OSDN Git Service

b6ed93e9946b18e06fe75ff1232c84c747388336
[android-x86/external-llvm.git] / include / llvm / ADT / STLExtras.h
1 //===- 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 <algorithm> // for std::all_of
21 #include <cassert>
22 #include <cstddef> // for std::size_t
23 #include <cstdlib> // for qsort
24 #include <functional>
25 #include <iterator>
26 #include <memory>
27 #include <tuple>
28 #include <utility> // for std::pair
29
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/ADT/iterator.h"
32 #include "llvm/ADT/iterator_range.h"
33 #include "llvm/Support/Compiler.h"
34
35 namespace llvm {
36 namespace detail {
37
38 template <typename RangeT>
39 using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
40
41 } // End detail namespace
42
43 //===----------------------------------------------------------------------===//
44 //     Extra additions to <functional>
45 //===----------------------------------------------------------------------===//
46
47 template<class Ty>
48 struct identity : public std::unary_function<Ty, Ty> {
49   Ty &operator()(Ty &self) const {
50     return self;
51   }
52   const Ty &operator()(const Ty &self) const {
53     return self;
54   }
55 };
56
57 template<class Ty>
58 struct less_ptr : public std::binary_function<Ty, Ty, bool> {
59   bool operator()(const Ty* left, const Ty* right) const {
60     return *left < *right;
61   }
62 };
63
64 template<class Ty>
65 struct greater_ptr : public std::binary_function<Ty, Ty, bool> {
66   bool operator()(const Ty* left, const Ty* right) const {
67     return *right < *left;
68   }
69 };
70
71 /// An efficient, type-erasing, non-owning reference to a callable. This is
72 /// intended for use as the type of a function parameter that is not used
73 /// after the function in question returns.
74 ///
75 /// This class does not own the callable, so it is not in general safe to store
76 /// a function_ref.
77 template<typename Fn> class function_ref;
78
79 template<typename Ret, typename ...Params>
80 class function_ref<Ret(Params...)> {
81   Ret (*callback)(intptr_t callable, Params ...params);
82   intptr_t callable;
83
84   template<typename Callable>
85   static Ret callback_fn(intptr_t callable, Params ...params) {
86     return (*reinterpret_cast<Callable*>(callable))(
87         std::forward<Params>(params)...);
88   }
89
90 public:
91   template <typename Callable>
92   function_ref(Callable &&callable,
93                typename std::enable_if<
94                    !std::is_same<typename std::remove_reference<Callable>::type,
95                                  function_ref>::value>::type * = nullptr)
96       : callback(callback_fn<typename std::remove_reference<Callable>::type>),
97         callable(reinterpret_cast<intptr_t>(&callable)) {}
98   Ret operator()(Params ...params) const {
99     return callback(callable, std::forward<Params>(params)...);
100   }
101 };
102
103 // deleter - Very very very simple method that is used to invoke operator
104 // delete on something.  It is used like this:
105 //
106 //   for_each(V.begin(), B.end(), deleter<Interval>);
107 //
108 template <class T>
109 inline void deleter(T *Ptr) {
110   delete Ptr;
111 }
112
113
114
115 //===----------------------------------------------------------------------===//
116 //     Extra additions to <iterator>
117 //===----------------------------------------------------------------------===//
118
119 // mapped_iterator - This is a simple iterator adapter that causes a function to
120 // be dereferenced whenever operator* is invoked on the iterator.
121 //
122 template <class RootIt, class UnaryFunc>
123 class mapped_iterator {
124   RootIt current;
125   UnaryFunc Fn;
126 public:
127   typedef typename std::iterator_traits<RootIt>::iterator_category
128           iterator_category;
129   typedef typename std::iterator_traits<RootIt>::difference_type
130           difference_type;
131   typedef typename std::result_of<
132             UnaryFunc(decltype(*std::declval<RootIt>()))>
133           ::type value_type;
134
135   typedef void pointer;
136   //typedef typename UnaryFunc::result_type *pointer;
137   typedef void reference;        // Can't modify value returned by fn
138
139   typedef RootIt iterator_type;
140
141   inline const RootIt &getCurrent() const { return current; }
142   inline const UnaryFunc &getFunc() const { return Fn; }
143
144   inline explicit mapped_iterator(const RootIt &I, UnaryFunc F)
145     : current(I), Fn(F) {}
146
147   inline value_type operator*() const {   // All this work to do this
148     return Fn(*current);         // little change
149   }
150
151   mapped_iterator &operator++() {
152     ++current;
153     return *this;
154   }
155   mapped_iterator &operator--() {
156     --current;
157     return *this;
158   }
159   mapped_iterator operator++(int) {
160     mapped_iterator __tmp = *this;
161     ++current;
162     return __tmp;
163   }
164   mapped_iterator operator--(int) {
165     mapped_iterator __tmp = *this;
166     --current;
167     return __tmp;
168   }
169   mapped_iterator operator+(difference_type n) const {
170     return mapped_iterator(current + n, Fn);
171   }
172   mapped_iterator &operator+=(difference_type n) {
173     current += n;
174     return *this;
175   }
176   mapped_iterator operator-(difference_type n) const {
177     return mapped_iterator(current - n, Fn);
178   }
179   mapped_iterator &operator-=(difference_type n) {
180     current -= n;
181     return *this;
182   }
183   reference operator[](difference_type n) const { return *(*this + n); }
184
185   bool operator!=(const mapped_iterator &X) const { return !operator==(X); }
186   bool operator==(const mapped_iterator &X) const {
187     return current == X.current;
188   }
189   bool operator<(const mapped_iterator &X) const { return current < X.current; }
190
191   difference_type operator-(const mapped_iterator &X) const {
192     return current - X.current;
193   }
194 };
195
196 template <class Iterator, class Func>
197 inline mapped_iterator<Iterator, Func>
198 operator+(typename mapped_iterator<Iterator, Func>::difference_type N,
199           const mapped_iterator<Iterator, Func> &X) {
200   return mapped_iterator<Iterator, Func>(X.getCurrent() - N, X.getFunc());
201 }
202
203
204 // map_iterator - Provide a convenient way to create mapped_iterators, just like
205 // make_pair is useful for creating pairs...
206 //
207 template <class ItTy, class FuncTy>
208 inline mapped_iterator<ItTy, FuncTy> map_iterator(const ItTy &I, FuncTy F) {
209   return mapped_iterator<ItTy, FuncTy>(I, F);
210 }
211
212 /// Helper to determine if type T has a member called rbegin().
213 template <typename Ty> class has_rbegin_impl {
214   typedef char yes[1];
215   typedef char no[2];
216
217   template <typename Inner>
218   static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
219
220   template <typename>
221   static no& test(...);
222
223 public:
224   static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
225 };
226
227 /// Metafunction to determine if T& or T has a member called rbegin().
228 template <typename Ty>
229 struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
230 };
231
232 // Returns an iterator_range over the given container which iterates in reverse.
233 // Note that the container must have rbegin()/rend() methods for this to work.
234 template <typename ContainerTy>
235 auto reverse(ContainerTy &&C,
236              typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
237                  nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
238   return make_range(C.rbegin(), C.rend());
239 }
240
241 // Returns a std::reverse_iterator wrapped around the given iterator.
242 template <typename IteratorTy>
243 std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
244   return std::reverse_iterator<IteratorTy>(It);
245 }
246
247 // Returns an iterator_range over the given container which iterates in reverse.
248 // Note that the container must have begin()/end() methods which return
249 // bidirectional iterators for this to work.
250 template <typename ContainerTy>
251 auto reverse(
252     ContainerTy &&C,
253     typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
254     -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
255                            llvm::make_reverse_iterator(std::begin(C)))) {
256   return make_range(llvm::make_reverse_iterator(std::end(C)),
257                     llvm::make_reverse_iterator(std::begin(C)));
258 }
259
260 /// An iterator adaptor that filters the elements of given inner iterators.
261 ///
262 /// The predicate parameter should be a callable object that accepts the wrapped
263 /// iterator's reference type and returns a bool. When incrementing or
264 /// decrementing the iterator, it will call the predicate on each element and
265 /// skip any where it returns false.
266 ///
267 /// \code
268 ///   int A[] = { 1, 2, 3, 4 };
269 ///   auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
270 ///   // R contains { 1, 3 }.
271 /// \endcode
272 template <typename WrappedIteratorT, typename PredicateT>
273 class filter_iterator
274     : public iterator_adaptor_base<
275           filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
276           typename std::common_type<
277               std::forward_iterator_tag,
278               typename std::iterator_traits<
279                   WrappedIteratorT>::iterator_category>::type> {
280   using BaseT = iterator_adaptor_base<
281       filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
282       typename std::common_type<
283           std::forward_iterator_tag,
284           typename std::iterator_traits<WrappedIteratorT>::iterator_category>::
285           type>;
286
287   struct PayloadType {
288     WrappedIteratorT End;
289     PredicateT Pred;
290   };
291
292   Optional<PayloadType> Payload;
293
294   void findNextValid() {
295     assert(Payload && "Payload should be engaged when findNextValid is called");
296     while (this->I != Payload->End && !Payload->Pred(*this->I))
297       BaseT::operator++();
298   }
299
300   // Construct the begin iterator. The begin iterator requires to know where end
301   // is, so that it can properly stop when it hits end.
302   filter_iterator(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
303       : BaseT(std::move(Begin)),
304         Payload(PayloadType{std::move(End), std::move(Pred)}) {
305     findNextValid();
306   }
307
308   // Construct the end iterator. It's not incrementable, so Payload doesn't
309   // have to be engaged.
310   filter_iterator(WrappedIteratorT End) : BaseT(End) {}
311
312 public:
313   using BaseT::operator++;
314
315   filter_iterator &operator++() {
316     BaseT::operator++();
317     findNextValid();
318     return *this;
319   }
320
321   template <typename RT, typename PT>
322   friend iterator_range<filter_iterator<detail::IterOfRange<RT>, PT>>
323   make_filter_range(RT &&, PT);
324 };
325
326 /// Convenience function that takes a range of elements and a predicate,
327 /// and return a new filter_iterator range.
328 ///
329 /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
330 /// lifetime of that temporary is not kept by the returned range object, and the
331 /// temporary is going to be dropped on the floor after the make_iterator_range
332 /// full expression that contains this function call.
333 template <typename RangeT, typename PredicateT>
334 iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
335 make_filter_range(RangeT &&Range, PredicateT Pred) {
336   using FilterIteratorT =
337       filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
338   return make_range(FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
339                                     std::end(std::forward<RangeT>(Range)),
340                                     std::move(Pred)),
341                     FilterIteratorT(std::end(std::forward<RangeT>(Range))));
342 }
343
344 // forward declarations required by zip_shortest/zip_first
345 template <typename R, class UnaryPredicate>
346 bool all_of(R &&range, UnaryPredicate &&P);
347
348 template <size_t... I> struct index_sequence;
349
350 template <class... Ts> struct index_sequence_for;
351
352 namespace detail {
353 template <typename... Iters> class zip_first {
354 public:
355   typedef std::input_iterator_tag iterator_category;
356   typedef std::tuple<decltype(*std::declval<Iters>())...> value_type;
357   std::tuple<Iters...> iterators;
358
359 private:
360   template <size_t... Ns> value_type deres(index_sequence<Ns...>) {
361     return value_type(*std::get<Ns>(iterators)...);
362   }
363
364   template <size_t... Ns> decltype(iterators) tup_inc(index_sequence<Ns...>) {
365     return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
366   }
367
368 public:
369   value_type operator*() { return deres(index_sequence_for<Iters...>{}); }
370
371   void operator++() { iterators = tup_inc(index_sequence_for<Iters...>{}); }
372
373   bool operator!=(const zip_first<Iters...> &other) const {
374     return std::get<0>(iterators) != std::get<0>(other.iterators);
375   }
376   zip_first(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
377 };
378
379 template <typename... Iters> class zip_shortest : public zip_first<Iters...> {
380   template <size_t... Ns>
381   bool test(const zip_first<Iters...> &other, index_sequence<Ns...>) const {
382     return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
383                                               std::get<Ns>(other.iterators)...},
384                   identity<bool>{});
385   }
386
387 public:
388   bool operator!=(const zip_first<Iters...> &other) const {
389     return test(other, index_sequence_for<Iters...>{});
390   }
391   zip_shortest(Iters &&... ts)
392       : zip_first<Iters...>(std::forward<Iters>(ts)...) {}
393 };
394
395 template <template <typename...> class ItType, typename... Args> class zippy {
396 public:
397   typedef ItType<decltype(std::begin(std::declval<Args>()))...> iterator;
398
399 private:
400   std::tuple<Args...> ts;
401
402   template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
403     return iterator(std::begin(std::get<Ns>(ts))...);
404   }
405   template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
406     return iterator(std::end(std::get<Ns>(ts))...);
407   }
408
409 public:
410   iterator begin() { return begin_impl(index_sequence_for<Args...>{}); }
411   iterator end() { return end_impl(index_sequence_for<Args...>{}); }
412   zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
413 };
414 } // End detail namespace
415
416 /// zip iterator for two or more iteratable types.
417 template <typename T, typename U, typename... Args>
418 detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
419                                                        Args &&... args) {
420   return detail::zippy<detail::zip_shortest, T, U, Args...>(
421       std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
422 }
423
424 /// zip iterator that, for the sake of efficiency, assumes the first iteratee to
425 /// be the shortest.
426 template <typename T, typename U, typename... Args>
427 detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
428                                                           Args &&... args) {
429   return detail::zippy<detail::zip_first, T, U, Args...>(
430       std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
431 }
432
433 //===----------------------------------------------------------------------===//
434 //     Extra additions to <utility>
435 //===----------------------------------------------------------------------===//
436
437 /// \brief Function object to check whether the first component of a std::pair
438 /// compares less than the first component of another std::pair.
439 struct less_first {
440   template <typename T> bool operator()(const T &lhs, const T &rhs) const {
441     return lhs.first < rhs.first;
442   }
443 };
444
445 /// \brief Function object to check whether the second component of a std::pair
446 /// compares less than the second component of another std::pair.
447 struct less_second {
448   template <typename T> bool operator()(const T &lhs, const T &rhs) const {
449     return lhs.second < rhs.second;
450   }
451 };
452
453 // A subset of N3658. More stuff can be added as-needed.
454
455 /// \brief Represents a compile-time sequence of integers.
456 template <class T, T... I> struct integer_sequence {
457   typedef T value_type;
458
459   static constexpr size_t size() { return sizeof...(I); }
460 };
461
462 /// \brief Alias for the common case of a sequence of size_ts.
463 template <size_t... I>
464 struct index_sequence : integer_sequence<std::size_t, I...> {};
465
466 template <std::size_t N, std::size_t... I>
467 struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
468 template <std::size_t... I>
469 struct build_index_impl<0, I...> : index_sequence<I...> {};
470
471 /// \brief Creates a compile-time integer sequence for a parameter pack.
472 template <class... Ts>
473 struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
474
475 /// Utility type to build an inheritance chain that makes it easy to rank
476 /// overload candidates.
477 template <int N> struct rank : rank<N - 1> {};
478 template <> struct rank<0> {};
479
480 //===----------------------------------------------------------------------===//
481 //     Extra additions for arrays
482 //===----------------------------------------------------------------------===//
483
484 /// Find the length of an array.
485 template <class T, std::size_t N>
486 constexpr inline size_t array_lengthof(T (&)[N]) {
487   return N;
488 }
489
490 /// Adapt std::less<T> for array_pod_sort.
491 template<typename T>
492 inline int array_pod_sort_comparator(const void *P1, const void *P2) {
493   if (std::less<T>()(*reinterpret_cast<const T*>(P1),
494                      *reinterpret_cast<const T*>(P2)))
495     return -1;
496   if (std::less<T>()(*reinterpret_cast<const T*>(P2),
497                      *reinterpret_cast<const T*>(P1)))
498     return 1;
499   return 0;
500 }
501
502 /// get_array_pod_sort_comparator - This is an internal helper function used to
503 /// get type deduction of T right.
504 template<typename T>
505 inline int (*get_array_pod_sort_comparator(const T &))
506              (const void*, const void*) {
507   return array_pod_sort_comparator<T>;
508 }
509
510
511 /// array_pod_sort - This sorts an array with the specified start and end
512 /// extent.  This is just like std::sort, except that it calls qsort instead of
513 /// using an inlined template.  qsort is slightly slower than std::sort, but
514 /// most sorts are not performance critical in LLVM and std::sort has to be
515 /// template instantiated for each type, leading to significant measured code
516 /// bloat.  This function should generally be used instead of std::sort where
517 /// possible.
518 ///
519 /// This function assumes that you have simple POD-like types that can be
520 /// compared with std::less and can be moved with memcpy.  If this isn't true,
521 /// you should use std::sort.
522 ///
523 /// NOTE: If qsort_r were portable, we could allow a custom comparator and
524 /// default to std::less.
525 template<class IteratorTy>
526 inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
527   // Don't inefficiently call qsort with one element or trigger undefined
528   // behavior with an empty sequence.
529   auto NElts = End - Start;
530   if (NElts <= 1) return;
531   qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
532 }
533
534 template <class IteratorTy>
535 inline void array_pod_sort(
536     IteratorTy Start, IteratorTy End,
537     int (*Compare)(
538         const typename std::iterator_traits<IteratorTy>::value_type *,
539         const typename std::iterator_traits<IteratorTy>::value_type *)) {
540   // Don't inefficiently call qsort with one element or trigger undefined
541   // behavior with an empty sequence.
542   auto NElts = End - Start;
543   if (NElts <= 1) return;
544   qsort(&*Start, NElts, sizeof(*Start),
545         reinterpret_cast<int (*)(const void *, const void *)>(Compare));
546 }
547
548 //===----------------------------------------------------------------------===//
549 //     Extra additions to <algorithm>
550 //===----------------------------------------------------------------------===//
551
552 /// For a container of pointers, deletes the pointers and then clears the
553 /// container.
554 template<typename Container>
555 void DeleteContainerPointers(Container &C) {
556   for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
557     delete *I;
558   C.clear();
559 }
560
561 /// In a container of pairs (usually a map) whose second element is a pointer,
562 /// deletes the second elements and then clears the container.
563 template<typename Container>
564 void DeleteContainerSeconds(Container &C) {
565   for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
566     delete I->second;
567   C.clear();
568 }
569
570 /// Provide wrappers to std::all_of which take ranges instead of having to pass
571 /// begin/end explicitly.
572 template<typename R, class UnaryPredicate>
573 bool all_of(R &&Range, UnaryPredicate &&P) {
574   return std::all_of(Range.begin(), Range.end(),
575                      std::forward<UnaryPredicate>(P));
576 }
577
578 /// Provide wrappers to std::any_of which take ranges instead of having to pass
579 /// begin/end explicitly.
580 template <typename R, class UnaryPredicate>
581 bool any_of(R &&Range, UnaryPredicate &&P) {
582   return std::any_of(Range.begin(), Range.end(),
583                      std::forward<UnaryPredicate>(P));
584 }
585
586 /// Provide wrappers to std::none_of which take ranges instead of having to pass
587 /// begin/end explicitly.
588 template <typename R, class UnaryPredicate>
589 bool none_of(R &&Range, UnaryPredicate &&P) {
590   return std::none_of(Range.begin(), Range.end(),
591                       std::forward<UnaryPredicate>(P));
592 }
593
594 /// Provide wrappers to std::find which take ranges instead of having to pass
595 /// begin/end explicitly.
596 template<typename R, class T>
597 auto find(R &&Range, const T &val) -> decltype(Range.begin()) {
598   return std::find(Range.begin(), Range.end(), val);
599 }
600
601 /// Provide wrappers to std::find_if which take ranges instead of having to pass
602 /// begin/end explicitly.
603 template <typename R, class T>
604 auto find_if(R &&Range, const T &Pred) -> decltype(Range.begin()) {
605   return std::find_if(Range.begin(), Range.end(), Pred);
606 }
607
608 /// Provide wrappers to std::remove_if which take ranges instead of having to
609 /// pass begin/end explicitly.
610 template<typename R, class UnaryPredicate>
611 auto remove_if(R &&Range, UnaryPredicate &&P) -> decltype(Range.begin()) {
612   return std::remove_if(Range.begin(), Range.end(), P);
613 }
614
615 /// Wrapper function around std::find to detect if an element exists
616 /// in a container.
617 template <typename R, typename E>
618 bool is_contained(R &&Range, const E &Element) {
619   return std::find(Range.begin(), Range.end(), Element) != Range.end();
620 }
621
622 /// Wrapper function around std::count_if to count the number of times an
623 /// element satisfying a given predicate occurs in a range.
624 template <typename R, typename UnaryPredicate>
625 auto count_if(R &&Range, UnaryPredicate &&P)
626     -> typename std::iterator_traits<decltype(Range.begin())>::difference_type {
627   return std::count_if(Range.begin(), Range.end(), P);
628 }
629
630 /// Wrapper function around std::transform to apply a function to a range and
631 /// store the result elsewhere.
632 template <typename R, class OutputIt, typename UnaryPredicate>
633 OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate &&P) {
634   return std::transform(Range.begin(), Range.end(), d_first,
635                         std::forward<UnaryPredicate>(P));
636 }
637
638 //===----------------------------------------------------------------------===//
639 //     Extra additions to <memory>
640 //===----------------------------------------------------------------------===//
641
642 // Implement make_unique according to N3656.
643
644 /// \brief Constructs a `new T()` with the given args and returns a
645 ///        `unique_ptr<T>` which owns the object.
646 ///
647 /// Example:
648 ///
649 ///     auto p = make_unique<int>();
650 ///     auto p = make_unique<std::tuple<int, int>>(0, 1);
651 template <class T, class... Args>
652 typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
653 make_unique(Args &&... args) {
654   return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
655 }
656
657 /// \brief Constructs a `new T[n]` with the given args and returns a
658 ///        `unique_ptr<T[]>` which owns the object.
659 ///
660 /// \param n size of the new array.
661 ///
662 /// Example:
663 ///
664 ///     auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
665 template <class T>
666 typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
667                         std::unique_ptr<T>>::type
668 make_unique(size_t n) {
669   return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
670 }
671
672 /// This function isn't used and is only here to provide better compile errors.
673 template <class T, class... Args>
674 typename std::enable_if<std::extent<T>::value != 0>::type
675 make_unique(Args &&...) = delete;
676
677 struct FreeDeleter {
678   void operator()(void* v) {
679     ::free(v);
680   }
681 };
682
683 template<typename First, typename Second>
684 struct pair_hash {
685   size_t operator()(const std::pair<First, Second> &P) const {
686     return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
687   }
688 };
689
690 /// A functor like C++14's std::less<void> in its absence.
691 struct less {
692   template <typename A, typename B> bool operator()(A &&a, B &&b) const {
693     return std::forward<A>(a) < std::forward<B>(b);
694   }
695 };
696
697 /// A functor like C++14's std::equal<void> in its absence.
698 struct equal {
699   template <typename A, typename B> bool operator()(A &&a, B &&b) const {
700     return std::forward<A>(a) == std::forward<B>(b);
701   }
702 };
703
704 /// Binary functor that adapts to any other binary functor after dereferencing
705 /// operands.
706 template <typename T> struct deref {
707   T func;
708   // Could be further improved to cope with non-derivable functors and
709   // non-binary functors (should be a variadic template member function
710   // operator()).
711   template <typename A, typename B>
712   auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
713     assert(lhs);
714     assert(rhs);
715     return func(*lhs, *rhs);
716   }
717 };
718
719 namespace detail {
720 template <typename R> class enumerator_impl {
721 public:
722   template <typename X> struct result_pair {
723     result_pair(std::size_t Index, X Value) : Index(Index), Value(Value) {}
724
725     const std::size_t Index;
726     X Value;
727   };
728
729   class iterator {
730     typedef
731         typename std::iterator_traits<IterOfRange<R>>::reference iter_reference;
732     typedef result_pair<iter_reference> result_type;
733
734   public:
735     iterator(IterOfRange<R> &&Iter, std::size_t Index)
736         : Iter(Iter), Index(Index) {}
737
738     result_type operator*() const { return result_type(Index, *Iter); }
739
740     iterator &operator++() {
741       ++Iter;
742       ++Index;
743       return *this;
744     }
745
746     bool operator!=(const iterator &RHS) const { return Iter != RHS.Iter; }
747
748   private:
749     IterOfRange<R> Iter;
750     std::size_t Index;
751   };
752
753 public:
754   explicit enumerator_impl(R &&Range) : Range(std::forward<R>(Range)) {}
755
756   iterator begin() { return iterator(std::begin(Range), 0); }
757   iterator end() { return iterator(std::end(Range), std::size_t(-1)); }
758
759 private:
760   R Range;
761 };
762 }
763
764 /// Given an input range, returns a new range whose values are are pair (A,B)
765 /// such that A is the 0-based index of the item in the sequence, and B is
766 /// the value from the original sequence.  Example:
767 ///
768 /// std::vector<char> Items = {'A', 'B', 'C', 'D'};
769 /// for (auto X : enumerate(Items)) {
770 ///   printf("Item %d - %c\n", X.Index, X.Value);
771 /// }
772 ///
773 /// Output:
774 ///   Item 0 - A
775 ///   Item 1 - B
776 ///   Item 2 - C
777 ///   Item 3 - D
778 ///
779 template <typename R> detail::enumerator_impl<R> enumerate(R &&Range) {
780   return detail::enumerator_impl<R>(std::forward<R>(Range));
781 }
782
783 namespace detail {
784 template <typename F, typename Tuple, std::size_t... I>
785 auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
786     -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
787   return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
788 }
789 }
790
791 /// Given an input tuple (a1, a2, ..., an), pass the arguments of the
792 /// tuple variadically to f as if by calling f(a1, a2, ..., an) and
793 /// return the result.
794 template <typename F, typename Tuple>
795 auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
796     std::forward<F>(f), std::forward<Tuple>(t),
797     build_index_impl<
798         std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
799   using Indices = build_index_impl<
800       std::tuple_size<typename std::decay<Tuple>::type>::value>;
801
802   return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
803                                   Indices{});
804 }
805 } // End llvm namespace
806
807 #endif