WPILibC++ 2023.4.3
PointerUnion.h
Go to the documentation of this file.
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/// \file
10/// This file defines the PointerUnion class, which is a discriminated union of
11/// pointer types.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef WPIUTIL_WPI_POINTERUNION_H
16#define WPIUTIL_WPI_POINTERUNION_H
17
18#include "wpi/DenseMapInfo.h"
19#include "wpi/PointerIntPair.h"
21#include <algorithm>
22#include <cassert>
23#include <cstddef>
24#include <cstdint>
25#include <type_traits>
26
27namespace wpi {
28
29namespace detail {
30template <typename T, typename... Us> struct TypesAreDistinct;
31template <typename T, typename... Us>
33 : std::integral_constant<bool, !std::disjunction_v<std::is_same<T, Us>...> &&
34 TypesAreDistinct<Us...>::value> {};
35template <typename T> struct TypesAreDistinct<T> : std::true_type {};
36} // namespace detail
37
38/// Determine if all types in Ts are distinct.
39///
40/// Useful to statically assert when Ts is intended to describe a non-multi set
41/// of types.
42///
43/// Expensive (currently quadratic in sizeof(Ts...)), and so should only be
44/// asserted once per instantiation of a type which requires it.
45template <typename... Ts> struct TypesAreDistinct;
46template <> struct TypesAreDistinct<> : std::true_type {};
47template <typename... Ts>
49 : std::integral_constant<bool, detail::TypesAreDistinct<Ts...>::value> {};
50
51/// Find the first index where a type appears in a list of types.
52///
53/// FirstIndexOfType<T, Us...>::value is the first index of T in Us.
54///
55/// Typically only meaningful when it is otherwise statically known that the
56/// type pack has no duplicate types. This should be guaranteed explicitly with
57/// static_assert(TypesAreDistinct<Us...>::value).
58///
59/// It is a compile-time error to instantiate when T is not present in Us, i.e.
60/// if is_one_of<T, Us...>::value is false.
61template <typename T, typename... Us> struct FirstIndexOfType;
62template <typename T, typename U, typename... Us>
63struct FirstIndexOfType<T, U, Us...>
64 : std::integral_constant<size_t, 1 + FirstIndexOfType<T, Us...>::value> {};
65template <typename T, typename... Us>
66struct FirstIndexOfType<T, T, Us...> : std::integral_constant<size_t, 0> {};
67
68/// Find the type at a given index in a list of types.
69///
70/// TypeAtIndex<I, Ts...> is the type at index I in Ts.
71template <size_t I, typename... Ts>
72using TypeAtIndex = std::tuple_element_t<I, std::tuple<Ts...>>;
73
74namespace pointer_union_detail {
75 /// Determine the number of bits required to store integers with values < n.
76 /// This is ceil(log2(n)).
77 constexpr int bitsRequired(unsigned n) {
78 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
79 }
80
81 template <typename... Ts> constexpr int lowBitsAvailable() {
82 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
83 }
84
85 /// Find the first type in a list of types.
86 template <typename T, typename...> struct GetFirstType {
87 using type = T;
88 };
89
90 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
91 /// for the template arguments.
92 template <typename ...PTs> class PointerUnionUIntTraits {
93 public:
94 static inline void *getAsVoidPointer(void *P) { return P; }
95 static inline void *getFromVoidPointer(void *P) { return P; }
96 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
97 };
98
99 template <typename Derived, typename ValTy, int I, typename ...Types>
101
102 template <typename Derived, typename ValTy, int I>
103 class PointerUnionMembers<Derived, ValTy, I> {
104 protected:
105 ValTy Val;
107 PointerUnionMembers(ValTy Val) : Val(Val) {}
108
109 friend struct PointerLikeTypeTraits<Derived>;
110 };
111
112 template <typename Derived, typename ValTy, int I, typename Type,
113 typename ...Types>
114 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
115 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
116 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
117 public:
118 using Base::Base;
121 : Base(ValTy(const_cast<void *>(
122 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
123 I)) {}
124
125 using Base::operator=;
126 Derived &operator=(Type V) {
127 this->Val = ValTy(
129 I);
130 return static_cast<Derived &>(*this);
131 };
132 };
133}
134
135/// A discriminated union of two or more pointer types, with the discriminator
136/// in the low bit of the pointer.
137///
138/// This implementation is extremely efficient in space due to leveraging the
139/// low bits of the pointer, while exposing a natural and type-safe API.
140///
141/// Common use patterns would be something like this:
142/// PointerUnion<int*, float*> P;
143/// P = (int*)0;
144/// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
145/// X = P.get<int*>(); // ok.
146/// Y = P.get<float*>(); // runtime assertion failure.
147/// Z = P.get<double*>(); // compile time failure.
148/// P = (float*)0;
149/// Y = P.get<float*>(); // ok.
150/// X = P.get<int*>(); // runtime assertion failure.
151/// PointerUnion<int*, int*> Q; // compile time failure.
152template <typename... PTs>
155 PointerUnion<PTs...>,
156 PointerIntPair<
157 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
158 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
159 0, PTs...> {
160 static_assert(TypesAreDistinct<PTs...>::value,
161 "PointerUnion alternative types cannot be repeated");
162 // The first type is special because we want to directly cast a pointer to a
163 // default-initialized union to a pointer to the first type. But we don't
164 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
165 // because it's much more convenient to have a name for the whole pack. So
166 // split off the first type here.
167 using First = TypeAtIndex<0, PTs...>;
168 using Base = typename PointerUnion::PointerUnionMembers;
169
170public:
171 PointerUnion() = default;
172
173 PointerUnion(std::nullptr_t) : PointerUnion() {}
174 using Base::Base;
175
176 /// Test if the pointer held in the union is null, regardless of
177 /// which type it is.
178 bool isNull() const { return !this->Val.getPointer(); }
179
180 explicit operator bool() const { return !isNull(); }
181
182 /// Test if the Union currently holds the type matching T.
183 template <typename T> bool is() const {
184 return this->Val.getInt() == FirstIndexOfType<T, PTs...>::value;
185 }
186
187 /// Returns the value of the specified pointer type.
188 ///
189 /// If the specified pointer type is incorrect, assert.
190 template <typename T> T get() const {
191 assert(is<T>() && "Invalid accessor called");
192 return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer());
193 }
194
195 /// Returns the current pointer if it is of the specified pointer type,
196 /// otherwise returns null.
197 template <typename T> T dyn_cast() const {
198 if (is<T>())
199 return get<T>();
200 return T();
201 }
202
203 /// If the union is set to the first pointer type get an address pointing to
204 /// it.
205 First const *getAddrOfPtr1() const {
206 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
207 }
208
209 /// If the union is set to the first pointer type get an address pointing to
210 /// it.
211 First *getAddrOfPtr1() {
212 assert(is<First>() && "Val is not the first pointer");
213 assert(
215 this->Val.getPointer() &&
216 "Can't get the address because PointerLikeTypeTraits changes the ptr");
217 return const_cast<First *>(
218 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
219 }
220
221 /// Assignment from nullptr which just clears the union.
222 const PointerUnion &operator=(std::nullptr_t) {
223 this->Val.initWithPointer(nullptr);
224 return *this;
225 }
226
227 /// Assignment from elements of the union.
228 using Base::operator=;
229
230 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
231 static inline PointerUnion getFromOpaqueValue(void *VP) {
232 PointerUnion V;
233 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
234 return V;
235 }
236};
237
238template <typename ...PTs>
240 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
241}
242
243template <typename ...PTs>
245 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
246}
247
248template <typename ...PTs>
250 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
251}
252
253// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
254// # low bits available = min(PT1bits,PT2bits)-1.
255template <typename ...PTs>
257 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
258 return P.getOpaqueValue();
259 }
260
261 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
263 }
264
265 // The number of bits available are the min of the pointer types minus the
266 // bits needed for the discriminator.
267 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
268 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
269};
270
271// Teach DenseMap how to use PointerUnions as keys.
272template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
273 using Union = PointerUnion<PTs...>;
274 using FirstInfo =
276
277 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
278
279 static inline Union getTombstoneKey() {
280 return Union(FirstInfo::getTombstoneKey());
281 }
282
283 static unsigned getHashValue(const Union &UnionVal) {
284 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
286 }
287
288 static bool isEqual(const Union &LHS, const Union &RHS) {
289 return LHS == RHS;
290 }
291};
292
293} // end namespace wpi
294
295#endif // WPIUTIL_WPI_POINTERUNION_H
This file defines DenseMapInfo traits for DenseMap.
This file defines the PointerIntPair class.
Definition: core.h:1240
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
Definition: PointerUnion.h:159
static PointerUnion getFromOpaqueValue(void *VP)
Definition: PointerUnion.h:231
PointerUnion()=default
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwise returns null.
Definition: PointerUnion.h:197
void * getOpaqueValue() const
Definition: PointerUnion.h:230
First * getAddrOfPtr1()
If the union is set to the first pointer type get an address pointing to it.
Definition: PointerUnion.h:211
PointerUnion(std::nullptr_t)
Definition: PointerUnion.h:173
First const * getAddrOfPtr1() const
If the union is set to the first pointer type get an address pointing to it.
Definition: PointerUnion.h:205
const PointerUnion & operator=(std::nullptr_t)
Assignment from nullptr which just clears the union.
Definition: PointerUnion.h:222
T get() const
Returns the value of the specified pointer type.
Definition: PointerUnion.h:190
bool isNull() const
Test if the pointer held in the union is null, regardless of which type it is.
Definition: PointerUnion.h:178
bool is() const
Test if the Union currently holds the type matching T.
Definition: PointerUnion.h:183
Provide PointerLikeTypeTraits for void* that is used by PointerUnion for the template arguments.
Definition: PointerUnion.h:92
static constexpr int NumLowBitsAvailable
Definition: PointerUnion.h:96
static void * getAsVoidPointer(void *P)
Definition: PointerUnion.h:94
static void * getFromVoidPointer(void *P)
Definition: PointerUnion.h:95
type
Definition: core.h:575
Type
Definition: Constants.h:471
Definition: chrono.h:303
constexpr int lowBitsAvailable()
Definition: PointerUnion.h:81
constexpr int bitsRequired(unsigned n)
Determine the number of bits required to store integers with values < n.
Definition: PointerUnion.h:77
/file This file defines the SmallVector class.
Definition: AprilTagFieldLayout.h:18
bool operator!=(PointerUnion< PTs... > lhs, PointerUnion< PTs... > rhs)
Definition: PointerUnion.h:244
std::tuple_element_t< I, std::tuple< Ts... > > TypeAtIndex
Find the type at a given index in a list of types.
Definition: PointerUnion.h:72
bool operator==(PointerUnion< PTs... > lhs, PointerUnion< PTs... > rhs)
Definition: PointerUnion.h:239
bool operator<(PointerUnion< PTs... > lhs, PointerUnion< PTs... > rhs)
Definition: PointerUnion.h:249
static Union getTombstoneKey()
Definition: PointerUnion.h:279
static unsigned getHashValue(const Union &UnionVal)
Definition: PointerUnion.h:283
static bool isEqual(const Union &LHS, const Union &RHS)
Definition: PointerUnion.h:288
static Union getEmptyKey()
Definition: PointerUnion.h:277
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:49
Find the first index where a type appears in a list of types.
Definition: PointerUnion.h:61
static PointerUnion< PTs... > getFromVoidPointer(void *P)
Definition: PointerUnion.h:261
static void * getAsVoidPointer(const PointerUnion< PTs... > &P)
Definition: PointerUnion.h:257
A traits type that is used to handle pointer types and things that are just wrappers for pointers as ...
Definition: PointerLikeTypeTraits.h:25
Determine if all types in Ts are distinct.
Definition: PointerUnion.h:49
Definition: PointerUnion.h:34
Find the first type in a list of types.
Definition: PointerUnion.h:86
T type
Definition: PointerUnion.h:87