1 //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains some templates that are useful if you are working with the
13 // No library is required when using these functions.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_ADT_STLEXTRAS_H
18 #define LLVM_ADT_STLEXTRAS_H
20 #include "llvm/Support/Compiler.h"
22 #include <cstddef> // for std::size_t
23 #include <cstdlib> // for qsort
27 #include <utility> // for std::pair
31 //===----------------------------------------------------------------------===//
32 // Extra additions to <functional>
33 //===----------------------------------------------------------------------===//
36 struct identity : public std::unary_function<Ty, Ty> {
37 Ty &operator()(Ty &self) const {
40 const Ty &operator()(const Ty &self) const {
46 struct less_ptr : public std::binary_function<Ty, Ty, bool> {
47 bool operator()(const Ty* left, const Ty* right) const {
48 return *left < *right;
53 struct greater_ptr : public std::binary_function<Ty, Ty, bool> {
54 bool operator()(const Ty* left, const Ty* right) const {
55 return *right < *left;
59 /// An efficient, type-erasing, non-owning reference to a callable. This is
60 /// intended for use as the type of a function parameter that is not used
61 /// after the function in question returns.
63 /// This class does not own the callable, so it is not in general safe to store
65 template<typename Fn> class function_ref;
67 template<typename Ret, typename ...Params>
68 class function_ref<Ret(Params...)> {
69 Ret (*callback)(intptr_t callable, Params ...params);
72 template<typename Callable>
73 static Ret callback_fn(intptr_t callable, Params ...params) {
74 return (*reinterpret_cast<Callable*>(callable))(
75 std::forward<Params>(params)...);
79 template <typename Callable>
80 function_ref(Callable &&callable,
81 typename std::enable_if<
82 !std::is_same<typename std::remove_reference<Callable>::type,
83 function_ref>::value>::type * = nullptr)
84 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
85 callable(reinterpret_cast<intptr_t>(&callable)) {}
86 Ret operator()(Params ...params) const {
87 return callback(callable, std::forward<Params>(params)...);
91 // deleter - Very very very simple method that is used to invoke operator
92 // delete on something. It is used like this:
94 // for_each(V.begin(), B.end(), deleter<Interval>);
97 inline void deleter(T *Ptr) {
103 //===----------------------------------------------------------------------===//
104 // Extra additions to <iterator>
105 //===----------------------------------------------------------------------===//
107 // mapped_iterator - This is a simple iterator adapter that causes a function to
108 // be dereferenced whenever operator* is invoked on the iterator.
110 template <class RootIt, class UnaryFunc>
111 class mapped_iterator {
115 typedef typename std::iterator_traits<RootIt>::iterator_category
117 typedef typename std::iterator_traits<RootIt>::difference_type
119 typedef typename UnaryFunc::result_type value_type;
121 typedef void pointer;
122 //typedef typename UnaryFunc::result_type *pointer;
123 typedef void reference; // Can't modify value returned by fn
125 typedef RootIt iterator_type;
126 typedef mapped_iterator<RootIt, UnaryFunc> _Self;
128 inline const RootIt &getCurrent() const { return current; }
129 inline const UnaryFunc &getFunc() const { return Fn; }
131 inline explicit mapped_iterator(const RootIt &I, UnaryFunc F)
132 : current(I), Fn(F) {}
134 inline value_type operator*() const { // All this work to do this
135 return Fn(*current); // little change
138 _Self& operator++() { ++current; return *this; }
139 _Self& operator--() { --current; return *this; }
140 _Self operator++(int) { _Self __tmp = *this; ++current; return __tmp; }
141 _Self operator--(int) { _Self __tmp = *this; --current; return __tmp; }
142 _Self operator+ (difference_type n) const {
143 return _Self(current + n, Fn);
145 _Self& operator+= (difference_type n) { current += n; return *this; }
146 _Self operator- (difference_type n) const {
147 return _Self(current - n, Fn);
149 _Self& operator-= (difference_type n) { current -= n; return *this; }
150 reference operator[](difference_type n) const { return *(*this + n); }
152 inline bool operator!=(const _Self &X) const { return !operator==(X); }
153 inline bool operator==(const _Self &X) const { return current == X.current; }
154 inline bool operator< (const _Self &X) const { return current < X.current; }
156 inline difference_type operator-(const _Self &X) const {
157 return current - X.current;
161 template <class _Iterator, class Func>
162 inline mapped_iterator<_Iterator, Func>
163 operator+(typename mapped_iterator<_Iterator, Func>::difference_type N,
164 const mapped_iterator<_Iterator, Func>& X) {
165 return mapped_iterator<_Iterator, Func>(X.getCurrent() - N, X.getFunc());
169 // map_iterator - Provide a convenient way to create mapped_iterators, just like
170 // make_pair is useful for creating pairs...
172 template <class ItTy, class FuncTy>
173 inline mapped_iterator<ItTy, FuncTy> map_iterator(const ItTy &I, FuncTy F) {
174 return mapped_iterator<ItTy, FuncTy>(I, F);
177 //===----------------------------------------------------------------------===//
178 // Extra additions to <utility>
179 //===----------------------------------------------------------------------===//
181 /// \brief Function object to check whether the first component of a std::pair
182 /// compares less than the first component of another std::pair.
184 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
185 return lhs.first < rhs.first;
189 /// \brief Function object to check whether the second component of a std::pair
190 /// compares less than the second component of another std::pair.
192 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
193 return lhs.second < rhs.second;
197 // A subset of N3658. More stuff can be added as-needed.
199 /// \brief Represents a compile-time sequence of integers.
200 template <class T, T... I> struct integer_sequence {
201 typedef T value_type;
203 static LLVM_CONSTEXPR size_t size() { return sizeof...(I); }
206 template <std::size_t N, std::size_t... I>
207 struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
208 template <std::size_t... I>
209 struct build_index_impl<0, I...> : integer_sequence<std::size_t, I...> {};
211 /// \brief Alias for the common case of a sequence of size_ts.
212 template <size_t... I>
213 using index_sequence = integer_sequence<std::size_t, I...>;
215 /// \brief Creates a compile-time integer sequence for a parameter pack.
216 template <class... Ts>
217 using index_sequence_for = build_index_impl<sizeof...(Ts)>;
219 //===----------------------------------------------------------------------===//
220 // Extra additions for arrays
221 //===----------------------------------------------------------------------===//
223 /// Find the length of an array.
224 template <class T, std::size_t N>
225 LLVM_CONSTEXPR inline size_t array_lengthof(T (&)[N]) {
229 /// Adapt std::less<T> for array_pod_sort.
231 inline int array_pod_sort_comparator(const void *P1, const void *P2) {
232 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
233 *reinterpret_cast<const T*>(P2)))
235 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
236 *reinterpret_cast<const T*>(P1)))
241 /// get_array_pod_sort_comparator - This is an internal helper function used to
242 /// get type deduction of T right.
244 inline int (*get_array_pod_sort_comparator(const T &))
245 (const void*, const void*) {
246 return array_pod_sort_comparator<T>;
250 /// array_pod_sort - This sorts an array with the specified start and end
251 /// extent. This is just like std::sort, except that it calls qsort instead of
252 /// using an inlined template. qsort is slightly slower than std::sort, but
253 /// most sorts are not performance critical in LLVM and std::sort has to be
254 /// template instantiated for each type, leading to significant measured code
255 /// bloat. This function should generally be used instead of std::sort where
258 /// This function assumes that you have simple POD-like types that can be
259 /// compared with std::less and can be moved with memcpy. If this isn't true,
260 /// you should use std::sort.
262 /// NOTE: If qsort_r were portable, we could allow a custom comparator and
263 /// default to std::less.
264 template<class IteratorTy>
265 inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
266 // Don't dereference start iterator of empty sequence.
267 if (Start == End) return;
268 qsort(&*Start, End-Start, sizeof(*Start),
269 get_array_pod_sort_comparator(*Start));
272 template <class IteratorTy>
273 inline void array_pod_sort(
274 IteratorTy Start, IteratorTy End,
276 const typename std::iterator_traits<IteratorTy>::value_type *,
277 const typename std::iterator_traits<IteratorTy>::value_type *)) {
278 // Don't dereference start iterator of empty sequence.
279 if (Start == End) return;
280 qsort(&*Start, End - Start, sizeof(*Start),
281 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
284 //===----------------------------------------------------------------------===//
285 // Extra additions to <algorithm>
286 //===----------------------------------------------------------------------===//
288 /// For a container of pointers, deletes the pointers and then clears the
290 template<typename Container>
291 void DeleteContainerPointers(Container &C) {
292 for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
297 /// In a container of pairs (usually a map) whose second element is a pointer,
298 /// deletes the second elements and then clears the container.
299 template<typename Container>
300 void DeleteContainerSeconds(Container &C) {
301 for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
306 //===----------------------------------------------------------------------===//
307 // Extra additions to <memory>
308 //===----------------------------------------------------------------------===//
310 // Implement make_unique according to N3656.
312 /// \brief Constructs a `new T()` with the given args and returns a
313 /// `unique_ptr<T>` which owns the object.
317 /// auto p = make_unique<int>();
318 /// auto p = make_unique<std::tuple<int, int>>(0, 1);
319 template <class T, class... Args>
320 typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
321 make_unique(Args &&... args) {
322 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
325 /// \brief Constructs a `new T[n]` with the given args and returns a
326 /// `unique_ptr<T[]>` which owns the object.
328 /// \param n size of the new array.
332 /// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
334 typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
335 std::unique_ptr<T>>::type
336 make_unique(size_t n) {
337 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
340 /// This function isn't used and is only here to provide better compile errors.
341 template <class T, class... Args>
342 typename std::enable_if<std::extent<T>::value != 0>::type
343 make_unique(Args &&...) = delete;
346 void operator()(void* v) {
351 template<typename First, typename Second>
353 size_t operator()(const std::pair<First, Second> &P) const {
354 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
358 /// A functor like C++14's std::less<void> in its absence.
360 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
361 return std::forward<A>(a) < std::forward<B>(b);
365 /// A functor like C++14's std::equal<void> in its absence.
367 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
368 return std::forward<A>(a) == std::forward<B>(b);
372 /// Binary functor that adapts to any other binary functor after dereferencing
374 template <typename T> struct deref {
376 // Could be further improved to cope with non-derivable functors and
377 // non-binary functors (should be a variadic template member function
379 template <typename A, typename B>
380 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
383 return func(*lhs, *rhs);
387 } // End llvm namespace