xref: /freebsd/contrib/llvm-project/llvm/include/llvm/ADT/STLExtras.h (revision 38a52bd3b5cac3da6f7f6eef3dd050e6aa08ebb3)
1 //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file contains some templates that are useful if you are working with
11 /// the 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/STLArrayExtras.h"
22 #include "llvm/ADT/STLForwardCompat.h"
23 #include "llvm/ADT/STLFunctionalExtras.h"
24 #include "llvm/ADT/identity.h"
25 #include "llvm/ADT/iterator.h"
26 #include "llvm/ADT/iterator_range.h"
27 #include "llvm/Config/abi-breaking.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstddef>
32 #include <cstdint>
33 #include <cstdlib>
34 #include <functional>
35 #include <initializer_list>
36 #include <iterator>
37 #include <limits>
38 #include <memory>
39 #include <tuple>
40 #include <type_traits>
41 #include <utility>
42 
43 #ifdef EXPENSIVE_CHECKS
44 #include <random> // for std::mt19937
45 #endif
46 
47 namespace llvm {
48 
49 // Only used by compiler if both template types are the same.  Useful when
50 // using SFINAE to test for the existence of member functions.
51 template <typename T, T> struct SameType;
52 
53 namespace detail {
54 
55 template <typename RangeT>
56 using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
57 
58 template <typename RangeT>
59 using ValueOfRange = typename std::remove_reference<decltype(
60     *std::begin(std::declval<RangeT &>()))>::type;
61 
62 } // end namespace detail
63 
64 //===----------------------------------------------------------------------===//
65 //     Extra additions to <type_traits>
66 //===----------------------------------------------------------------------===//
67 
68 template <typename T> struct make_const_ptr {
69   using type =
70       typename std::add_pointer<typename std::add_const<T>::type>::type;
71 };
72 
73 template <typename T> struct make_const_ref {
74   using type = typename std::add_lvalue_reference<
75       typename std::add_const<T>::type>::type;
76 };
77 
78 namespace detail {
79 template <typename...> using void_t = void;
80 template <class, template <class...> class Op, class... Args> struct detector {
81   using value_t = std::false_type;
82 };
83 template <template <class...> class Op, class... Args>
84 struct detector<void_t<Op<Args...>>, Op, Args...> {
85   using value_t = std::true_type;
86 };
87 } // end namespace detail
88 
89 /// Detects if a given trait holds for some set of arguments 'Args'.
90 /// For example, the given trait could be used to detect if a given type
91 /// has a copy assignment operator:
92 ///   template<class T>
93 ///   using has_copy_assign_t = decltype(std::declval<T&>()
94 ///                                                 = std::declval<const T&>());
95 ///   bool fooHasCopyAssign = is_detected<has_copy_assign_t, FooClass>::value;
96 template <template <class...> class Op, class... Args>
97 using is_detected = typename detail::detector<void, Op, Args...>::value_t;
98 
99 namespace detail {
100 template <typename Callable, typename... Args>
101 using is_invocable =
102     decltype(std::declval<Callable &>()(std::declval<Args>()...));
103 } // namespace detail
104 
105 /// Check if a Callable type can be invoked with the given set of arg types.
106 template <typename Callable, typename... Args>
107 using is_invocable = is_detected<detail::is_invocable, Callable, Args...>;
108 
109 /// This class provides various trait information about a callable object.
110 ///   * To access the number of arguments: Traits::num_args
111 ///   * To access the type of an argument: Traits::arg_t<Index>
112 ///   * To access the type of the result:  Traits::result_t
113 template <typename T, bool isClass = std::is_class<T>::value>
114 struct function_traits : public function_traits<decltype(&T::operator())> {};
115 
116 /// Overload for class function types.
117 template <typename ClassType, typename ReturnType, typename... Args>
118 struct function_traits<ReturnType (ClassType::*)(Args...) const, false> {
119   /// The number of arguments to this function.
120   enum { num_args = sizeof...(Args) };
121 
122   /// The result type of this function.
123   using result_t = ReturnType;
124 
125   /// The type of an argument to this function.
126   template <size_t Index>
127   using arg_t = typename std::tuple_element<Index, std::tuple<Args...>>::type;
128 };
129 /// Overload for class function types.
130 template <typename ClassType, typename ReturnType, typename... Args>
131 struct function_traits<ReturnType (ClassType::*)(Args...), false>
132     : function_traits<ReturnType (ClassType::*)(Args...) const> {};
133 /// Overload for non-class function types.
134 template <typename ReturnType, typename... Args>
135 struct function_traits<ReturnType (*)(Args...), false> {
136   /// The number of arguments to this function.
137   enum { num_args = sizeof...(Args) };
138 
139   /// The result type of this function.
140   using result_t = ReturnType;
141 
142   /// The type of an argument to this function.
143   template <size_t i>
144   using arg_t = typename std::tuple_element<i, std::tuple<Args...>>::type;
145 };
146 /// Overload for non-class function type references.
147 template <typename ReturnType, typename... Args>
148 struct function_traits<ReturnType (&)(Args...), false>
149     : public function_traits<ReturnType (*)(Args...)> {};
150 
151 /// traits class for checking whether type T is one of any of the given
152 /// types in the variadic list.
153 template <typename T, typename... Ts>
154 using is_one_of = disjunction<std::is_same<T, Ts>...>;
155 
156 /// traits class for checking whether type T is a base class for all
157 ///  the given types in the variadic list.
158 template <typename T, typename... Ts>
159 using are_base_of = conjunction<std::is_base_of<T, Ts>...>;
160 
161 namespace detail {
162 template <typename T, typename... Us> struct TypesAreDistinct;
163 template <typename T, typename... Us>
164 struct TypesAreDistinct
165     : std::integral_constant<bool, !is_one_of<T, Us...>::value &&
166                                        TypesAreDistinct<Us...>::value> {};
167 template <typename T> struct TypesAreDistinct<T> : std::true_type {};
168 } // namespace detail
169 
170 /// Determine if all types in Ts are distinct.
171 ///
172 /// Useful to statically assert when Ts is intended to describe a non-multi set
173 /// of types.
174 ///
175 /// Expensive (currently quadratic in sizeof(Ts...)), and so should only be
176 /// asserted once per instantiation of a type which requires it.
177 template <typename... Ts> struct TypesAreDistinct;
178 template <> struct TypesAreDistinct<> : std::true_type {};
179 template <typename... Ts>
180 struct TypesAreDistinct
181     : std::integral_constant<bool, detail::TypesAreDistinct<Ts...>::value> {};
182 
183 /// Find the first index where a type appears in a list of types.
184 ///
185 /// FirstIndexOfType<T, Us...>::value is the first index of T in Us.
186 ///
187 /// Typically only meaningful when it is otherwise statically known that the
188 /// type pack has no duplicate types. This should be guaranteed explicitly with
189 /// static_assert(TypesAreDistinct<Us...>::value).
190 ///
191 /// It is a compile-time error to instantiate when T is not present in Us, i.e.
192 /// if is_one_of<T, Us...>::value is false.
193 template <typename T, typename... Us> struct FirstIndexOfType;
194 template <typename T, typename U, typename... Us>
195 struct FirstIndexOfType<T, U, Us...>
196     : std::integral_constant<size_t, 1 + FirstIndexOfType<T, Us...>::value> {};
197 template <typename T, typename... Us>
198 struct FirstIndexOfType<T, T, Us...> : std::integral_constant<size_t, 0> {};
199 
200 /// Find the type at a given index in a list of types.
201 ///
202 /// TypeAtIndex<I, Ts...> is the type at index I in Ts.
203 template <size_t I, typename... Ts>
204 using TypeAtIndex = std::tuple_element_t<I, std::tuple<Ts...>>;
205 
206 //===----------------------------------------------------------------------===//
207 //     Extra additions to <iterator>
208 //===----------------------------------------------------------------------===//
209 
210 namespace adl_detail {
211 
212 using std::begin;
213 
214 template <typename ContainerTy>
215 decltype(auto) adl_begin(ContainerTy &&container) {
216   return begin(std::forward<ContainerTy>(container));
217 }
218 
219 using std::end;
220 
221 template <typename ContainerTy>
222 decltype(auto) adl_end(ContainerTy &&container) {
223   return end(std::forward<ContainerTy>(container));
224 }
225 
226 using std::swap;
227 
228 template <typename T>
229 void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
230                                                        std::declval<T>()))) {
231   swap(std::forward<T>(lhs), std::forward<T>(rhs));
232 }
233 
234 } // end namespace adl_detail
235 
236 template <typename ContainerTy>
237 decltype(auto) adl_begin(ContainerTy &&container) {
238   return adl_detail::adl_begin(std::forward<ContainerTy>(container));
239 }
240 
241 template <typename ContainerTy>
242 decltype(auto) adl_end(ContainerTy &&container) {
243   return adl_detail::adl_end(std::forward<ContainerTy>(container));
244 }
245 
246 template <typename T>
247 void adl_swap(T &&lhs, T &&rhs) noexcept(
248     noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
249   adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
250 }
251 
252 /// Test whether \p RangeOrContainer is empty. Similar to C++17 std::empty.
253 template <typename T>
254 constexpr bool empty(const T &RangeOrContainer) {
255   return adl_begin(RangeOrContainer) == adl_end(RangeOrContainer);
256 }
257 
258 /// Returns true if the given container only contains a single element.
259 template <typename ContainerTy> bool hasSingleElement(ContainerTy &&C) {
260   auto B = std::begin(C), E = std::end(C);
261   return B != E && std::next(B) == E;
262 }
263 
264 /// Return a range covering \p RangeOrContainer with the first N elements
265 /// excluded.
266 template <typename T> auto drop_begin(T &&RangeOrContainer, size_t N = 1) {
267   return make_range(std::next(adl_begin(RangeOrContainer), N),
268                     adl_end(RangeOrContainer));
269 }
270 
271 // mapped_iterator - This is a simple iterator adapter that causes a function to
272 // be applied whenever operator* is invoked on the iterator.
273 
274 template <typename ItTy, typename FuncTy,
275           typename ReferenceTy =
276               decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
277 class mapped_iterator
278     : public iterator_adaptor_base<
279           mapped_iterator<ItTy, FuncTy>, ItTy,
280           typename std::iterator_traits<ItTy>::iterator_category,
281           std::remove_reference_t<ReferenceTy>,
282           typename std::iterator_traits<ItTy>::difference_type,
283           std::remove_reference_t<ReferenceTy> *, ReferenceTy> {
284 public:
285   mapped_iterator(ItTy U, FuncTy F)
286     : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
287 
288   ItTy getCurrent() { return this->I; }
289 
290   const FuncTy &getFunction() const { return F; }
291 
292   ReferenceTy operator*() const { return F(*this->I); }
293 
294 private:
295   FuncTy F;
296 };
297 
298 // map_iterator - Provide a convenient way to create mapped_iterators, just like
299 // make_pair is useful for creating pairs...
300 template <class ItTy, class FuncTy>
301 inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
302   return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
303 }
304 
305 template <class ContainerTy, class FuncTy>
306 auto map_range(ContainerTy &&C, FuncTy F) {
307   return make_range(map_iterator(C.begin(), F), map_iterator(C.end(), F));
308 }
309 
310 /// A base type of mapped iterator, that is useful for building derived
311 /// iterators that do not need/want to store the map function (as in
312 /// mapped_iterator). These iterators must simply provide a `mapElement` method
313 /// that defines how to map a value of the iterator to the provided reference
314 /// type.
315 template <typename DerivedT, typename ItTy, typename ReferenceTy>
316 class mapped_iterator_base
317     : public iterator_adaptor_base<
318           DerivedT, ItTy,
319           typename std::iterator_traits<ItTy>::iterator_category,
320           std::remove_reference_t<ReferenceTy>,
321           typename std::iterator_traits<ItTy>::difference_type,
322           std::remove_reference_t<ReferenceTy> *, ReferenceTy> {
323 public:
324   using BaseT = mapped_iterator_base;
325 
326   mapped_iterator_base(ItTy U)
327       : mapped_iterator_base::iterator_adaptor_base(std::move(U)) {}
328 
329   ItTy getCurrent() { return this->I; }
330 
331   ReferenceTy operator*() const {
332     return static_cast<const DerivedT &>(*this).mapElement(*this->I);
333   }
334 };
335 
336 /// Helper to determine if type T has a member called rbegin().
337 template <typename Ty> class has_rbegin_impl {
338   using yes = char[1];
339   using no = char[2];
340 
341   template <typename Inner>
342   static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
343 
344   template <typename>
345   static no& test(...);
346 
347 public:
348   static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
349 };
350 
351 /// Metafunction to determine if T& or T has a member called rbegin().
352 template <typename Ty>
353 struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
354 };
355 
356 // Returns an iterator_range over the given container which iterates in reverse.
357 // Note that the container must have rbegin()/rend() methods for this to work.
358 template <typename ContainerTy>
359 auto reverse(ContainerTy &&C,
360              std::enable_if_t<has_rbegin<ContainerTy>::value> * = nullptr) {
361   return make_range(C.rbegin(), C.rend());
362 }
363 
364 // Returns an iterator_range over the given container which iterates in reverse.
365 // Note that the container must have begin()/end() methods which return
366 // bidirectional iterators for this to work.
367 template <typename ContainerTy>
368 auto reverse(ContainerTy &&C,
369              std::enable_if_t<!has_rbegin<ContainerTy>::value> * = nullptr) {
370   return make_range(std::make_reverse_iterator(std::end(C)),
371                     std::make_reverse_iterator(std::begin(C)));
372 }
373 
374 /// An iterator adaptor that filters the elements of given inner iterators.
375 ///
376 /// The predicate parameter should be a callable object that accepts the wrapped
377 /// iterator's reference type and returns a bool. When incrementing or
378 /// decrementing the iterator, it will call the predicate on each element and
379 /// skip any where it returns false.
380 ///
381 /// \code
382 ///   int A[] = { 1, 2, 3, 4 };
383 ///   auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
384 ///   // R contains { 1, 3 }.
385 /// \endcode
386 ///
387 /// Note: filter_iterator_base implements support for forward iteration.
388 /// filter_iterator_impl exists to provide support for bidirectional iteration,
389 /// conditional on whether the wrapped iterator supports it.
390 template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
391 class filter_iterator_base
392     : public iterator_adaptor_base<
393           filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
394           WrappedIteratorT,
395           typename std::common_type<
396               IterTag, typename std::iterator_traits<
397                            WrappedIteratorT>::iterator_category>::type> {
398   using BaseT = typename filter_iterator_base::iterator_adaptor_base;
399 
400 protected:
401   WrappedIteratorT End;
402   PredicateT Pred;
403 
404   void findNextValid() {
405     while (this->I != End && !Pred(*this->I))
406       BaseT::operator++();
407   }
408 
409   // Construct the iterator. The begin iterator needs to know where the end
410   // is, so that it can properly stop when it gets there. The end iterator only
411   // needs the predicate to support bidirectional iteration.
412   filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End,
413                        PredicateT Pred)
414       : BaseT(Begin), End(End), Pred(Pred) {
415     findNextValid();
416   }
417 
418 public:
419   using BaseT::operator++;
420 
421   filter_iterator_base &operator++() {
422     BaseT::operator++();
423     findNextValid();
424     return *this;
425   }
426 };
427 
428 /// Specialization of filter_iterator_base for forward iteration only.
429 template <typename WrappedIteratorT, typename PredicateT,
430           typename IterTag = std::forward_iterator_tag>
431 class filter_iterator_impl
432     : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
433 public:
434   filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
435                        PredicateT Pred)
436       : filter_iterator_impl::filter_iterator_base(Begin, End, Pred) {}
437 };
438 
439 /// Specialization of filter_iterator_base for bidirectional iteration.
440 template <typename WrappedIteratorT, typename PredicateT>
441 class filter_iterator_impl<WrappedIteratorT, PredicateT,
442                            std::bidirectional_iterator_tag>
443     : public filter_iterator_base<WrappedIteratorT, PredicateT,
444                                   std::bidirectional_iterator_tag> {
445   using BaseT = typename filter_iterator_impl::filter_iterator_base;
446 
447   void findPrevValid() {
448     while (!this->Pred(*this->I))
449       BaseT::operator--();
450   }
451 
452 public:
453   using BaseT::operator--;
454 
455   filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
456                        PredicateT Pred)
457       : BaseT(Begin, End, Pred) {}
458 
459   filter_iterator_impl &operator--() {
460     BaseT::operator--();
461     findPrevValid();
462     return *this;
463   }
464 };
465 
466 namespace detail {
467 
468 template <bool is_bidirectional> struct fwd_or_bidi_tag_impl {
469   using type = std::forward_iterator_tag;
470 };
471 
472 template <> struct fwd_or_bidi_tag_impl<true> {
473   using type = std::bidirectional_iterator_tag;
474 };
475 
476 /// Helper which sets its type member to forward_iterator_tag if the category
477 /// of \p IterT does not derive from bidirectional_iterator_tag, and to
478 /// bidirectional_iterator_tag otherwise.
479 template <typename IterT> struct fwd_or_bidi_tag {
480   using type = typename fwd_or_bidi_tag_impl<std::is_base_of<
481       std::bidirectional_iterator_tag,
482       typename std::iterator_traits<IterT>::iterator_category>::value>::type;
483 };
484 
485 } // namespace detail
486 
487 /// Defines filter_iterator to a suitable specialization of
488 /// filter_iterator_impl, based on the underlying iterator's category.
489 template <typename WrappedIteratorT, typename PredicateT>
490 using filter_iterator = filter_iterator_impl<
491     WrappedIteratorT, PredicateT,
492     typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>;
493 
494 /// Convenience function that takes a range of elements and a predicate,
495 /// and return a new filter_iterator range.
496 ///
497 /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
498 /// lifetime of that temporary is not kept by the returned range object, and the
499 /// temporary is going to be dropped on the floor after the make_iterator_range
500 /// full expression that contains this function call.
501 template <typename RangeT, typename PredicateT>
502 iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
503 make_filter_range(RangeT &&Range, PredicateT Pred) {
504   using FilterIteratorT =
505       filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
506   return make_range(
507       FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
508                       std::end(std::forward<RangeT>(Range)), Pred),
509       FilterIteratorT(std::end(std::forward<RangeT>(Range)),
510                       std::end(std::forward<RangeT>(Range)), Pred));
511 }
512 
513 /// A pseudo-iterator adaptor that is designed to implement "early increment"
514 /// style loops.
515 ///
516 /// This is *not a normal iterator* and should almost never be used directly. It
517 /// is intended primarily to be used with range based for loops and some range
518 /// algorithms.
519 ///
520 /// The iterator isn't quite an `OutputIterator` or an `InputIterator` but
521 /// somewhere between them. The constraints of these iterators are:
522 ///
523 /// - On construction or after being incremented, it is comparable and
524 ///   dereferencable. It is *not* incrementable.
525 /// - After being dereferenced, it is neither comparable nor dereferencable, it
526 ///   is only incrementable.
527 ///
528 /// This means you can only dereference the iterator once, and you can only
529 /// increment it once between dereferences.
530 template <typename WrappedIteratorT>
531 class early_inc_iterator_impl
532     : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
533                                    WrappedIteratorT, std::input_iterator_tag> {
534   using BaseT = typename early_inc_iterator_impl::iterator_adaptor_base;
535 
536   using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer;
537 
538 protected:
539 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
540   bool IsEarlyIncremented = false;
541 #endif
542 
543 public:
544   early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {}
545 
546   using BaseT::operator*;
547   decltype(*std::declval<WrappedIteratorT>()) operator*() {
548 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
549     assert(!IsEarlyIncremented && "Cannot dereference twice!");
550     IsEarlyIncremented = true;
551 #endif
552     return *(this->I)++;
553   }
554 
555   using BaseT::operator++;
556   early_inc_iterator_impl &operator++() {
557 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
558     assert(IsEarlyIncremented && "Cannot increment before dereferencing!");
559     IsEarlyIncremented = false;
560 #endif
561     return *this;
562   }
563 
564   friend bool operator==(const early_inc_iterator_impl &LHS,
565                          const early_inc_iterator_impl &RHS) {
566 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
567     assert(!LHS.IsEarlyIncremented && "Cannot compare after dereferencing!");
568 #endif
569     return (const BaseT &)LHS == (const BaseT &)RHS;
570   }
571 };
572 
573 /// Make a range that does early increment to allow mutation of the underlying
574 /// range without disrupting iteration.
575 ///
576 /// The underlying iterator will be incremented immediately after it is
577 /// dereferenced, allowing deletion of the current node or insertion of nodes to
578 /// not disrupt iteration provided they do not invalidate the *next* iterator --
579 /// the current iterator can be invalidated.
580 ///
581 /// This requires a very exact pattern of use that is only really suitable to
582 /// range based for loops and other range algorithms that explicitly guarantee
583 /// to dereference exactly once each element, and to increment exactly once each
584 /// element.
585 template <typename RangeT>
586 iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>>
587 make_early_inc_range(RangeT &&Range) {
588   using EarlyIncIteratorT =
589       early_inc_iterator_impl<detail::IterOfRange<RangeT>>;
590   return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))),
591                     EarlyIncIteratorT(std::end(std::forward<RangeT>(Range))));
592 }
593 
594 // forward declarations required by zip_shortest/zip_first/zip_longest
595 template <typename R, typename UnaryPredicate>
596 bool all_of(R &&range, UnaryPredicate P);
597 template <typename R, typename UnaryPredicate>
598 bool any_of(R &&range, UnaryPredicate P);
599 
600 namespace detail {
601 
602 using std::declval;
603 
604 // We have to alias this since inlining the actual type at the usage site
605 // in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
606 template<typename... Iters> struct ZipTupleType {
607   using type = std::tuple<decltype(*declval<Iters>())...>;
608 };
609 
610 template <typename ZipType, typename... Iters>
611 using zip_traits = iterator_facade_base<
612     ZipType, typename std::common_type<std::bidirectional_iterator_tag,
613                                        typename std::iterator_traits<
614                                            Iters>::iterator_category...>::type,
615     // ^ TODO: Implement random access methods.
616     typename ZipTupleType<Iters...>::type,
617     typename std::iterator_traits<typename std::tuple_element<
618         0, std::tuple<Iters...>>::type>::difference_type,
619     // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
620     // inner iterators have the same difference_type. It would fail if, for
621     // instance, the second field's difference_type were non-numeric while the
622     // first is.
623     typename ZipTupleType<Iters...>::type *,
624     typename ZipTupleType<Iters...>::type>;
625 
626 template <typename ZipType, typename... Iters>
627 struct zip_common : public zip_traits<ZipType, Iters...> {
628   using Base = zip_traits<ZipType, Iters...>;
629   using value_type = typename Base::value_type;
630 
631   std::tuple<Iters...> iterators;
632 
633 protected:
634   template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
635     return value_type(*std::get<Ns>(iterators)...);
636   }
637 
638   template <size_t... Ns>
639   decltype(iterators) tup_inc(std::index_sequence<Ns...>) const {
640     return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
641   }
642 
643   template <size_t... Ns>
644   decltype(iterators) tup_dec(std::index_sequence<Ns...>) const {
645     return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
646   }
647 
648   template <size_t... Ns>
649   bool test_all_equals(const zip_common &other,
650             std::index_sequence<Ns...>) const {
651     return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) ==
652                                               std::get<Ns>(other.iterators)...},
653                   identity<bool>{});
654   }
655 
656 public:
657   zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
658 
659   value_type operator*() const {
660     return deref(std::index_sequence_for<Iters...>{});
661   }
662 
663   ZipType &operator++() {
664     iterators = tup_inc(std::index_sequence_for<Iters...>{});
665     return *reinterpret_cast<ZipType *>(this);
666   }
667 
668   ZipType &operator--() {
669     static_assert(Base::IsBidirectional,
670                   "All inner iterators must be at least bidirectional.");
671     iterators = tup_dec(std::index_sequence_for<Iters...>{});
672     return *reinterpret_cast<ZipType *>(this);
673   }
674 
675   /// Return true if all the iterator are matching `other`'s iterators.
676   bool all_equals(zip_common &other) {
677     return test_all_equals(other, std::index_sequence_for<Iters...>{});
678   }
679 };
680 
681 template <typename... Iters>
682 struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
683   using Base = zip_common<zip_first<Iters...>, Iters...>;
684 
685   bool operator==(const zip_first<Iters...> &other) const {
686     return std::get<0>(this->iterators) == std::get<0>(other.iterators);
687   }
688 
689   zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
690 };
691 
692 template <typename... Iters>
693 class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
694   template <size_t... Ns>
695   bool test(const zip_shortest<Iters...> &other,
696             std::index_sequence<Ns...>) const {
697     return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
698                                               std::get<Ns>(other.iterators)...},
699                   identity<bool>{});
700   }
701 
702 public:
703   using Base = zip_common<zip_shortest<Iters...>, Iters...>;
704 
705   zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
706 
707   bool operator==(const zip_shortest<Iters...> &other) const {
708     return !test(other, std::index_sequence_for<Iters...>{});
709   }
710 };
711 
712 template <template <typename...> class ItType, typename... Args> class zippy {
713 public:
714   using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
715   using iterator_category = typename iterator::iterator_category;
716   using value_type = typename iterator::value_type;
717   using difference_type = typename iterator::difference_type;
718   using pointer = typename iterator::pointer;
719   using reference = typename iterator::reference;
720 
721 private:
722   std::tuple<Args...> ts;
723 
724   template <size_t... Ns>
725   iterator begin_impl(std::index_sequence<Ns...>) const {
726     return iterator(std::begin(std::get<Ns>(ts))...);
727   }
728   template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
729     return iterator(std::end(std::get<Ns>(ts))...);
730   }
731 
732 public:
733   zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
734 
735   iterator begin() const {
736     return begin_impl(std::index_sequence_for<Args...>{});
737   }
738   iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); }
739 };
740 
741 } // end namespace detail
742 
743 /// zip iterator for two or more iteratable types.
744 template <typename T, typename U, typename... Args>
745 detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
746                                                        Args &&... args) {
747   return detail::zippy<detail::zip_shortest, T, U, Args...>(
748       std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
749 }
750 
751 /// zip iterator that, for the sake of efficiency, assumes the first iteratee to
752 /// be the shortest.
753 template <typename T, typename U, typename... Args>
754 detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
755                                                           Args &&... args) {
756   return detail::zippy<detail::zip_first, T, U, Args...>(
757       std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
758 }
759 
760 namespace detail {
761 template <typename Iter>
762 Iter next_or_end(const Iter &I, const Iter &End) {
763   if (I == End)
764     return End;
765   return std::next(I);
766 }
767 
768 template <typename Iter>
769 auto deref_or_none(const Iter &I, const Iter &End) -> llvm::Optional<
770     std::remove_const_t<std::remove_reference_t<decltype(*I)>>> {
771   if (I == End)
772     return None;
773   return *I;
774 }
775 
776 template <typename Iter> struct ZipLongestItemType {
777   using type =
778       llvm::Optional<typename std::remove_const<typename std::remove_reference<
779           decltype(*std::declval<Iter>())>::type>::type>;
780 };
781 
782 template <typename... Iters> struct ZipLongestTupleType {
783   using type = std::tuple<typename ZipLongestItemType<Iters>::type...>;
784 };
785 
786 template <typename... Iters>
787 class zip_longest_iterator
788     : public iterator_facade_base<
789           zip_longest_iterator<Iters...>,
790           typename std::common_type<
791               std::forward_iterator_tag,
792               typename std::iterator_traits<Iters>::iterator_category...>::type,
793           typename ZipLongestTupleType<Iters...>::type,
794           typename std::iterator_traits<typename std::tuple_element<
795               0, std::tuple<Iters...>>::type>::difference_type,
796           typename ZipLongestTupleType<Iters...>::type *,
797           typename ZipLongestTupleType<Iters...>::type> {
798 public:
799   using value_type = typename ZipLongestTupleType<Iters...>::type;
800 
801 private:
802   std::tuple<Iters...> iterators;
803   std::tuple<Iters...> end_iterators;
804 
805   template <size_t... Ns>
806   bool test(const zip_longest_iterator<Iters...> &other,
807             std::index_sequence<Ns...>) const {
808     return llvm::any_of(
809         std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
810                                     std::get<Ns>(other.iterators)...},
811         identity<bool>{});
812   }
813 
814   template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
815     return value_type(
816         deref_or_none(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
817   }
818 
819   template <size_t... Ns>
820   decltype(iterators) tup_inc(std::index_sequence<Ns...>) const {
821     return std::tuple<Iters...>(
822         next_or_end(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
823   }
824 
825 public:
826   zip_longest_iterator(std::pair<Iters &&, Iters &&>... ts)
827       : iterators(std::forward<Iters>(ts.first)...),
828         end_iterators(std::forward<Iters>(ts.second)...) {}
829 
830   value_type operator*() const {
831     return deref(std::index_sequence_for<Iters...>{});
832   }
833 
834   zip_longest_iterator<Iters...> &operator++() {
835     iterators = tup_inc(std::index_sequence_for<Iters...>{});
836     return *this;
837   }
838 
839   bool operator==(const zip_longest_iterator<Iters...> &other) const {
840     return !test(other, std::index_sequence_for<Iters...>{});
841   }
842 };
843 
844 template <typename... Args> class zip_longest_range {
845 public:
846   using iterator =
847       zip_longest_iterator<decltype(adl_begin(std::declval<Args>()))...>;
848   using iterator_category = typename iterator::iterator_category;
849   using value_type = typename iterator::value_type;
850   using difference_type = typename iterator::difference_type;
851   using pointer = typename iterator::pointer;
852   using reference = typename iterator::reference;
853 
854 private:
855   std::tuple<Args...> ts;
856 
857   template <size_t... Ns>
858   iterator begin_impl(std::index_sequence<Ns...>) const {
859     return iterator(std::make_pair(adl_begin(std::get<Ns>(ts)),
860                                    adl_end(std::get<Ns>(ts)))...);
861   }
862 
863   template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
864     return iterator(std::make_pair(adl_end(std::get<Ns>(ts)),
865                                    adl_end(std::get<Ns>(ts)))...);
866   }
867 
868 public:
869   zip_longest_range(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
870 
871   iterator begin() const {
872     return begin_impl(std::index_sequence_for<Args...>{});
873   }
874   iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); }
875 };
876 } // namespace detail
877 
878 /// Iterate over two or more iterators at the same time. Iteration continues
879 /// until all iterators reach the end. The llvm::Optional only contains a value
880 /// if the iterator has not reached the end.
881 template <typename T, typename U, typename... Args>
882 detail::zip_longest_range<T, U, Args...> zip_longest(T &&t, U &&u,
883                                                      Args &&... args) {
884   return detail::zip_longest_range<T, U, Args...>(
885       std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
886 }
887 
888 /// Iterator wrapper that concatenates sequences together.
889 ///
890 /// This can concatenate different iterators, even with different types, into
891 /// a single iterator provided the value types of all the concatenated
892 /// iterators expose `reference` and `pointer` types that can be converted to
893 /// `ValueT &` and `ValueT *` respectively. It doesn't support more
894 /// interesting/customized pointer or reference types.
895 ///
896 /// Currently this only supports forward or higher iterator categories as
897 /// inputs and always exposes a forward iterator interface.
898 template <typename ValueT, typename... IterTs>
899 class concat_iterator
900     : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
901                                   std::forward_iterator_tag, ValueT> {
902   using BaseT = typename concat_iterator::iterator_facade_base;
903 
904   /// We store both the current and end iterators for each concatenated
905   /// sequence in a tuple of pairs.
906   ///
907   /// Note that something like iterator_range seems nice at first here, but the
908   /// range properties are of little benefit and end up getting in the way
909   /// because we need to do mutation on the current iterators.
910   std::tuple<IterTs...> Begins;
911   std::tuple<IterTs...> Ends;
912 
913   /// Attempts to increment a specific iterator.
914   ///
915   /// Returns true if it was able to increment the iterator. Returns false if
916   /// the iterator is already at the end iterator.
917   template <size_t Index> bool incrementHelper() {
918     auto &Begin = std::get<Index>(Begins);
919     auto &End = std::get<Index>(Ends);
920     if (Begin == End)
921       return false;
922 
923     ++Begin;
924     return true;
925   }
926 
927   /// Increments the first non-end iterator.
928   ///
929   /// It is an error to call this with all iterators at the end.
930   template <size_t... Ns> void increment(std::index_sequence<Ns...>) {
931     // Build a sequence of functions to increment each iterator if possible.
932     bool (concat_iterator::*IncrementHelperFns[])() = {
933         &concat_iterator::incrementHelper<Ns>...};
934 
935     // Loop over them, and stop as soon as we succeed at incrementing one.
936     for (auto &IncrementHelperFn : IncrementHelperFns)
937       if ((this->*IncrementHelperFn)())
938         return;
939 
940     llvm_unreachable("Attempted to increment an end concat iterator!");
941   }
942 
943   /// Returns null if the specified iterator is at the end. Otherwise,
944   /// dereferences the iterator and returns the address of the resulting
945   /// reference.
946   template <size_t Index> ValueT *getHelper() const {
947     auto &Begin = std::get<Index>(Begins);
948     auto &End = std::get<Index>(Ends);
949     if (Begin == End)
950       return nullptr;
951 
952     return &*Begin;
953   }
954 
955   /// Finds the first non-end iterator, dereferences, and returns the resulting
956   /// reference.
957   ///
958   /// It is an error to call this with all iterators at the end.
959   template <size_t... Ns> ValueT &get(std::index_sequence<Ns...>) const {
960     // Build a sequence of functions to get from iterator if possible.
961     ValueT *(concat_iterator::*GetHelperFns[])() const = {
962         &concat_iterator::getHelper<Ns>...};
963 
964     // Loop over them, and return the first result we find.
965     for (auto &GetHelperFn : GetHelperFns)
966       if (ValueT *P = (this->*GetHelperFn)())
967         return *P;
968 
969     llvm_unreachable("Attempted to get a pointer from an end concat iterator!");
970   }
971 
972 public:
973   /// Constructs an iterator from a sequence of ranges.
974   ///
975   /// We need the full range to know how to switch between each of the
976   /// iterators.
977   template <typename... RangeTs>
978   explicit concat_iterator(RangeTs &&... Ranges)
979       : Begins(std::begin(Ranges)...), Ends(std::end(Ranges)...) {}
980 
981   using BaseT::operator++;
982 
983   concat_iterator &operator++() {
984     increment(std::index_sequence_for<IterTs...>());
985     return *this;
986   }
987 
988   ValueT &operator*() const {
989     return get(std::index_sequence_for<IterTs...>());
990   }
991 
992   bool operator==(const concat_iterator &RHS) const {
993     return Begins == RHS.Begins && Ends == RHS.Ends;
994   }
995 };
996 
997 namespace detail {
998 
999 /// Helper to store a sequence of ranges being concatenated and access them.
1000 ///
1001 /// This is designed to facilitate providing actual storage when temporaries
1002 /// are passed into the constructor such that we can use it as part of range
1003 /// based for loops.
1004 template <typename ValueT, typename... RangeTs> class concat_range {
1005 public:
1006   using iterator =
1007       concat_iterator<ValueT,
1008                       decltype(std::begin(std::declval<RangeTs &>()))...>;
1009 
1010 private:
1011   std::tuple<RangeTs...> Ranges;
1012 
1013   template <size_t... Ns>
1014   iterator begin_impl(std::index_sequence<Ns...>) {
1015     return iterator(std::get<Ns>(Ranges)...);
1016   }
1017   template <size_t... Ns>
1018   iterator begin_impl(std::index_sequence<Ns...>) const {
1019     return iterator(std::get<Ns>(Ranges)...);
1020   }
1021   template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) {
1022     return iterator(make_range(std::end(std::get<Ns>(Ranges)),
1023                                std::end(std::get<Ns>(Ranges)))...);
1024   }
1025   template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
1026     return iterator(make_range(std::end(std::get<Ns>(Ranges)),
1027                                std::end(std::get<Ns>(Ranges)))...);
1028   }
1029 
1030 public:
1031   concat_range(RangeTs &&... Ranges)
1032       : Ranges(std::forward<RangeTs>(Ranges)...) {}
1033 
1034   iterator begin() {
1035     return begin_impl(std::index_sequence_for<RangeTs...>{});
1036   }
1037   iterator begin() const {
1038     return begin_impl(std::index_sequence_for<RangeTs...>{});
1039   }
1040   iterator end() {
1041     return end_impl(std::index_sequence_for<RangeTs...>{});
1042   }
1043   iterator end() const {
1044     return end_impl(std::index_sequence_for<RangeTs...>{});
1045   }
1046 };
1047 
1048 } // end namespace detail
1049 
1050 /// Concatenated range across two or more ranges.
1051 ///
1052 /// The desired value type must be explicitly specified.
1053 template <typename ValueT, typename... RangeTs>
1054 detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
1055   static_assert(sizeof...(RangeTs) > 1,
1056                 "Need more than one range to concatenate!");
1057   return detail::concat_range<ValueT, RangeTs...>(
1058       std::forward<RangeTs>(Ranges)...);
1059 }
1060 
1061 /// A utility class used to implement an iterator that contains some base object
1062 /// and an index. The iterator moves the index but keeps the base constant.
1063 template <typename DerivedT, typename BaseT, typename T,
1064           typename PointerT = T *, typename ReferenceT = T &>
1065 class indexed_accessor_iterator
1066     : public llvm::iterator_facade_base<DerivedT,
1067                                         std::random_access_iterator_tag, T,
1068                                         std::ptrdiff_t, PointerT, ReferenceT> {
1069 public:
1070   ptrdiff_t operator-(const indexed_accessor_iterator &rhs) const {
1071     assert(base == rhs.base && "incompatible iterators");
1072     return index - rhs.index;
1073   }
1074   bool operator==(const indexed_accessor_iterator &rhs) const {
1075     return base == rhs.base && index == rhs.index;
1076   }
1077   bool operator<(const indexed_accessor_iterator &rhs) const {
1078     assert(base == rhs.base && "incompatible iterators");
1079     return index < rhs.index;
1080   }
1081 
1082   DerivedT &operator+=(ptrdiff_t offset) {
1083     this->index += offset;
1084     return static_cast<DerivedT &>(*this);
1085   }
1086   DerivedT &operator-=(ptrdiff_t offset) {
1087     this->index -= offset;
1088     return static_cast<DerivedT &>(*this);
1089   }
1090 
1091   /// Returns the current index of the iterator.
1092   ptrdiff_t getIndex() const { return index; }
1093 
1094   /// Returns the current base of the iterator.
1095   const BaseT &getBase() const { return base; }
1096 
1097 protected:
1098   indexed_accessor_iterator(BaseT base, ptrdiff_t index)
1099       : base(base), index(index) {}
1100   BaseT base;
1101   ptrdiff_t index;
1102 };
1103 
1104 namespace detail {
1105 /// The class represents the base of a range of indexed_accessor_iterators. It
1106 /// provides support for many different range functionalities, e.g.
1107 /// drop_front/slice/etc.. Derived range classes must implement the following
1108 /// static methods:
1109 ///   * ReferenceT dereference_iterator(const BaseT &base, ptrdiff_t index)
1110 ///     - Dereference an iterator pointing to the base object at the given
1111 ///       index.
1112 ///   * BaseT offset_base(const BaseT &base, ptrdiff_t index)
1113 ///     - Return a new base that is offset from the provide base by 'index'
1114 ///       elements.
1115 template <typename DerivedT, typename BaseT, typename T,
1116           typename PointerT = T *, typename ReferenceT = T &>
1117 class indexed_accessor_range_base {
1118 public:
1119   using RangeBaseT = indexed_accessor_range_base;
1120 
1121   /// An iterator element of this range.
1122   class iterator : public indexed_accessor_iterator<iterator, BaseT, T,
1123                                                     PointerT, ReferenceT> {
1124   public:
1125     // Index into this iterator, invoking a static method on the derived type.
1126     ReferenceT operator*() const {
1127       return DerivedT::dereference_iterator(this->getBase(), this->getIndex());
1128     }
1129 
1130   private:
1131     iterator(BaseT owner, ptrdiff_t curIndex)
1132         : iterator::indexed_accessor_iterator(owner, curIndex) {}
1133 
1134     /// Allow access to the constructor.
1135     friend indexed_accessor_range_base<DerivedT, BaseT, T, PointerT,
1136                                        ReferenceT>;
1137   };
1138 
1139   indexed_accessor_range_base(iterator begin, iterator end)
1140       : base(offset_base(begin.getBase(), begin.getIndex())),
1141         count(end.getIndex() - begin.getIndex()) {}
1142   indexed_accessor_range_base(const iterator_range<iterator> &range)
1143       : indexed_accessor_range_base(range.begin(), range.end()) {}
1144   indexed_accessor_range_base(BaseT base, ptrdiff_t count)
1145       : base(base), count(count) {}
1146 
1147   iterator begin() const { return iterator(base, 0); }
1148   iterator end() const { return iterator(base, count); }
1149   ReferenceT operator[](size_t Index) const {
1150     assert(Index < size() && "invalid index for value range");
1151     return DerivedT::dereference_iterator(base, static_cast<ptrdiff_t>(Index));
1152   }
1153   ReferenceT front() const {
1154     assert(!empty() && "expected non-empty range");
1155     return (*this)[0];
1156   }
1157   ReferenceT back() const {
1158     assert(!empty() && "expected non-empty range");
1159     return (*this)[size() - 1];
1160   }
1161 
1162   /// Compare this range with another.
1163   template <typename OtherT> bool operator==(const OtherT &other) const {
1164     return size() ==
1165                static_cast<size_t>(std::distance(other.begin(), other.end())) &&
1166            std::equal(begin(), end(), other.begin());
1167   }
1168   template <typename OtherT> bool operator!=(const OtherT &other) const {
1169     return !(*this == other);
1170   }
1171 
1172   /// Return the size of this range.
1173   size_t size() const { return count; }
1174 
1175   /// Return if the range is empty.
1176   bool empty() const { return size() == 0; }
1177 
1178   /// Drop the first N elements, and keep M elements.
1179   DerivedT slice(size_t n, size_t m) const {
1180     assert(n + m <= size() && "invalid size specifiers");
1181     return DerivedT(offset_base(base, n), m);
1182   }
1183 
1184   /// Drop the first n elements.
1185   DerivedT drop_front(size_t n = 1) const {
1186     assert(size() >= n && "Dropping more elements than exist");
1187     return slice(n, size() - n);
1188   }
1189   /// Drop the last n elements.
1190   DerivedT drop_back(size_t n = 1) const {
1191     assert(size() >= n && "Dropping more elements than exist");
1192     return DerivedT(base, size() - n);
1193   }
1194 
1195   /// Take the first n elements.
1196   DerivedT take_front(size_t n = 1) const {
1197     return n < size() ? drop_back(size() - n)
1198                       : static_cast<const DerivedT &>(*this);
1199   }
1200 
1201   /// Take the last n elements.
1202   DerivedT take_back(size_t n = 1) const {
1203     return n < size() ? drop_front(size() - n)
1204                       : static_cast<const DerivedT &>(*this);
1205   }
1206 
1207   /// Allow conversion to any type accepting an iterator_range.
1208   template <typename RangeT, typename = std::enable_if_t<std::is_constructible<
1209                                  RangeT, iterator_range<iterator>>::value>>
1210   operator RangeT() const {
1211     return RangeT(iterator_range<iterator>(*this));
1212   }
1213 
1214   /// Returns the base of this range.
1215   const BaseT &getBase() const { return base; }
1216 
1217 private:
1218   /// Offset the given base by the given amount.
1219   static BaseT offset_base(const BaseT &base, size_t n) {
1220     return n == 0 ? base : DerivedT::offset_base(base, n);
1221   }
1222 
1223 protected:
1224   indexed_accessor_range_base(const indexed_accessor_range_base &) = default;
1225   indexed_accessor_range_base(indexed_accessor_range_base &&) = default;
1226   indexed_accessor_range_base &
1227   operator=(const indexed_accessor_range_base &) = default;
1228 
1229   /// The base that owns the provided range of values.
1230   BaseT base;
1231   /// The size from the owning range.
1232   ptrdiff_t count;
1233 };
1234 } // end namespace detail
1235 
1236 /// This class provides an implementation of a range of
1237 /// indexed_accessor_iterators where the base is not indexable. Ranges with
1238 /// bases that are offsetable should derive from indexed_accessor_range_base
1239 /// instead. Derived range classes are expected to implement the following
1240 /// static method:
1241 ///   * ReferenceT dereference(const BaseT &base, ptrdiff_t index)
1242 ///     - Dereference an iterator pointing to a parent base at the given index.
1243 template <typename DerivedT, typename BaseT, typename T,
1244           typename PointerT = T *, typename ReferenceT = T &>
1245 class indexed_accessor_range
1246     : public detail::indexed_accessor_range_base<
1247           DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT> {
1248 public:
1249   indexed_accessor_range(BaseT base, ptrdiff_t startIndex, ptrdiff_t count)
1250       : detail::indexed_accessor_range_base<
1251             DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT>(
1252             std::make_pair(base, startIndex), count) {}
1253   using detail::indexed_accessor_range_base<
1254       DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT,
1255       ReferenceT>::indexed_accessor_range_base;
1256 
1257   /// Returns the current base of the range.
1258   const BaseT &getBase() const { return this->base.first; }
1259 
1260   /// Returns the current start index of the range.
1261   ptrdiff_t getStartIndex() const { return this->base.second; }
1262 
1263   /// See `detail::indexed_accessor_range_base` for details.
1264   static std::pair<BaseT, ptrdiff_t>
1265   offset_base(const std::pair<BaseT, ptrdiff_t> &base, ptrdiff_t index) {
1266     // We encode the internal base as a pair of the derived base and a start
1267     // index into the derived base.
1268     return std::make_pair(base.first, base.second + index);
1269   }
1270   /// See `detail::indexed_accessor_range_base` for details.
1271   static ReferenceT
1272   dereference_iterator(const std::pair<BaseT, ptrdiff_t> &base,
1273                        ptrdiff_t index) {
1274     return DerivedT::dereference(base.first, base.second + index);
1275   }
1276 };
1277 
1278 namespace detail {
1279 /// Return a reference to the first or second member of a reference. Otherwise,
1280 /// return a copy of the member of a temporary.
1281 ///
1282 /// When passing a range whose iterators return values instead of references,
1283 /// the reference must be dropped from `decltype((elt.first))`, which will
1284 /// always be a reference, to avoid returning a reference to a temporary.
1285 template <typename EltTy, typename FirstTy> class first_or_second_type {
1286 public:
1287   using type =
1288       typename std::conditional_t<std::is_reference<EltTy>::value, FirstTy,
1289                                   std::remove_reference_t<FirstTy>>;
1290 };
1291 } // end namespace detail
1292 
1293 /// Given a container of pairs, return a range over the first elements.
1294 template <typename ContainerTy> auto make_first_range(ContainerTy &&c) {
1295   using EltTy = decltype((*std::begin(c)));
1296   return llvm::map_range(std::forward<ContainerTy>(c),
1297                          [](EltTy elt) -> typename detail::first_or_second_type<
1298                                            EltTy, decltype((elt.first))>::type {
1299                            return elt.first;
1300                          });
1301 }
1302 
1303 /// Given a container of pairs, return a range over the second elements.
1304 template <typename ContainerTy> auto make_second_range(ContainerTy &&c) {
1305   using EltTy = decltype((*std::begin(c)));
1306   return llvm::map_range(
1307       std::forward<ContainerTy>(c),
1308       [](EltTy elt) ->
1309       typename detail::first_or_second_type<EltTy,
1310                                             decltype((elt.second))>::type {
1311         return elt.second;
1312       });
1313 }
1314 
1315 //===----------------------------------------------------------------------===//
1316 //     Extra additions to <utility>
1317 //===----------------------------------------------------------------------===//
1318 
1319 /// Function object to check whether the first component of a std::pair
1320 /// compares less than the first component of another std::pair.
1321 struct less_first {
1322   template <typename T> bool operator()(const T &lhs, const T &rhs) const {
1323     return std::less<>()(lhs.first, rhs.first);
1324   }
1325 };
1326 
1327 /// Function object to check whether the second component of a std::pair
1328 /// compares less than the second component of another std::pair.
1329 struct less_second {
1330   template <typename T> bool operator()(const T &lhs, const T &rhs) const {
1331     return std::less<>()(lhs.second, rhs.second);
1332   }
1333 };
1334 
1335 /// \brief Function object to apply a binary function to the first component of
1336 /// a std::pair.
1337 template<typename FuncTy>
1338 struct on_first {
1339   FuncTy func;
1340 
1341   template <typename T>
1342   decltype(auto) operator()(const T &lhs, const T &rhs) const {
1343     return func(lhs.first, rhs.first);
1344   }
1345 };
1346 
1347 /// Utility type to build an inheritance chain that makes it easy to rank
1348 /// overload candidates.
1349 template <int N> struct rank : rank<N - 1> {};
1350 template <> struct rank<0> {};
1351 
1352 /// traits class for checking whether type T is one of any of the given
1353 /// types in the variadic list.
1354 template <typename T, typename... Ts>
1355 using is_one_of = disjunction<std::is_same<T, Ts>...>;
1356 
1357 /// traits class for checking whether type T is a base class for all
1358 ///  the given types in the variadic list.
1359 template <typename T, typename... Ts>
1360 using are_base_of = conjunction<std::is_base_of<T, Ts>...>;
1361 
1362 namespace detail {
1363 template <typename... Ts> struct Visitor;
1364 
1365 template <typename HeadT, typename... TailTs>
1366 struct Visitor<HeadT, TailTs...> : remove_cvref_t<HeadT>, Visitor<TailTs...> {
1367   explicit constexpr Visitor(HeadT &&Head, TailTs &&...Tail)
1368       : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)),
1369         Visitor<TailTs...>(std::forward<TailTs>(Tail)...) {}
1370   using remove_cvref_t<HeadT>::operator();
1371   using Visitor<TailTs...>::operator();
1372 };
1373 
1374 template <typename HeadT> struct Visitor<HeadT> : remove_cvref_t<HeadT> {
1375   explicit constexpr Visitor(HeadT &&Head)
1376       : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)) {}
1377   using remove_cvref_t<HeadT>::operator();
1378 };
1379 } // namespace detail
1380 
1381 /// Returns an opaquely-typed Callable object whose operator() overload set is
1382 /// the sum of the operator() overload sets of each CallableT in CallableTs.
1383 ///
1384 /// The type of the returned object derives from each CallableT in CallableTs.
1385 /// The returned object is constructed by invoking the appropriate copy or move
1386 /// constructor of each CallableT, as selected by overload resolution on the
1387 /// corresponding argument to makeVisitor.
1388 ///
1389 /// Example:
1390 ///
1391 /// \code
1392 /// auto visitor = makeVisitor([](auto) { return "unhandled type"; },
1393 ///                            [](int i) { return "int"; },
1394 ///                            [](std::string s) { return "str"; });
1395 /// auto a = visitor(42);    // `a` is now "int".
1396 /// auto b = visitor("foo"); // `b` is now "str".
1397 /// auto c = visitor(3.14f); // `c` is now "unhandled type".
1398 /// \endcode
1399 ///
1400 /// Example of making a visitor with a lambda which captures a move-only type:
1401 ///
1402 /// \code
1403 /// std::unique_ptr<FooHandler> FH = /* ... */;
1404 /// auto visitor = makeVisitor(
1405 ///     [FH{std::move(FH)}](Foo F) { return FH->handle(F); },
1406 ///     [](int i) { return i; },
1407 ///     [](std::string s) { return atoi(s); });
1408 /// \endcode
1409 template <typename... CallableTs>
1410 constexpr decltype(auto) makeVisitor(CallableTs &&...Callables) {
1411   return detail::Visitor<CallableTs...>(std::forward<CallableTs>(Callables)...);
1412 }
1413 
1414 //===----------------------------------------------------------------------===//
1415 //     Extra additions to <algorithm>
1416 //===----------------------------------------------------------------------===//
1417 
1418 // We have a copy here so that LLVM behaves the same when using different
1419 // standard libraries.
1420 template <class Iterator, class RNG>
1421 void shuffle(Iterator first, Iterator last, RNG &&g) {
1422   // It would be better to use a std::uniform_int_distribution,
1423   // but that would be stdlib dependent.
1424   typedef
1425       typename std::iterator_traits<Iterator>::difference_type difference_type;
1426   for (auto size = last - first; size > 1; ++first, (void)--size) {
1427     difference_type offset = g() % size;
1428     // Avoid self-assignment due to incorrect assertions in libstdc++
1429     // containers (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85828).
1430     if (offset != difference_type(0))
1431       std::iter_swap(first, first + offset);
1432   }
1433 }
1434 
1435 /// Adapt std::less<T> for array_pod_sort.
1436 template<typename T>
1437 inline int array_pod_sort_comparator(const void *P1, const void *P2) {
1438   if (std::less<T>()(*reinterpret_cast<const T*>(P1),
1439                      *reinterpret_cast<const T*>(P2)))
1440     return -1;
1441   if (std::less<T>()(*reinterpret_cast<const T*>(P2),
1442                      *reinterpret_cast<const T*>(P1)))
1443     return 1;
1444   return 0;
1445 }
1446 
1447 /// get_array_pod_sort_comparator - This is an internal helper function used to
1448 /// get type deduction of T right.
1449 template<typename T>
1450 inline int (*get_array_pod_sort_comparator(const T &))
1451              (const void*, const void*) {
1452   return array_pod_sort_comparator<T>;
1453 }
1454 
1455 #ifdef EXPENSIVE_CHECKS
1456 namespace detail {
1457 
1458 inline unsigned presortShuffleEntropy() {
1459   static unsigned Result(std::random_device{}());
1460   return Result;
1461 }
1462 
1463 template <class IteratorTy>
1464 inline void presortShuffle(IteratorTy Start, IteratorTy End) {
1465   std::mt19937 Generator(presortShuffleEntropy());
1466   llvm::shuffle(Start, End, Generator);
1467 }
1468 
1469 } // end namespace detail
1470 #endif
1471 
1472 /// array_pod_sort - This sorts an array with the specified start and end
1473 /// extent.  This is just like std::sort, except that it calls qsort instead of
1474 /// using an inlined template.  qsort is slightly slower than std::sort, but
1475 /// most sorts are not performance critical in LLVM and std::sort has to be
1476 /// template instantiated for each type, leading to significant measured code
1477 /// bloat.  This function should generally be used instead of std::sort where
1478 /// possible.
1479 ///
1480 /// This function assumes that you have simple POD-like types that can be
1481 /// compared with std::less and can be moved with memcpy.  If this isn't true,
1482 /// you should use std::sort.
1483 ///
1484 /// NOTE: If qsort_r were portable, we could allow a custom comparator and
1485 /// default to std::less.
1486 template<class IteratorTy>
1487 inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
1488   // Don't inefficiently call qsort with one element or trigger undefined
1489   // behavior with an empty sequence.
1490   auto NElts = End - Start;
1491   if (NElts <= 1) return;
1492 #ifdef EXPENSIVE_CHECKS
1493   detail::presortShuffle<IteratorTy>(Start, End);
1494 #endif
1495   qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
1496 }
1497 
1498 template <class IteratorTy>
1499 inline void array_pod_sort(
1500     IteratorTy Start, IteratorTy End,
1501     int (*Compare)(
1502         const typename std::iterator_traits<IteratorTy>::value_type *,
1503         const typename std::iterator_traits<IteratorTy>::value_type *)) {
1504   // Don't inefficiently call qsort with one element or trigger undefined
1505   // behavior with an empty sequence.
1506   auto NElts = End - Start;
1507   if (NElts <= 1) return;
1508 #ifdef EXPENSIVE_CHECKS
1509   detail::presortShuffle<IteratorTy>(Start, End);
1510 #endif
1511   qsort(&*Start, NElts, sizeof(*Start),
1512         reinterpret_cast<int (*)(const void *, const void *)>(Compare));
1513 }
1514 
1515 namespace detail {
1516 template <typename T>
1517 // We can use qsort if the iterator type is a pointer and the underlying value
1518 // is trivially copyable.
1519 using sort_trivially_copyable = conjunction<
1520     std::is_pointer<T>,
1521     std::is_trivially_copyable<typename std::iterator_traits<T>::value_type>>;
1522 } // namespace detail
1523 
1524 // Provide wrappers to std::sort which shuffle the elements before sorting
1525 // to help uncover non-deterministic behavior (PR35135).
1526 template <typename IteratorTy,
1527           std::enable_if_t<!detail::sort_trivially_copyable<IteratorTy>::value,
1528                            int> = 0>
1529 inline void sort(IteratorTy Start, IteratorTy End) {
1530 #ifdef EXPENSIVE_CHECKS
1531   detail::presortShuffle<IteratorTy>(Start, End);
1532 #endif
1533   std::sort(Start, End);
1534 }
1535 
1536 // Forward trivially copyable types to array_pod_sort. This avoids a large
1537 // amount of code bloat for a minor performance hit.
1538 template <typename IteratorTy,
1539           std::enable_if_t<detail::sort_trivially_copyable<IteratorTy>::value,
1540                            int> = 0>
1541 inline void sort(IteratorTy Start, IteratorTy End) {
1542   array_pod_sort(Start, End);
1543 }
1544 
1545 template <typename Container> inline void sort(Container &&C) {
1546   llvm::sort(adl_begin(C), adl_end(C));
1547 }
1548 
1549 template <typename IteratorTy, typename Compare>
1550 inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
1551 #ifdef EXPENSIVE_CHECKS
1552   detail::presortShuffle<IteratorTy>(Start, End);
1553 #endif
1554   std::sort(Start, End, Comp);
1555 }
1556 
1557 template <typename Container, typename Compare>
1558 inline void sort(Container &&C, Compare Comp) {
1559   llvm::sort(adl_begin(C), adl_end(C), Comp);
1560 }
1561 
1562 /// Get the size of a range. This is a wrapper function around std::distance
1563 /// which is only enabled when the operation is O(1).
1564 template <typename R>
1565 auto size(R &&Range,
1566           std::enable_if_t<
1567               std::is_base_of<std::random_access_iterator_tag,
1568                               typename std::iterator_traits<decltype(
1569                                   Range.begin())>::iterator_category>::value,
1570               void> * = nullptr) {
1571   return std::distance(Range.begin(), Range.end());
1572 }
1573 
1574 /// Provide wrappers to std::for_each which take ranges instead of having to
1575 /// pass begin/end explicitly.
1576 template <typename R, typename UnaryFunction>
1577 UnaryFunction for_each(R &&Range, UnaryFunction F) {
1578   return std::for_each(adl_begin(Range), adl_end(Range), F);
1579 }
1580 
1581 /// Provide wrappers to std::all_of which take ranges instead of having to pass
1582 /// begin/end explicitly.
1583 template <typename R, typename UnaryPredicate>
1584 bool all_of(R &&Range, UnaryPredicate P) {
1585   return std::all_of(adl_begin(Range), adl_end(Range), P);
1586 }
1587 
1588 /// Provide wrappers to std::any_of which take ranges instead of having to pass
1589 /// begin/end explicitly.
1590 template <typename R, typename UnaryPredicate>
1591 bool any_of(R &&Range, UnaryPredicate P) {
1592   return std::any_of(adl_begin(Range), adl_end(Range), P);
1593 }
1594 
1595 /// Provide wrappers to std::none_of which take ranges instead of having to pass
1596 /// begin/end explicitly.
1597 template <typename R, typename UnaryPredicate>
1598 bool none_of(R &&Range, UnaryPredicate P) {
1599   return std::none_of(adl_begin(Range), adl_end(Range), P);
1600 }
1601 
1602 /// Provide wrappers to std::find which take ranges instead of having to pass
1603 /// begin/end explicitly.
1604 template <typename R, typename T> auto find(R &&Range, const T &Val) {
1605   return std::find(adl_begin(Range), adl_end(Range), Val);
1606 }
1607 
1608 /// Provide wrappers to std::find_if which take ranges instead of having to pass
1609 /// begin/end explicitly.
1610 template <typename R, typename UnaryPredicate>
1611 auto find_if(R &&Range, UnaryPredicate P) {
1612   return std::find_if(adl_begin(Range), adl_end(Range), P);
1613 }
1614 
1615 template <typename R, typename UnaryPredicate>
1616 auto find_if_not(R &&Range, UnaryPredicate P) {
1617   return std::find_if_not(adl_begin(Range), adl_end(Range), P);
1618 }
1619 
1620 /// Provide wrappers to std::remove_if which take ranges instead of having to
1621 /// pass begin/end explicitly.
1622 template <typename R, typename UnaryPredicate>
1623 auto remove_if(R &&Range, UnaryPredicate P) {
1624   return std::remove_if(adl_begin(Range), adl_end(Range), P);
1625 }
1626 
1627 /// Provide wrappers to std::copy_if which take ranges instead of having to
1628 /// pass begin/end explicitly.
1629 template <typename R, typename OutputIt, typename UnaryPredicate>
1630 OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
1631   return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
1632 }
1633 
1634 template <typename R, typename OutputIt>
1635 OutputIt copy(R &&Range, OutputIt Out) {
1636   return std::copy(adl_begin(Range), adl_end(Range), Out);
1637 }
1638 
1639 /// Provide wrappers to std::move which take ranges instead of having to
1640 /// pass begin/end explicitly.
1641 template <typename R, typename OutputIt>
1642 OutputIt move(R &&Range, OutputIt Out) {
1643   return std::move(adl_begin(Range), adl_end(Range), Out);
1644 }
1645 
1646 /// Wrapper function around std::find to detect if an element exists
1647 /// in a container.
1648 template <typename R, typename E>
1649 bool is_contained(R &&Range, const E &Element) {
1650   return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
1651 }
1652 
1653 /// Wrapper function around std::is_sorted to check if elements in a range \p R
1654 /// are sorted with respect to a comparator \p C.
1655 template <typename R, typename Compare> bool is_sorted(R &&Range, Compare C) {
1656   return std::is_sorted(adl_begin(Range), adl_end(Range), C);
1657 }
1658 
1659 /// Wrapper function around std::is_sorted to check if elements in a range \p R
1660 /// are sorted in non-descending order.
1661 template <typename R> bool is_sorted(R &&Range) {
1662   return std::is_sorted(adl_begin(Range), adl_end(Range));
1663 }
1664 
1665 /// Wrapper function around std::count to count the number of times an element
1666 /// \p Element occurs in the given range \p Range.
1667 template <typename R, typename E> auto count(R &&Range, const E &Element) {
1668   return std::count(adl_begin(Range), adl_end(Range), Element);
1669 }
1670 
1671 /// Wrapper function around std::count_if to count the number of times an
1672 /// element satisfying a given predicate occurs in a range.
1673 template <typename R, typename UnaryPredicate>
1674 auto count_if(R &&Range, UnaryPredicate P) {
1675   return std::count_if(adl_begin(Range), adl_end(Range), P);
1676 }
1677 
1678 /// Wrapper function around std::transform to apply a function to a range and
1679 /// store the result elsewhere.
1680 template <typename R, typename OutputIt, typename UnaryFunction>
1681 OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F) {
1682   return std::transform(adl_begin(Range), adl_end(Range), d_first, F);
1683 }
1684 
1685 /// Provide wrappers to std::partition which take ranges instead of having to
1686 /// pass begin/end explicitly.
1687 template <typename R, typename UnaryPredicate>
1688 auto partition(R &&Range, UnaryPredicate P) {
1689   return std::partition(adl_begin(Range), adl_end(Range), P);
1690 }
1691 
1692 /// Provide wrappers to std::lower_bound which take ranges instead of having to
1693 /// pass begin/end explicitly.
1694 template <typename R, typename T> auto lower_bound(R &&Range, T &&Value) {
1695   return std::lower_bound(adl_begin(Range), adl_end(Range),
1696                           std::forward<T>(Value));
1697 }
1698 
1699 template <typename R, typename T, typename Compare>
1700 auto lower_bound(R &&Range, T &&Value, Compare C) {
1701   return std::lower_bound(adl_begin(Range), adl_end(Range),
1702                           std::forward<T>(Value), C);
1703 }
1704 
1705 /// Provide wrappers to std::upper_bound which take ranges instead of having to
1706 /// pass begin/end explicitly.
1707 template <typename R, typename T> auto upper_bound(R &&Range, T &&Value) {
1708   return std::upper_bound(adl_begin(Range), adl_end(Range),
1709                           std::forward<T>(Value));
1710 }
1711 
1712 template <typename R, typename T, typename Compare>
1713 auto upper_bound(R &&Range, T &&Value, Compare C) {
1714   return std::upper_bound(adl_begin(Range), adl_end(Range),
1715                           std::forward<T>(Value), C);
1716 }
1717 
1718 template <typename R>
1719 void stable_sort(R &&Range) {
1720   std::stable_sort(adl_begin(Range), adl_end(Range));
1721 }
1722 
1723 template <typename R, typename Compare>
1724 void stable_sort(R &&Range, Compare C) {
1725   std::stable_sort(adl_begin(Range), adl_end(Range), C);
1726 }
1727 
1728 /// Binary search for the first iterator in a range where a predicate is false.
1729 /// Requires that C is always true below some limit, and always false above it.
1730 template <typename R, typename Predicate,
1731           typename Val = decltype(*adl_begin(std::declval<R>()))>
1732 auto partition_point(R &&Range, Predicate P) {
1733   return std::partition_point(adl_begin(Range), adl_end(Range), P);
1734 }
1735 
1736 template<typename Range, typename Predicate>
1737 auto unique(Range &&R, Predicate P) {
1738   return std::unique(adl_begin(R), adl_end(R), P);
1739 }
1740 
1741 /// Wrapper function around std::equal to detect if pair-wise elements between
1742 /// two ranges are the same.
1743 template <typename L, typename R> bool equal(L &&LRange, R &&RRange) {
1744   return std::equal(adl_begin(LRange), adl_end(LRange), adl_begin(RRange),
1745                     adl_end(RRange));
1746 }
1747 
1748 /// Wrapper function around std::equal to detect if all elements
1749 /// in a container are same.
1750 template <typename R>
1751 bool is_splat(R &&Range) {
1752   size_t range_size = size(Range);
1753   return range_size != 0 && (range_size == 1 ||
1754          std::equal(adl_begin(Range) + 1, adl_end(Range), adl_begin(Range)));
1755 }
1756 
1757 /// Provide a container algorithm similar to C++ Library Fundamentals v2's
1758 /// `erase_if` which is equivalent to:
1759 ///
1760 ///   C.erase(remove_if(C, pred), C.end());
1761 ///
1762 /// This version works for any container with an erase method call accepting
1763 /// two iterators.
1764 template <typename Container, typename UnaryPredicate>
1765 void erase_if(Container &C, UnaryPredicate P) {
1766   C.erase(remove_if(C, P), C.end());
1767 }
1768 
1769 /// Wrapper function to remove a value from a container:
1770 ///
1771 /// C.erase(remove(C.begin(), C.end(), V), C.end());
1772 template <typename Container, typename ValueType>
1773 void erase_value(Container &C, ValueType V) {
1774   C.erase(std::remove(C.begin(), C.end(), V), C.end());
1775 }
1776 
1777 /// Wrapper function to append a range to a container.
1778 ///
1779 /// C.insert(C.end(), R.begin(), R.end());
1780 template <typename Container, typename Range>
1781 inline void append_range(Container &C, Range &&R) {
1782   C.insert(C.end(), R.begin(), R.end());
1783 }
1784 
1785 /// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
1786 /// the range [ValIt, ValEnd) (which is not from the same container).
1787 template<typename Container, typename RandomAccessIterator>
1788 void replace(Container &Cont, typename Container::iterator ContIt,
1789              typename Container::iterator ContEnd, RandomAccessIterator ValIt,
1790              RandomAccessIterator ValEnd) {
1791   while (true) {
1792     if (ValIt == ValEnd) {
1793       Cont.erase(ContIt, ContEnd);
1794       return;
1795     } else if (ContIt == ContEnd) {
1796       Cont.insert(ContIt, ValIt, ValEnd);
1797       return;
1798     }
1799     *ContIt++ = *ValIt++;
1800   }
1801 }
1802 
1803 /// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
1804 /// the range R.
1805 template<typename Container, typename Range = std::initializer_list<
1806                                  typename Container::value_type>>
1807 void replace(Container &Cont, typename Container::iterator ContIt,
1808              typename Container::iterator ContEnd, Range R) {
1809   replace(Cont, ContIt, ContEnd, R.begin(), R.end());
1810 }
1811 
1812 /// An STL-style algorithm similar to std::for_each that applies a second
1813 /// functor between every pair of elements.
1814 ///
1815 /// This provides the control flow logic to, for example, print a
1816 /// comma-separated list:
1817 /// \code
1818 ///   interleave(names.begin(), names.end(),
1819 ///              [&](StringRef name) { os << name; },
1820 ///              [&] { os << ", "; });
1821 /// \endcode
1822 template <typename ForwardIterator, typename UnaryFunctor,
1823           typename NullaryFunctor,
1824           typename = typename std::enable_if<
1825               !std::is_constructible<StringRef, UnaryFunctor>::value &&
1826               !std::is_constructible<StringRef, NullaryFunctor>::value>::type>
1827 inline void interleave(ForwardIterator begin, ForwardIterator end,
1828                        UnaryFunctor each_fn, NullaryFunctor between_fn) {
1829   if (begin == end)
1830     return;
1831   each_fn(*begin);
1832   ++begin;
1833   for (; begin != end; ++begin) {
1834     between_fn();
1835     each_fn(*begin);
1836   }
1837 }
1838 
1839 template <typename Container, typename UnaryFunctor, typename NullaryFunctor,
1840           typename = typename std::enable_if<
1841               !std::is_constructible<StringRef, UnaryFunctor>::value &&
1842               !std::is_constructible<StringRef, NullaryFunctor>::value>::type>
1843 inline void interleave(const Container &c, UnaryFunctor each_fn,
1844                        NullaryFunctor between_fn) {
1845   interleave(c.begin(), c.end(), each_fn, between_fn);
1846 }
1847 
1848 /// Overload of interleave for the common case of string separator.
1849 template <typename Container, typename UnaryFunctor, typename StreamT,
1850           typename T = detail::ValueOfRange<Container>>
1851 inline void interleave(const Container &c, StreamT &os, UnaryFunctor each_fn,
1852                        const StringRef &separator) {
1853   interleave(c.begin(), c.end(), each_fn, [&] { os << separator; });
1854 }
1855 template <typename Container, typename StreamT,
1856           typename T = detail::ValueOfRange<Container>>
1857 inline void interleave(const Container &c, StreamT &os,
1858                        const StringRef &separator) {
1859   interleave(
1860       c, os, [&](const T &a) { os << a; }, separator);
1861 }
1862 
1863 template <typename Container, typename UnaryFunctor, typename StreamT,
1864           typename T = detail::ValueOfRange<Container>>
1865 inline void interleaveComma(const Container &c, StreamT &os,
1866                             UnaryFunctor each_fn) {
1867   interleave(c, os, each_fn, ", ");
1868 }
1869 template <typename Container, typename StreamT,
1870           typename T = detail::ValueOfRange<Container>>
1871 inline void interleaveComma(const Container &c, StreamT &os) {
1872   interleaveComma(c, os, [&](const T &a) { os << a; });
1873 }
1874 
1875 //===----------------------------------------------------------------------===//
1876 //     Extra additions to <memory>
1877 //===----------------------------------------------------------------------===//
1878 
1879 struct FreeDeleter {
1880   void operator()(void* v) {
1881     ::free(v);
1882   }
1883 };
1884 
1885 template<typename First, typename Second>
1886 struct pair_hash {
1887   size_t operator()(const std::pair<First, Second> &P) const {
1888     return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1889   }
1890 };
1891 
1892 /// Binary functor that adapts to any other binary functor after dereferencing
1893 /// operands.
1894 template <typename T> struct deref {
1895   T func;
1896 
1897   // Could be further improved to cope with non-derivable functors and
1898   // non-binary functors (should be a variadic template member function
1899   // operator()).
1900   template <typename A, typename B> auto operator()(A &lhs, B &rhs) const {
1901     assert(lhs);
1902     assert(rhs);
1903     return func(*lhs, *rhs);
1904   }
1905 };
1906 
1907 namespace detail {
1908 
1909 template <typename R> class enumerator_iter;
1910 
1911 template <typename R> struct result_pair {
1912   using value_reference =
1913       typename std::iterator_traits<IterOfRange<R>>::reference;
1914 
1915   friend class enumerator_iter<R>;
1916 
1917   result_pair() = default;
1918   result_pair(std::size_t Index, IterOfRange<R> Iter)
1919       : Index(Index), Iter(Iter) {}
1920 
1921   result_pair(const result_pair<R> &Other)
1922       : Index(Other.Index), Iter(Other.Iter) {}
1923   result_pair &operator=(const result_pair &Other) {
1924     Index = Other.Index;
1925     Iter = Other.Iter;
1926     return *this;
1927   }
1928 
1929   std::size_t index() const { return Index; }
1930   value_reference value() const { return *Iter; }
1931 
1932 private:
1933   std::size_t Index = std::numeric_limits<std::size_t>::max();
1934   IterOfRange<R> Iter;
1935 };
1936 
1937 template <typename R>
1938 class enumerator_iter
1939     : public iterator_facade_base<enumerator_iter<R>, std::forward_iterator_tag,
1940                                   const result_pair<R>> {
1941   using result_type = result_pair<R>;
1942 
1943 public:
1944   explicit enumerator_iter(IterOfRange<R> EndIter)
1945       : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1946 
1947   enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1948       : Result(Index, Iter) {}
1949 
1950   const result_type &operator*() const { return Result; }
1951 
1952   enumerator_iter &operator++() {
1953     assert(Result.Index != std::numeric_limits<size_t>::max());
1954     ++Result.Iter;
1955     ++Result.Index;
1956     return *this;
1957   }
1958 
1959   bool operator==(const enumerator_iter &RHS) const {
1960     // Don't compare indices here, only iterators.  It's possible for an end
1961     // iterator to have different indices depending on whether it was created
1962     // by calling std::end() versus incrementing a valid iterator.
1963     return Result.Iter == RHS.Result.Iter;
1964   }
1965 
1966   enumerator_iter(const enumerator_iter &Other) : Result(Other.Result) {}
1967   enumerator_iter &operator=(const enumerator_iter &Other) {
1968     Result = Other.Result;
1969     return *this;
1970   }
1971 
1972 private:
1973   result_type Result;
1974 };
1975 
1976 template <typename R> class enumerator {
1977 public:
1978   explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1979 
1980   enumerator_iter<R> begin() {
1981     return enumerator_iter<R>(0, std::begin(TheRange));
1982   }
1983   enumerator_iter<R> begin() const {
1984     return enumerator_iter<R>(0, std::begin(TheRange));
1985   }
1986 
1987   enumerator_iter<R> end() {
1988     return enumerator_iter<R>(std::end(TheRange));
1989   }
1990   enumerator_iter<R> end() const {
1991     return enumerator_iter<R>(std::end(TheRange));
1992   }
1993 
1994 private:
1995   R TheRange;
1996 };
1997 
1998 } // end namespace detail
1999 
2000 /// Given an input range, returns a new range whose values are are pair (A,B)
2001 /// such that A is the 0-based index of the item in the sequence, and B is
2002 /// the value from the original sequence.  Example:
2003 ///
2004 /// std::vector<char> Items = {'A', 'B', 'C', 'D'};
2005 /// for (auto X : enumerate(Items)) {
2006 ///   printf("Item %d - %c\n", X.index(), X.value());
2007 /// }
2008 ///
2009 /// Output:
2010 ///   Item 0 - A
2011 ///   Item 1 - B
2012 ///   Item 2 - C
2013 ///   Item 3 - D
2014 ///
2015 template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
2016   return detail::enumerator<R>(std::forward<R>(TheRange));
2017 }
2018 
2019 namespace detail {
2020 
2021 template <typename F, typename Tuple, std::size_t... I>
2022 decltype(auto) apply_tuple_impl(F &&f, Tuple &&t, std::index_sequence<I...>) {
2023   return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
2024 }
2025 
2026 } // end namespace detail
2027 
2028 /// Given an input tuple (a1, a2, ..., an), pass the arguments of the
2029 /// tuple variadically to f as if by calling f(a1, a2, ..., an) and
2030 /// return the result.
2031 template <typename F, typename Tuple>
2032 decltype(auto) apply_tuple(F &&f, Tuple &&t) {
2033   using Indices = std::make_index_sequence<
2034       std::tuple_size<typename std::decay<Tuple>::type>::value>;
2035 
2036   return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
2037                                   Indices{});
2038 }
2039 
2040 namespace detail {
2041 
2042 template <typename Predicate, typename... Args>
2043 bool all_of_zip_predicate_first(Predicate &&P, Args &&...args) {
2044   auto z = zip(args...);
2045   auto it = z.begin();
2046   auto end = z.end();
2047   while (it != end) {
2048     if (!apply_tuple([&](auto &&...args) { return P(args...); }, *it))
2049       return false;
2050     ++it;
2051   }
2052   return it.all_equals(end);
2053 }
2054 
2055 // Just an adaptor to switch the order of argument and have the predicate before
2056 // the zipped inputs.
2057 template <typename... ArgsThenPredicate, size_t... InputIndexes>
2058 bool all_of_zip_predicate_last(
2059     std::tuple<ArgsThenPredicate...> argsThenPredicate,
2060     std::index_sequence<InputIndexes...>) {
2061   auto constexpr OutputIndex =
2062       std::tuple_size<decltype(argsThenPredicate)>::value - 1;
2063   return all_of_zip_predicate_first(std::get<OutputIndex>(argsThenPredicate),
2064                              std::get<InputIndexes>(argsThenPredicate)...);
2065 }
2066 
2067 } // end namespace detail
2068 
2069 /// Compare two zipped ranges using the provided predicate (as last argument).
2070 /// Return true if all elements satisfy the predicate and false otherwise.
2071 //  Return false if the zipped iterator aren't all at end (size mismatch).
2072 template <typename... ArgsAndPredicate>
2073 bool all_of_zip(ArgsAndPredicate &&...argsAndPredicate) {
2074   return detail::all_of_zip_predicate_last(
2075       std::forward_as_tuple(argsAndPredicate...),
2076       std::make_index_sequence<sizeof...(argsAndPredicate) - 1>{});
2077 }
2078 
2079 /// Return true if the sequence [Begin, End) has exactly N items. Runs in O(N)
2080 /// time. Not meant for use with random-access iterators.
2081 /// Can optionally take a predicate to filter lazily some items.
2082 template <typename IterTy,
2083           typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
2084 bool hasNItems(
2085     IterTy &&Begin, IterTy &&End, unsigned N,
2086     Pred &&ShouldBeCounted =
2087         [](const decltype(*std::declval<IterTy>()) &) { return true; },
2088     std::enable_if_t<
2089         !std::is_base_of<std::random_access_iterator_tag,
2090                          typename std::iterator_traits<std::remove_reference_t<
2091                              decltype(Begin)>>::iterator_category>::value,
2092         void> * = nullptr) {
2093   for (; N; ++Begin) {
2094     if (Begin == End)
2095       return false; // Too few.
2096     N -= ShouldBeCounted(*Begin);
2097   }
2098   for (; Begin != End; ++Begin)
2099     if (ShouldBeCounted(*Begin))
2100       return false; // Too many.
2101   return true;
2102 }
2103 
2104 /// Return true if the sequence [Begin, End) has N or more items. Runs in O(N)
2105 /// time. Not meant for use with random-access iterators.
2106 /// Can optionally take a predicate to lazily filter some items.
2107 template <typename IterTy,
2108           typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
2109 bool hasNItemsOrMore(
2110     IterTy &&Begin, IterTy &&End, unsigned N,
2111     Pred &&ShouldBeCounted =
2112         [](const decltype(*std::declval<IterTy>()) &) { return true; },
2113     std::enable_if_t<
2114         !std::is_base_of<std::random_access_iterator_tag,
2115                          typename std::iterator_traits<std::remove_reference_t<
2116                              decltype(Begin)>>::iterator_category>::value,
2117         void> * = nullptr) {
2118   for (; N; ++Begin) {
2119     if (Begin == End)
2120       return false; // Too few.
2121     N -= ShouldBeCounted(*Begin);
2122   }
2123   return true;
2124 }
2125 
2126 /// Returns true if the sequence [Begin, End) has N or less items. Can
2127 /// optionally take a predicate to lazily filter some items.
2128 template <typename IterTy,
2129           typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
2130 bool hasNItemsOrLess(
2131     IterTy &&Begin, IterTy &&End, unsigned N,
2132     Pred &&ShouldBeCounted = [](const decltype(*std::declval<IterTy>()) &) {
2133       return true;
2134     }) {
2135   assert(N != std::numeric_limits<unsigned>::max());
2136   return !hasNItemsOrMore(Begin, End, N + 1, ShouldBeCounted);
2137 }
2138 
2139 /// Returns true if the given container has exactly N items
2140 template <typename ContainerTy> bool hasNItems(ContainerTy &&C, unsigned N) {
2141   return hasNItems(std::begin(C), std::end(C), N);
2142 }
2143 
2144 /// Returns true if the given container has N or more items
2145 template <typename ContainerTy>
2146 bool hasNItemsOrMore(ContainerTy &&C, unsigned N) {
2147   return hasNItemsOrMore(std::begin(C), std::end(C), N);
2148 }
2149 
2150 /// Returns true if the given container has N or less items
2151 template <typename ContainerTy>
2152 bool hasNItemsOrLess(ContainerTy &&C, unsigned N) {
2153   return hasNItemsOrLess(std::begin(C), std::end(C), N);
2154 }
2155 
2156 /// Returns a raw pointer that represents the same address as the argument.
2157 ///
2158 /// This implementation can be removed once we move to C++20 where it's defined
2159 /// as std::to_address().
2160 ///
2161 /// The std::pointer_traits<>::to_address(p) variations of these overloads has
2162 /// not been implemented.
2163 template <class Ptr> auto to_address(const Ptr &P) { return P.operator->(); }
2164 template <class T> constexpr T *to_address(T *P) { return P; }
2165 
2166 } // end namespace llvm
2167 
2168 #endif // LLVM_ADT_STLEXTRAS_H
2169