1 //===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the PointerUnion class, which is a discriminated union of
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_POINTERUNION_H
15 #define LLVM_ADT_POINTERUNION_H
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/ADT/PointerIntPair.h"
19 #include "llvm/Support/PointerLikeTypeTraits.h"
26 template <typename T
> struct PointerUnionTypeSelectorReturn
{
30 /// Get a type based on whether two types are the same or not.
35 /// using Ret = typename PointerUnionTypeSelector<T1, T2, EQ, NE>::Return;
38 /// Ret will be EQ type if T1 is same as T2 or NE type otherwise.
39 template <typename T1
, typename T2
, typename RET_EQ
, typename RET_NE
>
40 struct PointerUnionTypeSelector
{
41 using Return
= typename PointerUnionTypeSelectorReturn
<RET_NE
>::Return
;
44 template <typename T
, typename RET_EQ
, typename RET_NE
>
45 struct PointerUnionTypeSelector
<T
, T
, RET_EQ
, RET_NE
> {
46 using Return
= typename PointerUnionTypeSelectorReturn
<RET_EQ
>::Return
;
49 template <typename T1
, typename T2
, typename RET_EQ
, typename RET_NE
>
50 struct PointerUnionTypeSelectorReturn
<
51 PointerUnionTypeSelector
<T1
, T2
, RET_EQ
, RET_NE
>> {
53 typename PointerUnionTypeSelector
<T1
, T2
, RET_EQ
, RET_NE
>::Return
;
56 namespace pointer_union_detail
{
57 /// Determine the number of bits required to store integers with values < n.
58 /// This is ceil(log2(n)).
59 constexpr int bitsRequired(unsigned n
) {
60 return n
> 1 ? 1 + bitsRequired((n
+ 1) / 2) : 0;
63 template <typename
... Ts
> constexpr int lowBitsAvailable() {
64 return std::min
<int>({PointerLikeTypeTraits
<Ts
>::NumLowBitsAvailable
...});
67 /// Find the index of a type in a list of types. TypeIndex<T, Us...>::Index
68 /// is the index of T in Us, or sizeof...(Us) if T does not appear in the
70 template <typename T
, typename
...Us
> struct TypeIndex
;
71 template <typename T
, typename
...Us
> struct TypeIndex
<T
, T
, Us
...> {
72 static constexpr int Index
= 0;
74 template <typename T
, typename U
, typename
... Us
>
75 struct TypeIndex
<T
, U
, Us
...> {
76 static constexpr int Index
= 1 + TypeIndex
<T
, Us
...>::Index
;
78 template <typename T
> struct TypeIndex
<T
> {
79 static constexpr int Index
= 0;
82 /// Find the first type in a list of types.
83 template <typename T
, typename
...> struct GetFirstType
{
87 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
88 /// for the template arguments.
89 template <typename
...PTs
> class PointerUnionUIntTraits
{
91 static inline void *getAsVoidPointer(void *P
) { return P
; }
92 static inline void *getFromVoidPointer(void *P
) { return P
; }
93 static constexpr int NumLowBitsAvailable
= lowBitsAvailable
<PTs
...>();
96 /// Implement assigment in terms of construction.
97 template <typename Derived
, typename T
> struct AssignableFrom
{
98 Derived
&operator=(T t
) {
99 return static_cast<Derived
&>(*this) = Derived(t
);
103 template <typename Derived
, typename ValTy
, int I
, typename
...Types
>
104 class PointerUnionMembers
;
106 template <typename Derived
, typename ValTy
, int I
>
107 class PointerUnionMembers
<Derived
, ValTy
, I
> {
110 PointerUnionMembers() = default;
111 PointerUnionMembers(ValTy Val
) : Val(Val
) {}
113 friend struct PointerLikeTypeTraits
<Derived
>;
116 template <typename Derived
, typename ValTy
, int I
, typename Type
,
118 class PointerUnionMembers
<Derived
, ValTy
, I
, Type
, Types
...>
119 : public PointerUnionMembers
<Derived
, ValTy
, I
+ 1, Types
...> {
120 using Base
= PointerUnionMembers
<Derived
, ValTy
, I
+ 1, Types
...>;
123 PointerUnionMembers() = default;
124 PointerUnionMembers(Type V
)
125 : Base(ValTy(const_cast<void *>(
126 PointerLikeTypeTraits
<Type
>::getAsVoidPointer(V
)),
129 using Base::operator=;
130 Derived
&operator=(Type V
) {
132 const_cast<void *>(PointerLikeTypeTraits
<Type
>::getAsVoidPointer(V
)),
134 return static_cast<Derived
&>(*this);
139 /// A discriminated union of two or more pointer types, with the discriminator
140 /// in the low bit of the pointer.
142 /// This implementation is extremely efficient in space due to leveraging the
143 /// low bits of the pointer, while exposing a natural and type-safe API.
145 /// Common use patterns would be something like this:
146 /// PointerUnion<int*, float*> P;
148 /// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
149 /// X = P.get<int*>(); // ok.
150 /// Y = P.get<float*>(); // runtime assertion failure.
151 /// Z = P.get<double*>(); // compile time failure.
153 /// Y = P.get<float*>(); // ok.
154 /// X = P.get<int*>(); // runtime assertion failure.
155 template <typename
... PTs
>
157 : public pointer_union_detail::PointerUnionMembers
<
158 PointerUnion
<PTs
...>,
160 void *, pointer_union_detail::bitsRequired(sizeof...(PTs
)), int,
161 pointer_union_detail::PointerUnionUIntTraits
<PTs
...>>,
163 // The first type is special because we want to directly cast a pointer to a
164 // default-initialized union to a pointer to the first type. But we don't
165 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
166 // because it's much more convenient to have a name for the whole pack. So
167 // split off the first type here.
168 using First
= typename
pointer_union_detail::GetFirstType
<PTs
...>::type
;
169 using Base
= typename
PointerUnion::PointerUnionMembers
;
172 PointerUnion() = default;
174 PointerUnion(std::nullptr_t
) : PointerUnion() {}
177 /// Test if the pointer held in the union is null, regardless of
178 /// which type it is.
179 bool isNull() const { return !this->Val
.getPointer(); }
181 explicit operator bool() const { return !isNull(); }
183 /// Test if the Union currently holds the type matching T.
184 template <typename T
> int is() const {
185 constexpr int Index
= pointer_union_detail::TypeIndex
<T
, PTs
...>::Index
;
186 static_assert(Index
< sizeof...(PTs
),
187 "PointerUnion::is<T> given type not in the union");
188 return this->Val
.getInt() == Index
;
191 /// Returns the value of the specified pointer type.
193 /// If the specified pointer type is incorrect, assert.
194 template <typename T
> T
get() const {
195 assert(is
<T
>() && "Invalid accessor called");
196 return PointerLikeTypeTraits
<T
>::getFromVoidPointer(this->Val
.getPointer());
199 /// Returns the current pointer if it is of the specified pointer type,
200 /// otherwises returns null.
201 template <typename T
> T
dyn_cast() const {
207 /// If the union is set to the first pointer type get an address pointing to
209 First
const *getAddrOfPtr1() const {
210 return const_cast<PointerUnion
*>(this)->getAddrOfPtr1();
213 /// If the union is set to the first pointer type get an address pointing to
215 First
*getAddrOfPtr1() {
216 assert(is
<First
>() && "Val is not the first pointer");
218 PointerLikeTypeTraits
<First
>::getAsVoidPointer(get
<First
>()) ==
219 this->Val
.getPointer() &&
220 "Can't get the address because PointerLikeTypeTraits changes the ptr");
221 return const_cast<First
*>(
222 reinterpret_cast<const First
*>(this->Val
.getAddrOfPointer()));
225 /// Assignment from nullptr which just clears the union.
226 const PointerUnion
&operator=(std::nullptr_t
) {
227 this->Val
.initWithPointer(nullptr);
231 /// Assignment from elements of the union.
232 using Base::operator=;
234 void *getOpaqueValue() const { return this->Val
.getOpaqueValue(); }
235 static inline PointerUnion
getFromOpaqueValue(void *VP
) {
237 V
.Val
= decltype(V
.Val
)::getFromOpaqueValue(VP
);
242 template <typename
...PTs
>
243 bool operator==(PointerUnion
<PTs
...> lhs
, PointerUnion
<PTs
...> rhs
) {
244 return lhs
.getOpaqueValue() == rhs
.getOpaqueValue();
247 template <typename
...PTs
>
248 bool operator!=(PointerUnion
<PTs
...> lhs
, PointerUnion
<PTs
...> rhs
) {
249 return lhs
.getOpaqueValue() != rhs
.getOpaqueValue();
252 template <typename
...PTs
>
253 bool operator<(PointerUnion
<PTs
...> lhs
, PointerUnion
<PTs
...> rhs
) {
254 return lhs
.getOpaqueValue() < rhs
.getOpaqueValue();
257 // Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
258 // # low bits available = min(PT1bits,PT2bits)-1.
259 template <typename
...PTs
>
260 struct PointerLikeTypeTraits
<PointerUnion
<PTs
...>> {
261 static inline void *getAsVoidPointer(const PointerUnion
<PTs
...> &P
) {
262 return P
.getOpaqueValue();
265 static inline PointerUnion
<PTs
...> getFromVoidPointer(void *P
) {
266 return PointerUnion
<PTs
...>::getFromOpaqueValue(P
);
269 // The number of bits available are the min of the pointer types minus the
270 // bits needed for the discriminator.
271 static constexpr int NumLowBitsAvailable
= PointerLikeTypeTraits
<decltype(
272 PointerUnion
<PTs
...>::Val
)>::NumLowBitsAvailable
;
275 /// A pointer union of three pointer types. See documentation for PointerUnion
277 template <typename PT1
, typename PT2
, typename PT3
>
278 using PointerUnion3
= PointerUnion
<PT1
, PT2
, PT3
>;
280 /// A pointer union of four pointer types. See documentation for PointerUnion
282 template <typename PT1
, typename PT2
, typename PT3
, typename PT4
>
283 using PointerUnion4
= PointerUnion
<PT1
, PT2
, PT3
, PT4
>;
285 // Teach DenseMap how to use PointerUnions as keys.
286 template <typename
...PTs
> struct DenseMapInfo
<PointerUnion
<PTs
...>> {
287 using Union
= PointerUnion
<PTs
...>;
289 DenseMapInfo
<typename
pointer_union_detail::GetFirstType
<PTs
...>::type
>;
291 static inline Union
getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
293 static inline Union
getTombstoneKey() {
294 return Union(FirstInfo::getTombstoneKey());
297 static unsigned getHashValue(const Union
&UnionVal
) {
298 intptr_t key
= (intptr_t)UnionVal
.getOpaqueValue();
299 return DenseMapInfo
<intptr_t>::getHashValue(key
);
302 static bool isEqual(const Union
&LHS
, const Union
&RHS
) {
307 } // end namespace llvm
309 #endif // LLVM_ADT_POINTERUNION_H