blob: 03109a078ed3d232ab677f3739775934ca6a09b8 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains some templates that are useful if you are working with the
11// STL at all.
12//
13// No library is required when using these functions.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_ADT_STLEXTRAS_H
18#define LLVM_ADT_STLEXTRAS_H
19
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
Andrew Scullcdfcccc2018-10-05 20:58:37 +010024#include "llvm/Config/abi-breaking.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010025#include "llvm/Support/ErrorHandling.h"
26#include <algorithm>
27#include <cassert>
28#include <cstddef>
29#include <cstdint>
30#include <cstdlib>
31#include <functional>
32#include <initializer_list>
33#include <iterator>
34#include <limits>
35#include <memory>
36#include <tuple>
37#include <type_traits>
38#include <utility>
39
40#ifdef EXPENSIVE_CHECKS
41#include <random> // for std::mt19937
42#endif
43
44namespace llvm {
45
46// Only used by compiler if both template types are the same. Useful when
47// using SFINAE to test for the existence of member functions.
48template <typename T, T> struct SameType;
49
50namespace detail {
51
52template <typename RangeT>
53using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
54
55template <typename RangeT>
56using ValueOfRange = typename std::remove_reference<decltype(
57 *std::begin(std::declval<RangeT &>()))>::type;
58
59} // end namespace detail
60
61//===----------------------------------------------------------------------===//
Andrew Scullcdfcccc2018-10-05 20:58:37 +010062// Extra additions to <type_traits>
63//===----------------------------------------------------------------------===//
64
65template <typename T>
66struct negation : std::integral_constant<bool, !bool(T::value)> {};
67
68template <typename...> struct conjunction : std::true_type {};
69template <typename B1> struct conjunction<B1> : B1 {};
70template <typename B1, typename... Bn>
71struct conjunction<B1, Bn...>
72 : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
73
74//===----------------------------------------------------------------------===//
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010075// Extra additions to <functional>
76//===----------------------------------------------------------------------===//
77
78template <class Ty> struct identity {
79 using argument_type = Ty;
80
81 Ty &operator()(Ty &self) const {
82 return self;
83 }
84 const Ty &operator()(const Ty &self) const {
85 return self;
86 }
87};
88
89template <class Ty> struct less_ptr {
90 bool operator()(const Ty* left, const Ty* right) const {
91 return *left < *right;
92 }
93};
94
95template <class Ty> struct greater_ptr {
96 bool operator()(const Ty* left, const Ty* right) const {
97 return *right < *left;
98 }
99};
100
101/// An efficient, type-erasing, non-owning reference to a callable. This is
102/// intended for use as the type of a function parameter that is not used
103/// after the function in question returns.
104///
105/// This class does not own the callable, so it is not in general safe to store
106/// a function_ref.
107template<typename Fn> class function_ref;
108
109template<typename Ret, typename ...Params>
110class function_ref<Ret(Params...)> {
111 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
112 intptr_t callable;
113
114 template<typename Callable>
115 static Ret callback_fn(intptr_t callable, Params ...params) {
116 return (*reinterpret_cast<Callable*>(callable))(
117 std::forward<Params>(params)...);
118 }
119
120public:
121 function_ref() = default;
122 function_ref(std::nullptr_t) {}
123
124 template <typename Callable>
125 function_ref(Callable &&callable,
126 typename std::enable_if<
127 !std::is_same<typename std::remove_reference<Callable>::type,
128 function_ref>::value>::type * = nullptr)
129 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
130 callable(reinterpret_cast<intptr_t>(&callable)) {}
131
132 Ret operator()(Params ...params) const {
133 return callback(callable, std::forward<Params>(params)...);
134 }
135
136 operator bool() const { return callback; }
137};
138
139// deleter - Very very very simple method that is used to invoke operator
140// delete on something. It is used like this:
141//
142// for_each(V.begin(), B.end(), deleter<Interval>);
143template <class T>
144inline void deleter(T *Ptr) {
145 delete Ptr;
146}
147
148//===----------------------------------------------------------------------===//
149// Extra additions to <iterator>
150//===----------------------------------------------------------------------===//
151
152namespace adl_detail {
153
154using std::begin;
155
156template <typename ContainerTy>
157auto adl_begin(ContainerTy &&container)
158 -> decltype(begin(std::forward<ContainerTy>(container))) {
159 return begin(std::forward<ContainerTy>(container));
160}
161
162using std::end;
163
164template <typename ContainerTy>
165auto adl_end(ContainerTy &&container)
166 -> decltype(end(std::forward<ContainerTy>(container))) {
167 return end(std::forward<ContainerTy>(container));
168}
169
170using std::swap;
171
172template <typename T>
173void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
174 std::declval<T>()))) {
175 swap(std::forward<T>(lhs), std::forward<T>(rhs));
176}
177
178} // end namespace adl_detail
179
180template <typename ContainerTy>
181auto adl_begin(ContainerTy &&container)
182 -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) {
183 return adl_detail::adl_begin(std::forward<ContainerTy>(container));
184}
185
186template <typename ContainerTy>
187auto adl_end(ContainerTy &&container)
188 -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) {
189 return adl_detail::adl_end(std::forward<ContainerTy>(container));
190}
191
192template <typename T>
193void adl_swap(T &&lhs, T &&rhs) noexcept(
194 noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
195 adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
196}
197
198// mapped_iterator - This is a simple iterator adapter that causes a function to
199// be applied whenever operator* is invoked on the iterator.
200
201template <typename ItTy, typename FuncTy,
202 typename FuncReturnTy =
203 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
204class mapped_iterator
205 : public iterator_adaptor_base<
206 mapped_iterator<ItTy, FuncTy>, ItTy,
207 typename std::iterator_traits<ItTy>::iterator_category,
208 typename std::remove_reference<FuncReturnTy>::type> {
209public:
210 mapped_iterator(ItTy U, FuncTy F)
211 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
212
213 ItTy getCurrent() { return this->I; }
214
215 FuncReturnTy operator*() { return F(*this->I); }
216
217private:
218 FuncTy F;
219};
220
221// map_iterator - Provide a convenient way to create mapped_iterators, just like
222// make_pair is useful for creating pairs...
223template <class ItTy, class FuncTy>
224inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
225 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
226}
227
228/// Helper to determine if type T has a member called rbegin().
229template <typename Ty> class has_rbegin_impl {
230 using yes = char[1];
231 using no = char[2];
232
233 template <typename Inner>
234 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
235
236 template <typename>
237 static no& test(...);
238
239public:
240 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
241};
242
243/// Metafunction to determine if T& or T has a member called rbegin().
244template <typename Ty>
245struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
246};
247
248// Returns an iterator_range over the given container which iterates in reverse.
249// Note that the container must have rbegin()/rend() methods for this to work.
250template <typename ContainerTy>
251auto reverse(ContainerTy &&C,
252 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
253 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
254 return make_range(C.rbegin(), C.rend());
255}
256
257// Returns a std::reverse_iterator wrapped around the given iterator.
258template <typename IteratorTy>
259std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
260 return std::reverse_iterator<IteratorTy>(It);
261}
262
263// Returns an iterator_range over the given container which iterates in reverse.
264// Note that the container must have begin()/end() methods which return
265// bidirectional iterators for this to work.
266template <typename ContainerTy>
267auto reverse(
268 ContainerTy &&C,
269 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
270 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
271 llvm::make_reverse_iterator(std::begin(C)))) {
272 return make_range(llvm::make_reverse_iterator(std::end(C)),
273 llvm::make_reverse_iterator(std::begin(C)));
274}
275
276/// An iterator adaptor that filters the elements of given inner iterators.
277///
278/// The predicate parameter should be a callable object that accepts the wrapped
279/// iterator's reference type and returns a bool. When incrementing or
280/// decrementing the iterator, it will call the predicate on each element and
281/// skip any where it returns false.
282///
283/// \code
284/// int A[] = { 1, 2, 3, 4 };
285/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
286/// // R contains { 1, 3 }.
287/// \endcode
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100288///
289/// Note: filter_iterator_base implements support for forward iteration.
290/// filter_iterator_impl exists to provide support for bidirectional iteration,
291/// conditional on whether the wrapped iterator supports it.
292template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
293class filter_iterator_base
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100294 : public iterator_adaptor_base<
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100295 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
296 WrappedIteratorT,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100297 typename std::common_type<
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100298 IterTag, typename std::iterator_traits<
299 WrappedIteratorT>::iterator_category>::type> {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100300 using BaseT = iterator_adaptor_base<
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100301 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
302 WrappedIteratorT,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100303 typename std::common_type<
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100304 IterTag, typename std::iterator_traits<
305 WrappedIteratorT>::iterator_category>::type>;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100306
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100307protected:
308 WrappedIteratorT End;
309 PredicateT Pred;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100310
311 void findNextValid() {
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100312 while (this->I != End && !Pred(*this->I))
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100313 BaseT::operator++();
314 }
315
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100316 // Construct the iterator. The begin iterator needs to know where the end
317 // is, so that it can properly stop when it gets there. The end iterator only
318 // needs the predicate to support bidirectional iteration.
319 filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End,
320 PredicateT Pred)
321 : BaseT(Begin), End(End), Pred(Pred) {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100322 findNextValid();
323 }
324
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100325public:
326 using BaseT::operator++;
327
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100328 filter_iterator_base &operator++() {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100329 BaseT::operator++();
330 findNextValid();
331 return *this;
332 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100333};
334
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100335/// Specialization of filter_iterator_base for forward iteration only.
336template <typename WrappedIteratorT, typename PredicateT,
337 typename IterTag = std::forward_iterator_tag>
338class filter_iterator_impl
339 : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
340 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>;
341
342public:
343 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
344 PredicateT Pred)
345 : BaseT(Begin, End, Pred) {}
346};
347
348/// Specialization of filter_iterator_base for bidirectional iteration.
349template <typename WrappedIteratorT, typename PredicateT>
350class filter_iterator_impl<WrappedIteratorT, PredicateT,
351 std::bidirectional_iterator_tag>
352 : public filter_iterator_base<WrappedIteratorT, PredicateT,
353 std::bidirectional_iterator_tag> {
354 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT,
355 std::bidirectional_iterator_tag>;
356 void findPrevValid() {
357 while (!this->Pred(*this->I))
358 BaseT::operator--();
359 }
360
361public:
362 using BaseT::operator--;
363
364 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
365 PredicateT Pred)
366 : BaseT(Begin, End, Pred) {}
367
368 filter_iterator_impl &operator--() {
369 BaseT::operator--();
370 findPrevValid();
371 return *this;
372 }
373};
374
375namespace detail {
376
377template <bool is_bidirectional> struct fwd_or_bidi_tag_impl {
378 using type = std::forward_iterator_tag;
379};
380
381template <> struct fwd_or_bidi_tag_impl<true> {
382 using type = std::bidirectional_iterator_tag;
383};
384
385/// Helper which sets its type member to forward_iterator_tag if the category
386/// of \p IterT does not derive from bidirectional_iterator_tag, and to
387/// bidirectional_iterator_tag otherwise.
388template <typename IterT> struct fwd_or_bidi_tag {
389 using type = typename fwd_or_bidi_tag_impl<std::is_base_of<
390 std::bidirectional_iterator_tag,
391 typename std::iterator_traits<IterT>::iterator_category>::value>::type;
392};
393
394} // namespace detail
395
396/// Defines filter_iterator to a suitable specialization of
397/// filter_iterator_impl, based on the underlying iterator's category.
398template <typename WrappedIteratorT, typename PredicateT>
399using filter_iterator = filter_iterator_impl<
400 WrappedIteratorT, PredicateT,
401 typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>;
402
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100403/// Convenience function that takes a range of elements and a predicate,
404/// and return a new filter_iterator range.
405///
406/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
407/// lifetime of that temporary is not kept by the returned range object, and the
408/// temporary is going to be dropped on the floor after the make_iterator_range
409/// full expression that contains this function call.
410template <typename RangeT, typename PredicateT>
411iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
412make_filter_range(RangeT &&Range, PredicateT Pred) {
413 using FilterIteratorT =
414 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100415 return make_range(
416 FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
417 std::end(std::forward<RangeT>(Range)), Pred),
418 FilterIteratorT(std::end(std::forward<RangeT>(Range)),
419 std::end(std::forward<RangeT>(Range)), Pred));
420}
421
422/// A pseudo-iterator adaptor that is designed to implement "early increment"
423/// style loops.
424///
425/// This is *not a normal iterator* and should almost never be used directly. It
426/// is intended primarily to be used with range based for loops and some range
427/// algorithms.
428///
429/// The iterator isn't quite an `OutputIterator` or an `InputIterator` but
430/// somewhere between them. The constraints of these iterators are:
431///
432/// - On construction or after being incremented, it is comparable and
433/// dereferencable. It is *not* incrementable.
434/// - After being dereferenced, it is neither comparable nor dereferencable, it
435/// is only incrementable.
436///
437/// This means you can only dereference the iterator once, and you can only
438/// increment it once between dereferences.
439template <typename WrappedIteratorT>
440class early_inc_iterator_impl
441 : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
442 WrappedIteratorT, std::input_iterator_tag> {
443 using BaseT =
444 iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
445 WrappedIteratorT, std::input_iterator_tag>;
446
447 using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer;
448
449protected:
450#if LLVM_ENABLE_ABI_BREAKING_CHECKS
451 bool IsEarlyIncremented = false;
452#endif
453
454public:
455 early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {}
456
457 using BaseT::operator*;
458 typename BaseT::reference operator*() {
459#if LLVM_ENABLE_ABI_BREAKING_CHECKS
460 assert(!IsEarlyIncremented && "Cannot dereference twice!");
461 IsEarlyIncremented = true;
462#endif
463 return *(this->I)++;
464 }
465
466 using BaseT::operator++;
467 early_inc_iterator_impl &operator++() {
468#if LLVM_ENABLE_ABI_BREAKING_CHECKS
469 assert(IsEarlyIncremented && "Cannot increment before dereferencing!");
470 IsEarlyIncremented = false;
471#endif
472 return *this;
473 }
474
475 using BaseT::operator==;
476 bool operator==(const early_inc_iterator_impl &RHS) const {
477#if LLVM_ENABLE_ABI_BREAKING_CHECKS
478 assert(!IsEarlyIncremented && "Cannot compare after dereferencing!");
479#endif
480 return BaseT::operator==(RHS);
481 }
482};
483
484/// Make a range that does early increment to allow mutation of the underlying
485/// range without disrupting iteration.
486///
487/// The underlying iterator will be incremented immediately after it is
488/// dereferenced, allowing deletion of the current node or insertion of nodes to
489/// not disrupt iteration provided they do not invalidate the *next* iterator --
490/// the current iterator can be invalidated.
491///
492/// This requires a very exact pattern of use that is only really suitable to
493/// range based for loops and other range algorithms that explicitly guarantee
494/// to dereference exactly once each element, and to increment exactly once each
495/// element.
496template <typename RangeT>
497iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>>
498make_early_inc_range(RangeT &&Range) {
499 using EarlyIncIteratorT =
500 early_inc_iterator_impl<detail::IterOfRange<RangeT>>;
501 return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))),
502 EarlyIncIteratorT(std::end(std::forward<RangeT>(Range))));
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100503}
504
505// forward declarations required by zip_shortest/zip_first
506template <typename R, typename UnaryPredicate>
507bool all_of(R &&range, UnaryPredicate P);
508
509template <size_t... I> struct index_sequence;
510
511template <class... Ts> struct index_sequence_for;
512
513namespace detail {
514
515using std::declval;
516
517// We have to alias this since inlining the actual type at the usage site
518// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
519template<typename... Iters> struct ZipTupleType {
520 using type = std::tuple<decltype(*declval<Iters>())...>;
521};
522
523template <typename ZipType, typename... Iters>
524using zip_traits = iterator_facade_base<
525 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
526 typename std::iterator_traits<
527 Iters>::iterator_category...>::type,
528 // ^ TODO: Implement random access methods.
529 typename ZipTupleType<Iters...>::type,
530 typename std::iterator_traits<typename std::tuple_element<
531 0, std::tuple<Iters...>>::type>::difference_type,
532 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
533 // inner iterators have the same difference_type. It would fail if, for
534 // instance, the second field's difference_type were non-numeric while the
535 // first is.
536 typename ZipTupleType<Iters...>::type *,
537 typename ZipTupleType<Iters...>::type>;
538
539template <typename ZipType, typename... Iters>
540struct zip_common : public zip_traits<ZipType, Iters...> {
541 using Base = zip_traits<ZipType, Iters...>;
542 using value_type = typename Base::value_type;
543
544 std::tuple<Iters...> iterators;
545
546protected:
547 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
548 return value_type(*std::get<Ns>(iterators)...);
549 }
550
551 template <size_t... Ns>
552 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
553 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
554 }
555
556 template <size_t... Ns>
557 decltype(iterators) tup_dec(index_sequence<Ns...>) const {
558 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
559 }
560
561public:
562 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
563
564 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
565
566 const value_type operator*() const {
567 return deref(index_sequence_for<Iters...>{});
568 }
569
570 ZipType &operator++() {
571 iterators = tup_inc(index_sequence_for<Iters...>{});
572 return *reinterpret_cast<ZipType *>(this);
573 }
574
575 ZipType &operator--() {
576 static_assert(Base::IsBidirectional,
577 "All inner iterators must be at least bidirectional.");
578 iterators = tup_dec(index_sequence_for<Iters...>{});
579 return *reinterpret_cast<ZipType *>(this);
580 }
581};
582
583template <typename... Iters>
584struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
585 using Base = zip_common<zip_first<Iters...>, Iters...>;
586
587 bool operator==(const zip_first<Iters...> &other) const {
588 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
589 }
590
591 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
592};
593
594template <typename... Iters>
595class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
596 template <size_t... Ns>
597 bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
598 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
599 std::get<Ns>(other.iterators)...},
600 identity<bool>{});
601 }
602
603public:
604 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
605
606 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
607
608 bool operator==(const zip_shortest<Iters...> &other) const {
609 return !test(other, index_sequence_for<Iters...>{});
610 }
611};
612
613template <template <typename...> class ItType, typename... Args> class zippy {
614public:
615 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
616 using iterator_category = typename iterator::iterator_category;
617 using value_type = typename iterator::value_type;
618 using difference_type = typename iterator::difference_type;
619 using pointer = typename iterator::pointer;
620 using reference = typename iterator::reference;
621
622private:
623 std::tuple<Args...> ts;
624
625 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
626 return iterator(std::begin(std::get<Ns>(ts))...);
627 }
628 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
629 return iterator(std::end(std::get<Ns>(ts))...);
630 }
631
632public:
633 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
634
635 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
636 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
637};
638
639} // end namespace detail
640
641/// zip iterator for two or more iteratable types.
642template <typename T, typename U, typename... Args>
643detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
644 Args &&... args) {
645 return detail::zippy<detail::zip_shortest, T, U, Args...>(
646 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
647}
648
649/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
650/// be the shortest.
651template <typename T, typename U, typename... Args>
652detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
653 Args &&... args) {
654 return detail::zippy<detail::zip_first, T, U, Args...>(
655 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
656}
657
658/// Iterator wrapper that concatenates sequences together.
659///
660/// This can concatenate different iterators, even with different types, into
661/// a single iterator provided the value types of all the concatenated
662/// iterators expose `reference` and `pointer` types that can be converted to
663/// `ValueT &` and `ValueT *` respectively. It doesn't support more
664/// interesting/customized pointer or reference types.
665///
666/// Currently this only supports forward or higher iterator categories as
667/// inputs and always exposes a forward iterator interface.
668template <typename ValueT, typename... IterTs>
669class concat_iterator
670 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
671 std::forward_iterator_tag, ValueT> {
672 using BaseT = typename concat_iterator::iterator_facade_base;
673
674 /// We store both the current and end iterators for each concatenated
675 /// sequence in a tuple of pairs.
676 ///
677 /// Note that something like iterator_range seems nice at first here, but the
678 /// range properties are of little benefit and end up getting in the way
679 /// because we need to do mutation on the current iterators.
680 std::tuple<std::pair<IterTs, IterTs>...> IterPairs;
681
682 /// Attempts to increment a specific iterator.
683 ///
684 /// Returns true if it was able to increment the iterator. Returns false if
685 /// the iterator is already at the end iterator.
686 template <size_t Index> bool incrementHelper() {
687 auto &IterPair = std::get<Index>(IterPairs);
688 if (IterPair.first == IterPair.second)
689 return false;
690
691 ++IterPair.first;
692 return true;
693 }
694
695 /// Increments the first non-end iterator.
696 ///
697 /// It is an error to call this with all iterators at the end.
698 template <size_t... Ns> void increment(index_sequence<Ns...>) {
699 // Build a sequence of functions to increment each iterator if possible.
700 bool (concat_iterator::*IncrementHelperFns[])() = {
701 &concat_iterator::incrementHelper<Ns>...};
702
703 // Loop over them, and stop as soon as we succeed at incrementing one.
704 for (auto &IncrementHelperFn : IncrementHelperFns)
705 if ((this->*IncrementHelperFn)())
706 return;
707
708 llvm_unreachable("Attempted to increment an end concat iterator!");
709 }
710
711 /// Returns null if the specified iterator is at the end. Otherwise,
712 /// dereferences the iterator and returns the address of the resulting
713 /// reference.
714 template <size_t Index> ValueT *getHelper() const {
715 auto &IterPair = std::get<Index>(IterPairs);
716 if (IterPair.first == IterPair.second)
717 return nullptr;
718
719 return &*IterPair.first;
720 }
721
722 /// Finds the first non-end iterator, dereferences, and returns the resulting
723 /// reference.
724 ///
725 /// It is an error to call this with all iterators at the end.
726 template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
727 // Build a sequence of functions to get from iterator if possible.
728 ValueT *(concat_iterator::*GetHelperFns[])() const = {
729 &concat_iterator::getHelper<Ns>...};
730
731 // Loop over them, and return the first result we find.
732 for (auto &GetHelperFn : GetHelperFns)
733 if (ValueT *P = (this->*GetHelperFn)())
734 return *P;
735
736 llvm_unreachable("Attempted to get a pointer from an end concat iterator!");
737 }
738
739public:
740 /// Constructs an iterator from a squence of ranges.
741 ///
742 /// We need the full range to know how to switch between each of the
743 /// iterators.
744 template <typename... RangeTs>
745 explicit concat_iterator(RangeTs &&... Ranges)
746 : IterPairs({std::begin(Ranges), std::end(Ranges)}...) {}
747
748 using BaseT::operator++;
749
750 concat_iterator &operator++() {
751 increment(index_sequence_for<IterTs...>());
752 return *this;
753 }
754
755 ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
756
757 bool operator==(const concat_iterator &RHS) const {
758 return IterPairs == RHS.IterPairs;
759 }
760};
761
762namespace detail {
763
764/// Helper to store a sequence of ranges being concatenated and access them.
765///
766/// This is designed to facilitate providing actual storage when temporaries
767/// are passed into the constructor such that we can use it as part of range
768/// based for loops.
769template <typename ValueT, typename... RangeTs> class concat_range {
770public:
771 using iterator =
772 concat_iterator<ValueT,
773 decltype(std::begin(std::declval<RangeTs &>()))...>;
774
775private:
776 std::tuple<RangeTs...> Ranges;
777
778 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
779 return iterator(std::get<Ns>(Ranges)...);
780 }
781 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
782 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
783 std::end(std::get<Ns>(Ranges)))...);
784 }
785
786public:
787 concat_range(RangeTs &&... Ranges)
788 : Ranges(std::forward<RangeTs>(Ranges)...) {}
789
790 iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
791 iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
792};
793
794} // end namespace detail
795
796/// Concatenated range across two or more ranges.
797///
798/// The desired value type must be explicitly specified.
799template <typename ValueT, typename... RangeTs>
800detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
801 static_assert(sizeof...(RangeTs) > 1,
802 "Need more than one range to concatenate!");
803 return detail::concat_range<ValueT, RangeTs...>(
804 std::forward<RangeTs>(Ranges)...);
805}
806
807//===----------------------------------------------------------------------===//
808// Extra additions to <utility>
809//===----------------------------------------------------------------------===//
810
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100811/// Function object to check whether the first component of a std::pair
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100812/// compares less than the first component of another std::pair.
813struct less_first {
814 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
815 return lhs.first < rhs.first;
816 }
817};
818
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100819/// Function object to check whether the second component of a std::pair
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100820/// compares less than the second component of another std::pair.
821struct less_second {
822 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
823 return lhs.second < rhs.second;
824 }
825};
826
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100827/// \brief Function object to apply a binary function to the first component of
828/// a std::pair.
829template<typename FuncTy>
830struct on_first {
831 FuncTy func;
832
833 template <typename T>
834 auto operator()(const T &lhs, const T &rhs) const
835 -> decltype(func(lhs.first, rhs.first)) {
836 return func(lhs.first, rhs.first);
837 }
838};
839
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100840// A subset of N3658. More stuff can be added as-needed.
841
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100842/// Represents a compile-time sequence of integers.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100843template <class T, T... I> struct integer_sequence {
844 using value_type = T;
845
846 static constexpr size_t size() { return sizeof...(I); }
847};
848
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100849/// Alias for the common case of a sequence of size_ts.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100850template <size_t... I>
851struct index_sequence : integer_sequence<std::size_t, I...> {};
852
853template <std::size_t N, std::size_t... I>
854struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
855template <std::size_t... I>
856struct build_index_impl<0, I...> : index_sequence<I...> {};
857
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100858/// Creates a compile-time integer sequence for a parameter pack.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100859template <class... Ts>
860struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
861
862/// Utility type to build an inheritance chain that makes it easy to rank
863/// overload candidates.
864template <int N> struct rank : rank<N - 1> {};
865template <> struct rank<0> {};
866
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100867/// traits class for checking whether type T is one of any of the given
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100868/// types in the variadic list.
869template <typename T, typename... Ts> struct is_one_of {
870 static const bool value = false;
871};
872
873template <typename T, typename U, typename... Ts>
874struct is_one_of<T, U, Ts...> {
875 static const bool value =
876 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
877};
878
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100879/// traits class for checking whether type T is a base class for all
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100880/// the given types in the variadic list.
881template <typename T, typename... Ts> struct are_base_of {
882 static const bool value = true;
883};
884
885template <typename T, typename U, typename... Ts>
886struct are_base_of<T, U, Ts...> {
887 static const bool value =
888 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
889};
890
891//===----------------------------------------------------------------------===//
892// Extra additions for arrays
893//===----------------------------------------------------------------------===//
894
895/// Find the length of an array.
896template <class T, std::size_t N>
897constexpr inline size_t array_lengthof(T (&)[N]) {
898 return N;
899}
900
901/// Adapt std::less<T> for array_pod_sort.
902template<typename T>
903inline int array_pod_sort_comparator(const void *P1, const void *P2) {
904 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
905 *reinterpret_cast<const T*>(P2)))
906 return -1;
907 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
908 *reinterpret_cast<const T*>(P1)))
909 return 1;
910 return 0;
911}
912
913/// get_array_pod_sort_comparator - This is an internal helper function used to
914/// get type deduction of T right.
915template<typename T>
916inline int (*get_array_pod_sort_comparator(const T &))
917 (const void*, const void*) {
918 return array_pod_sort_comparator<T>;
919}
920
921/// array_pod_sort - This sorts an array with the specified start and end
922/// extent. This is just like std::sort, except that it calls qsort instead of
923/// using an inlined template. qsort is slightly slower than std::sort, but
924/// most sorts are not performance critical in LLVM and std::sort has to be
925/// template instantiated for each type, leading to significant measured code
926/// bloat. This function should generally be used instead of std::sort where
927/// possible.
928///
929/// This function assumes that you have simple POD-like types that can be
930/// compared with std::less and can be moved with memcpy. If this isn't true,
931/// you should use std::sort.
932///
933/// NOTE: If qsort_r were portable, we could allow a custom comparator and
934/// default to std::less.
935template<class IteratorTy>
936inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
937 // Don't inefficiently call qsort with one element or trigger undefined
938 // behavior with an empty sequence.
939 auto NElts = End - Start;
940 if (NElts <= 1) return;
941#ifdef EXPENSIVE_CHECKS
942 std::mt19937 Generator(std::random_device{}());
943 std::shuffle(Start, End, Generator);
944#endif
945 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
946}
947
948template <class IteratorTy>
949inline void array_pod_sort(
950 IteratorTy Start, IteratorTy End,
951 int (*Compare)(
952 const typename std::iterator_traits<IteratorTy>::value_type *,
953 const typename std::iterator_traits<IteratorTy>::value_type *)) {
954 // Don't inefficiently call qsort with one element or trigger undefined
955 // behavior with an empty sequence.
956 auto NElts = End - Start;
957 if (NElts <= 1) return;
958#ifdef EXPENSIVE_CHECKS
959 std::mt19937 Generator(std::random_device{}());
960 std::shuffle(Start, End, Generator);
961#endif
962 qsort(&*Start, NElts, sizeof(*Start),
963 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
964}
965
966// Provide wrappers to std::sort which shuffle the elements before sorting
967// to help uncover non-deterministic behavior (PR35135).
968template <typename IteratorTy>
969inline void sort(IteratorTy Start, IteratorTy End) {
970#ifdef EXPENSIVE_CHECKS
971 std::mt19937 Generator(std::random_device{}());
972 std::shuffle(Start, End, Generator);
973#endif
974 std::sort(Start, End);
975}
976
977template <typename IteratorTy, typename Compare>
978inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
979#ifdef EXPENSIVE_CHECKS
980 std::mt19937 Generator(std::random_device{}());
981 std::shuffle(Start, End, Generator);
982#endif
983 std::sort(Start, End, Comp);
984}
985
986//===----------------------------------------------------------------------===//
987// Extra additions to <algorithm>
988//===----------------------------------------------------------------------===//
989
990/// For a container of pointers, deletes the pointers and then clears the
991/// container.
992template<typename Container>
993void DeleteContainerPointers(Container &C) {
994 for (auto V : C)
995 delete V;
996 C.clear();
997}
998
999/// In a container of pairs (usually a map) whose second element is a pointer,
1000/// deletes the second elements and then clears the container.
1001template<typename Container>
1002void DeleteContainerSeconds(Container &C) {
1003 for (auto &V : C)
1004 delete V.second;
1005 C.clear();
1006}
1007
1008/// Provide wrappers to std::for_each which take ranges instead of having to
1009/// pass begin/end explicitly.
1010template <typename R, typename UnaryPredicate>
1011UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
1012 return std::for_each(adl_begin(Range), adl_end(Range), P);
1013}
1014
1015/// Provide wrappers to std::all_of which take ranges instead of having to pass
1016/// begin/end explicitly.
1017template <typename R, typename UnaryPredicate>
1018bool all_of(R &&Range, UnaryPredicate P) {
1019 return std::all_of(adl_begin(Range), adl_end(Range), P);
1020}
1021
1022/// Provide wrappers to std::any_of which take ranges instead of having to pass
1023/// begin/end explicitly.
1024template <typename R, typename UnaryPredicate>
1025bool any_of(R &&Range, UnaryPredicate P) {
1026 return std::any_of(adl_begin(Range), adl_end(Range), P);
1027}
1028
1029/// Provide wrappers to std::none_of which take ranges instead of having to pass
1030/// begin/end explicitly.
1031template <typename R, typename UnaryPredicate>
1032bool none_of(R &&Range, UnaryPredicate P) {
1033 return std::none_of(adl_begin(Range), adl_end(Range), P);
1034}
1035
1036/// Provide wrappers to std::find which take ranges instead of having to pass
1037/// begin/end explicitly.
1038template <typename R, typename T>
1039auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) {
1040 return std::find(adl_begin(Range), adl_end(Range), Val);
1041}
1042
1043/// Provide wrappers to std::find_if which take ranges instead of having to pass
1044/// begin/end explicitly.
1045template <typename R, typename UnaryPredicate>
1046auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1047 return std::find_if(adl_begin(Range), adl_end(Range), P);
1048}
1049
1050template <typename R, typename UnaryPredicate>
1051auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1052 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
1053}
1054
1055/// Provide wrappers to std::remove_if which take ranges instead of having to
1056/// pass begin/end explicitly.
1057template <typename R, typename UnaryPredicate>
1058auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1059 return std::remove_if(adl_begin(Range), adl_end(Range), P);
1060}
1061
1062/// Provide wrappers to std::copy_if which take ranges instead of having to
1063/// pass begin/end explicitly.
1064template <typename R, typename OutputIt, typename UnaryPredicate>
1065OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
1066 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
1067}
1068
1069template <typename R, typename OutputIt>
1070OutputIt copy(R &&Range, OutputIt Out) {
1071 return std::copy(adl_begin(Range), adl_end(Range), Out);
1072}
1073
1074/// Wrapper function around std::find to detect if an element exists
1075/// in a container.
1076template <typename R, typename E>
1077bool is_contained(R &&Range, const E &Element) {
1078 return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
1079}
1080
1081/// Wrapper function around std::count to count the number of times an element
1082/// \p Element occurs in the given range \p Range.
1083template <typename R, typename E>
1084auto count(R &&Range, const E &Element) ->
1085 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
1086 return std::count(adl_begin(Range), adl_end(Range), Element);
1087}
1088
1089/// Wrapper function around std::count_if to count the number of times an
1090/// element satisfying a given predicate occurs in a range.
1091template <typename R, typename UnaryPredicate>
1092auto count_if(R &&Range, UnaryPredicate P) ->
1093 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
1094 return std::count_if(adl_begin(Range), adl_end(Range), P);
1095}
1096
1097/// Wrapper function around std::transform to apply a function to a range and
1098/// store the result elsewhere.
1099template <typename R, typename OutputIt, typename UnaryPredicate>
1100OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
1101 return std::transform(adl_begin(Range), adl_end(Range), d_first, P);
1102}
1103
1104/// Provide wrappers to std::partition which take ranges instead of having to
1105/// pass begin/end explicitly.
1106template <typename R, typename UnaryPredicate>
1107auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1108 return std::partition(adl_begin(Range), adl_end(Range), P);
1109}
1110
1111/// Provide wrappers to std::lower_bound which take ranges instead of having to
1112/// pass begin/end explicitly.
1113template <typename R, typename ForwardIt>
1114auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) {
1115 return std::lower_bound(adl_begin(Range), adl_end(Range), I);
1116}
1117
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001118/// Given a range of type R, iterate the entire range and return a
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001119/// SmallVector with elements of the vector. This is useful, for example,
1120/// when you want to iterate a range and then sort the results.
1121template <unsigned Size, typename R>
1122SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size>
1123to_vector(R &&Range) {
1124 return {adl_begin(Range), adl_end(Range)};
1125}
1126
1127/// Provide a container algorithm similar to C++ Library Fundamentals v2's
1128/// `erase_if` which is equivalent to:
1129///
1130/// C.erase(remove_if(C, pred), C.end());
1131///
1132/// This version works for any container with an erase method call accepting
1133/// two iterators.
1134template <typename Container, typename UnaryPredicate>
1135void erase_if(Container &C, UnaryPredicate P) {
1136 C.erase(remove_if(C, P), C.end());
1137}
1138
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001139/// Get the size of a range. This is a wrapper function around std::distance
1140/// which is only enabled when the operation is O(1).
1141template <typename R>
1142auto size(R &&Range, typename std::enable_if<
1143 std::is_same<typename std::iterator_traits<decltype(
1144 Range.begin())>::iterator_category,
1145 std::random_access_iterator_tag>::value,
1146 void>::type * = nullptr)
1147 -> decltype(std::distance(Range.begin(), Range.end())) {
1148 return std::distance(Range.begin(), Range.end());
1149}
1150
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001151//===----------------------------------------------------------------------===//
1152// Extra additions to <memory>
1153//===----------------------------------------------------------------------===//
1154
1155// Implement make_unique according to N3656.
1156
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001157/// Constructs a `new T()` with the given args and returns a
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001158/// `unique_ptr<T>` which owns the object.
1159///
1160/// Example:
1161///
1162/// auto p = make_unique<int>();
1163/// auto p = make_unique<std::tuple<int, int>>(0, 1);
1164template <class T, class... Args>
1165typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
1166make_unique(Args &&... args) {
1167 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
1168}
1169
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001170/// Constructs a `new T[n]` with the given args and returns a
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001171/// `unique_ptr<T[]>` which owns the object.
1172///
1173/// \param n size of the new array.
1174///
1175/// Example:
1176///
1177/// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
1178template <class T>
1179typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
1180 std::unique_ptr<T>>::type
1181make_unique(size_t n) {
1182 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
1183}
1184
1185/// This function isn't used and is only here to provide better compile errors.
1186template <class T, class... Args>
1187typename std::enable_if<std::extent<T>::value != 0>::type
1188make_unique(Args &&...) = delete;
1189
1190struct FreeDeleter {
1191 void operator()(void* v) {
1192 ::free(v);
1193 }
1194};
1195
1196template<typename First, typename Second>
1197struct pair_hash {
1198 size_t operator()(const std::pair<First, Second> &P) const {
1199 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1200 }
1201};
1202
1203/// A functor like C++14's std::less<void> in its absence.
1204struct less {
1205 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1206 return std::forward<A>(a) < std::forward<B>(b);
1207 }
1208};
1209
1210/// A functor like C++14's std::equal<void> in its absence.
1211struct equal {
1212 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1213 return std::forward<A>(a) == std::forward<B>(b);
1214 }
1215};
1216
1217/// Binary functor that adapts to any other binary functor after dereferencing
1218/// operands.
1219template <typename T> struct deref {
1220 T func;
1221
1222 // Could be further improved to cope with non-derivable functors and
1223 // non-binary functors (should be a variadic template member function
1224 // operator()).
1225 template <typename A, typename B>
1226 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
1227 assert(lhs);
1228 assert(rhs);
1229 return func(*lhs, *rhs);
1230 }
1231};
1232
1233namespace detail {
1234
1235template <typename R> class enumerator_iter;
1236
1237template <typename R> struct result_pair {
1238 friend class enumerator_iter<R>;
1239
1240 result_pair() = default;
1241 result_pair(std::size_t Index, IterOfRange<R> Iter)
1242 : Index(Index), Iter(Iter) {}
1243
1244 result_pair<R> &operator=(const result_pair<R> &Other) {
1245 Index = Other.Index;
1246 Iter = Other.Iter;
1247 return *this;
1248 }
1249
1250 std::size_t index() const { return Index; }
1251 const ValueOfRange<R> &value() const { return *Iter; }
1252 ValueOfRange<R> &value() { return *Iter; }
1253
1254private:
1255 std::size_t Index = std::numeric_limits<std::size_t>::max();
1256 IterOfRange<R> Iter;
1257};
1258
1259template <typename R>
1260class enumerator_iter
1261 : public iterator_facade_base<
1262 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1263 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1264 typename std::iterator_traits<IterOfRange<R>>::pointer,
1265 typename std::iterator_traits<IterOfRange<R>>::reference> {
1266 using result_type = result_pair<R>;
1267
1268public:
1269 explicit enumerator_iter(IterOfRange<R> EndIter)
1270 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1271
1272 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1273 : Result(Index, Iter) {}
1274
1275 result_type &operator*() { return Result; }
1276 const result_type &operator*() const { return Result; }
1277
1278 enumerator_iter<R> &operator++() {
1279 assert(Result.Index != std::numeric_limits<size_t>::max());
1280 ++Result.Iter;
1281 ++Result.Index;
1282 return *this;
1283 }
1284
1285 bool operator==(const enumerator_iter<R> &RHS) const {
1286 // Don't compare indices here, only iterators. It's possible for an end
1287 // iterator to have different indices depending on whether it was created
1288 // by calling std::end() versus incrementing a valid iterator.
1289 return Result.Iter == RHS.Result.Iter;
1290 }
1291
1292 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1293 Result = Other.Result;
1294 return *this;
1295 }
1296
1297private:
1298 result_type Result;
1299};
1300
1301template <typename R> class enumerator {
1302public:
1303 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1304
1305 enumerator_iter<R> begin() {
1306 return enumerator_iter<R>(0, std::begin(TheRange));
1307 }
1308
1309 enumerator_iter<R> end() {
1310 return enumerator_iter<R>(std::end(TheRange));
1311 }
1312
1313private:
1314 R TheRange;
1315};
1316
1317} // end namespace detail
1318
1319/// Given an input range, returns a new range whose values are are pair (A,B)
1320/// such that A is the 0-based index of the item in the sequence, and B is
1321/// the value from the original sequence. Example:
1322///
1323/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1324/// for (auto X : enumerate(Items)) {
1325/// printf("Item %d - %c\n", X.index(), X.value());
1326/// }
1327///
1328/// Output:
1329/// Item 0 - A
1330/// Item 1 - B
1331/// Item 2 - C
1332/// Item 3 - D
1333///
1334template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1335 return detail::enumerator<R>(std::forward<R>(TheRange));
1336}
1337
1338namespace detail {
1339
1340template <typename F, typename Tuple, std::size_t... I>
1341auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
1342 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1343 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1344}
1345
1346} // end namespace detail
1347
1348/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1349/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1350/// return the result.
1351template <typename F, typename Tuple>
1352auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1353 std::forward<F>(f), std::forward<Tuple>(t),
1354 build_index_impl<
1355 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1356 using Indices = build_index_impl<
1357 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1358
1359 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1360 Indices{});
1361}
1362
1363} // end namespace llvm
1364
1365#endif // LLVM_ADT_STLEXTRAS_H