LLVM 22.0.0git
STLExtras.h
Go to the documentation of this file.
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/ADL.h"
21#include "llvm/ADT/Hashing.h"
24#include "llvm/ADT/iterator.h"
26#include "llvm/Config/abi-breaking.h"
28#include <algorithm>
29#include <cassert>
30#include <cstddef>
31#include <cstdint>
32#include <cstdlib>
33#include <functional>
34#include <initializer_list>
35#include <iterator>
36#include <limits>
37#include <memory>
38#include <optional>
39#include <tuple>
40#include <type_traits>
41#include <utility>
42
43#ifdef EXPENSIVE_CHECKS
44#include <random> // for std::mt19937
45#endif
46
47namespace llvm {
48
49//===----------------------------------------------------------------------===//
50// Extra additions to <type_traits>
51//===----------------------------------------------------------------------===//
52
53template <typename T> struct make_const_ptr {
54 using type = std::add_pointer_t<std::add_const_t<T>>;
55};
56
57template <typename T> struct make_const_ref {
58 using type = std::add_lvalue_reference_t<std::add_const_t<T>>;
59};
60
61/// This class provides various trait information about a callable object.
62/// * To access the number of arguments: Traits::num_args
63/// * To access the type of an argument: Traits::arg_t<Index>
64/// * To access the type of the result: Traits::result_t
65template <typename T, bool isClass = std::is_class<T>::value>
66struct function_traits : public function_traits<decltype(&T::operator())> {};
67
68/// Overload for class function types.
69template <typename ClassType, typename ReturnType, typename... Args>
70struct function_traits<ReturnType (ClassType::*)(Args...) const, false> {
71 /// The number of arguments to this function.
72 enum { num_args = sizeof...(Args) };
73
74 /// The result type of this function.
75 using result_t = ReturnType;
76
77 /// The type of an argument to this function.
78 template <size_t Index>
79 using arg_t = std::tuple_element_t<Index, std::tuple<Args...>>;
80};
81/// Overload for class function types.
82template <typename ClassType, typename ReturnType, typename... Args>
83struct function_traits<ReturnType (ClassType::*)(Args...), false>
84 : public function_traits<ReturnType (ClassType::*)(Args...) const> {};
85/// Overload for non-class function types.
86template <typename ReturnType, typename... Args>
87struct function_traits<ReturnType (*)(Args...), false> {
88 /// The number of arguments to this function.
89 enum { num_args = sizeof...(Args) };
90
91 /// The result type of this function.
92 using result_t = ReturnType;
93
94 /// The type of an argument to this function.
95 template <size_t i>
96 using arg_t = std::tuple_element_t<i, std::tuple<Args...>>;
97};
98template <typename ReturnType, typename... Args>
99struct function_traits<ReturnType (*const)(Args...), false>
100 : public function_traits<ReturnType (*)(Args...)> {};
101/// Overload for non-class function type references.
102template <typename ReturnType, typename... Args>
103struct function_traits<ReturnType (&)(Args...), false>
104 : public function_traits<ReturnType (*)(Args...)> {};
105
106/// traits class for checking whether type T is one of any of the given
107/// types in the variadic list.
108template <typename T, typename... Ts>
109using is_one_of = std::disjunction<std::is_same<T, Ts>...>;
110
111/// traits class for checking whether type T is a base class for all
112/// the given types in the variadic list.
113template <typename T, typename... Ts>
114using are_base_of = std::conjunction<std::is_base_of<T, Ts>...>;
115
116/// Determine if all types in Ts are distinct.
117///
118/// Useful to statically assert when Ts is intended to describe a non-multi set
119/// of types.
120///
121/// Expensive (currently quadratic in sizeof(Ts...)), and so should only be
122/// asserted once per instantiation of a type which requires it.
123template <typename... Ts> struct TypesAreDistinct;
124template <> struct TypesAreDistinct<> : std::true_type {};
125template <typename T, typename... Us>
126struct TypesAreDistinct<T, Us...>
127 : std::conjunction<std::negation<is_one_of<T, Us...>>,
128 TypesAreDistinct<Us...>> {};
129
130/// Find the first index where a type appears in a list of types.
131///
132/// FirstIndexOfType<T, Us...>::value is the first index of T in Us.
133///
134/// Typically only meaningful when it is otherwise statically known that the
135/// type pack has no duplicate types. This should be guaranteed explicitly with
136/// static_assert(TypesAreDistinct<Us...>::value).
137///
138/// It is a compile-time error to instantiate when T is not present in Us, i.e.
139/// if is_one_of<T, Us...>::value is false.
140template <typename T, typename... Us> struct FirstIndexOfType;
141template <typename T, typename U, typename... Us>
142struct FirstIndexOfType<T, U, Us...>
143 : std::integral_constant<size_t, 1 + FirstIndexOfType<T, Us...>::value> {};
144template <typename T, typename... Us>
145struct FirstIndexOfType<T, T, Us...> : std::integral_constant<size_t, 0> {};
146
147/// Find the type at a given index in a list of types.
148///
149/// TypeAtIndex<I, Ts...> is the type at index I in Ts.
150template <size_t I, typename... Ts>
151using TypeAtIndex = std::tuple_element_t<I, std::tuple<Ts...>>;
152
153/// Helper which adds two underlying types of enumeration type.
154/// Implicit conversion to a common type is accepted.
155template <typename EnumTy1, typename EnumTy2,
156 typename UT1 = std::enable_if_t<std::is_enum<EnumTy1>::value,
157 std::underlying_type_t<EnumTy1>>,
158 typename UT2 = std::enable_if_t<std::is_enum<EnumTy2>::value,
159 std::underlying_type_t<EnumTy2>>>
160constexpr auto addEnumValues(EnumTy1 LHS, EnumTy2 RHS) {
161 return static_cast<UT1>(LHS) + static_cast<UT2>(RHS);
162}
163
164//===----------------------------------------------------------------------===//
165// Extra additions to <iterator>
166//===----------------------------------------------------------------------===//
167
169
170/// Templated storage wrapper for a callable.
171///
172/// This class is consistently default constructible, copy / move
173/// constructible / assignable.
174///
175/// Supported callable types:
176/// - Function pointer
177/// - Function reference
178/// - Lambda
179/// - Function object
180template <typename T,
181 bool = std::is_function_v<std::remove_pointer_t<remove_cvref_t<T>>>>
182class Callable {
183 using value_type = std::remove_reference_t<T>;
184 using reference = value_type &;
185 using const_reference = value_type const &;
186
187 std::optional<value_type> Obj;
188
189 static_assert(!std::is_pointer_v<value_type>,
190 "Pointers to non-functions are not callable.");
191
192public:
193 Callable() = default;
194 Callable(T const &O) : Obj(std::in_place, O) {}
195
196 Callable(Callable const &Other) = default;
197 Callable(Callable &&Other) = default;
198
200 Obj = std::nullopt;
201 if (Other.Obj)
202 Obj.emplace(*Other.Obj);
203 return *this;
204 }
205
207 Obj = std::nullopt;
208 if (Other.Obj)
209 Obj.emplace(std::move(*Other.Obj));
210 return *this;
211 }
212
213 template <typename... Pn,
214 std::enable_if_t<std::is_invocable_v<T, Pn...>, int> = 0>
215 decltype(auto) operator()(Pn &&...Params) {
216 return (*Obj)(std::forward<Pn>(Params)...);
217 }
218
219 template <typename... Pn,
220 std::enable_if_t<std::is_invocable_v<T const, Pn...>, int> = 0>
221 decltype(auto) operator()(Pn &&...Params) const {
222 return (*Obj)(std::forward<Pn>(Params)...);
223 }
224
225 bool valid() const { return Obj != std::nullopt; }
226 bool reset() { return Obj = std::nullopt; }
227
228 operator reference() { return *Obj; }
229 operator const_reference() const { return *Obj; }
230};
231
232// Function specialization. No need to waste extra space wrapping with a
233// std::optional.
234template <typename T> class Callable<T, true> {
235 static constexpr bool IsPtr = std::is_pointer_v<remove_cvref_t<T>>;
236
237 using StorageT = std::conditional_t<IsPtr, T, std::remove_reference_t<T> *>;
238 using CastT = std::conditional_t<IsPtr, T, T &>;
239
240private:
241 StorageT Func = nullptr;
242
243private:
244 template <typename In> static constexpr auto convertIn(In &&I) {
245 if constexpr (IsPtr) {
246 // Pointer... just echo it back.
247 return I;
248 } else {
249 // Must be a function reference. Return its address.
250 return &I;
251 }
252 }
253
254public:
255 Callable() = default;
256
257 // Construct from a function pointer or reference.
258 //
259 // Disable this constructor for references to 'Callable' so we don't violate
260 // the rule of 0.
261 template < // clang-format off
262 typename FnPtrOrRef,
263 std::enable_if_t<
264 !std::is_same_v<remove_cvref_t<FnPtrOrRef>, Callable>, int
265 > = 0
266 > // clang-format on
267 Callable(FnPtrOrRef &&F) : Func(convertIn(F)) {}
268
269 template <typename... Pn,
270 std::enable_if_t<std::is_invocable_v<T, Pn...>, int> = 0>
271 decltype(auto) operator()(Pn &&...Params) const {
272 return Func(std::forward<Pn>(Params)...);
273 }
274
275 bool valid() const { return Func != nullptr; }
276 void reset() { Func = nullptr; }
277
278 operator T const &() const {
279 if constexpr (IsPtr) {
280 // T is a pointer... just echo it back.
281 return Func;
282 } else {
283 static_assert(std::is_reference_v<T>,
284 "Expected a reference to a function.");
285 // T is a function reference... dereference the stored pointer.
286 return *Func;
287 }
288 }
289};
290
291} // namespace callable_detail
292
293/// Returns true if the given container only contains a single element.
294template <typename ContainerTy> bool hasSingleElement(ContainerTy &&C) {
295 auto B = adl_begin(C);
296 auto E = adl_end(C);
297 return B != E && std::next(B) == E;
298}
299
300/// Asserts that the given container has a single element and returns that
301/// element.
302template <typename ContainerTy>
303decltype(auto) getSingleElement(ContainerTy &&C) {
304 assert(hasSingleElement(C) && "expected container with single element");
305 return *adl_begin(C);
306}
307
308/// Return a range covering \p RangeOrContainer with the first N elements
309/// excluded.
310template <typename T> auto drop_begin(T &&RangeOrContainer, size_t N = 1) {
311 return make_range(std::next(adl_begin(RangeOrContainer), N),
312 adl_end(RangeOrContainer));
313}
314
315/// Return a range covering \p RangeOrContainer with the last N elements
316/// excluded.
317template <typename T> auto drop_end(T &&RangeOrContainer, size_t N = 1) {
318 return make_range(adl_begin(RangeOrContainer),
319 std::prev(adl_end(RangeOrContainer), N));
320}
321
322// mapped_iterator - This is a simple iterator adapter that causes a function to
323// be applied whenever operator* is invoked on the iterator.
324
325template <typename ItTy, typename FuncTy,
326 typename ReferenceTy =
327 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
329 : public iterator_adaptor_base<
330 mapped_iterator<ItTy, FuncTy>, ItTy,
331 typename std::iterator_traits<ItTy>::iterator_category,
332 std::remove_reference_t<ReferenceTy>,
333 typename std::iterator_traits<ItTy>::difference_type,
334 std::remove_reference_t<ReferenceTy> *, ReferenceTy> {
335public:
336 mapped_iterator() = default;
339
340 ItTy getCurrent() { return this->I; }
341
342 const FuncTy &getFunction() const { return F; }
343
344 ReferenceTy operator*() const { return F(*this->I); }
345
346private:
348};
349
350// map_iterator - Provide a convenient way to create mapped_iterators, just like
351// make_pair is useful for creating pairs...
352template <class ItTy, class FuncTy>
354 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
355}
356
357template <class ContainerTy, class FuncTy>
358auto map_range(ContainerTy &&C, FuncTy F) {
360}
361
362/// A base type of mapped iterator, that is useful for building derived
363/// iterators that do not need/want to store the map function (as in
364/// mapped_iterator). These iterators must simply provide a `mapElement` method
365/// that defines how to map a value of the iterator to the provided reference
366/// type.
367template <typename DerivedT, typename ItTy, typename ReferenceTy>
369 : public iterator_adaptor_base<
370 DerivedT, ItTy,
371 typename std::iterator_traits<ItTy>::iterator_category,
372 std::remove_reference_t<ReferenceTy>,
373 typename std::iterator_traits<ItTy>::difference_type,
374 std::remove_reference_t<ReferenceTy> *, ReferenceTy> {
375public:
377
380
381 ItTy getCurrent() { return this->I; }
382
383 ReferenceTy operator*() const {
384 return static_cast<const DerivedT &>(*this).mapElement(*this->I);
385 }
386};
387
388namespace detail {
389template <typename Range>
391 decltype(adl_rbegin(std::declval<Range &>()));
392
393template <typename Range>
394static constexpr bool HasFreeFunctionRBegin =
396} // namespace detail
397
398// Returns an iterator_range over the given container which iterates in reverse.
399// Does not mutate the container.
400template <typename ContainerTy> [[nodiscard]] auto reverse(ContainerTy &&C) {
402 return make_range(adl_rbegin(C), adl_rend(C));
403 else
404 return make_range(std::make_reverse_iterator(adl_end(C)),
405 std::make_reverse_iterator(adl_begin(C)));
406}
407
408/// An iterator adaptor that filters the elements of given inner iterators.
409///
410/// The predicate parameter should be a callable object that accepts the wrapped
411/// iterator's reference type and returns a bool. When incrementing or
412/// decrementing the iterator, it will call the predicate on each element and
413/// skip any where it returns false.
414///
415/// \code
416/// int A[] = { 1, 2, 3, 4 };
417/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
418/// // R contains { 1, 3 }.
419/// \endcode
420///
421/// Note: filter_iterator_base implements support for forward iteration.
422/// filter_iterator_impl exists to provide support for bidirectional iteration,
423/// conditional on whether the wrapped iterator supports it.
424template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
426 : public iterator_adaptor_base<
427 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
428 WrappedIteratorT,
429 std::common_type_t<IterTag,
430 typename std::iterator_traits<
431 WrappedIteratorT>::iterator_category>> {
432 using BaseT = typename filter_iterator_base::iterator_adaptor_base;
433
434protected:
437
439 while (this->I != End && !Pred(*this->I))
440 BaseT::operator++();
441 }
442
444
445 // Construct the iterator. The begin iterator needs to know where the end
446 // is, so that it can properly stop when it gets there. The end iterator only
447 // needs the predicate to support bidirectional iteration.
453
454public:
455 using BaseT::operator++;
456
458 BaseT::operator++();
460 return *this;
461 }
462
463 decltype(auto) operator*() const {
464 assert(BaseT::wrapped() != End && "Cannot dereference end iterator!");
465 return BaseT::operator*();
466 }
467
468 decltype(auto) operator->() const {
469 assert(BaseT::wrapped() != End && "Cannot dereference end iterator!");
470 return BaseT::operator->();
471 }
472};
473
474/// Specialization of filter_iterator_base for forward iteration only.
475template <typename WrappedIteratorT, typename PredicateT,
476 typename IterTag = std::forward_iterator_tag>
478 : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
479public:
481
485};
486
487/// Specialization of filter_iterator_base for bidirectional iteration.
488template <typename WrappedIteratorT, typename PredicateT>
490 std::bidirectional_iterator_tag>
491 : public filter_iterator_base<WrappedIteratorT, PredicateT,
492 std::bidirectional_iterator_tag> {
493 using BaseT = typename filter_iterator_impl::filter_iterator_base;
494
495 void findPrevValid() {
496 while (!this->Pred(*this->I))
497 BaseT::operator--();
498 }
499
500public:
501 using BaseT::operator--;
502
504
508
510 BaseT::operator--();
511 findPrevValid();
512 return *this;
513 }
514};
515
516namespace detail {
517
518/// A type alias which is std::bidirectional_iterator_tag if the category of
519/// \p IterT derives from it, and std::forward_iterator_tag otherwise.
520template <typename IterT>
521using fwd_or_bidi_tag = std::conditional_t<
522 std::is_base_of_v<std::bidirectional_iterator_tag,
523 typename std::iterator_traits<IterT>::iterator_category>,
524 std::bidirectional_iterator_tag, std::forward_iterator_tag>;
525
526} // namespace detail
527
528/// Defines filter_iterator to a suitable specialization of
529/// filter_iterator_impl, based on the underlying iterator's category.
530template <typename WrappedIteratorT, typename PredicateT>
534
535/// Convenience function that takes a range of elements and a predicate,
536/// and return a new filter_iterator range.
537///
538/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
539/// lifetime of that temporary is not kept by the returned range object, and the
540/// temporary is going to be dropped on the floor after the make_iterator_range
541/// full expression that contains this function call.
542template <typename RangeT, typename PredicateT>
545 using FilterIteratorT =
547 auto B = adl_begin(Range);
548 auto E = adl_end(Range);
549 return make_range(FilterIteratorT(B, E, Pred), FilterIteratorT(E, E, Pred));
550}
551
552/// A pseudo-iterator adaptor that is designed to implement "early increment"
553/// style loops.
554///
555/// This is *not a normal iterator* and should almost never be used directly. It
556/// is intended primarily to be used with range based for loops and some range
557/// algorithms.
558///
559/// The iterator isn't quite an `OutputIterator` or an `InputIterator` but
560/// somewhere between them. The constraints of these iterators are:
561///
562/// - On construction or after being incremented, it is comparable and
563/// dereferencable. It is *not* incrementable.
564/// - After being dereferenced, it is neither comparable nor dereferencable, it
565/// is only incrementable.
566///
567/// This means you can only dereference the iterator once, and you can only
568/// increment it once between dereferences.
569template <typename WrappedIteratorT>
571 : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
572 WrappedIteratorT, std::input_iterator_tag> {
574
575 using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer;
576
577protected:
578#if LLVM_ENABLE_ABI_BREAKING_CHECKS
579 bool IsEarlyIncremented = false;
580#endif
581
582public:
584
585 using BaseT::operator*;
586 decltype(*std::declval<WrappedIteratorT>()) operator*() {
587#if LLVM_ENABLE_ABI_BREAKING_CHECKS
588 assert(!IsEarlyIncremented && "Cannot dereference twice!");
589 IsEarlyIncremented = true;
590#endif
591 return *(this->I)++;
592 }
593
594 using BaseT::operator++;
596#if LLVM_ENABLE_ABI_BREAKING_CHECKS
597 assert(IsEarlyIncremented && "Cannot increment before dereferencing!");
598 IsEarlyIncremented = false;
599#endif
600 return *this;
601 }
602
605#if LLVM_ENABLE_ABI_BREAKING_CHECKS
606 assert(!LHS.IsEarlyIncremented && "Cannot compare after dereferencing!");
607#endif
608 return (const BaseT &)LHS == (const BaseT &)RHS;
609 }
610};
611
612/// Make a range that does early increment to allow mutation of the underlying
613/// range without disrupting iteration.
614///
615/// The underlying iterator will be incremented immediately after it is
616/// dereferenced, allowing deletion of the current node or insertion of nodes to
617/// not disrupt iteration provided they do not invalidate the *next* iterator --
618/// the current iterator can be invalidated.
619///
620/// This requires a very exact pattern of use that is only really suitable to
621/// range based for loops and other range algorithms that explicitly guarantee
622/// to dereference exactly once each element, and to increment exactly once each
623/// element.
624template <typename RangeT>
627 using EarlyIncIteratorT =
629 return make_range(EarlyIncIteratorT(adl_begin(Range)),
630 EarlyIncIteratorT(adl_end(Range)));
631}
632
633// Forward declarations required by zip_shortest/zip_equal/zip_first/zip_longest
634template <typename R, typename UnaryPredicate>
635bool all_of(R &&range, UnaryPredicate P);
636
637template <typename R, typename UnaryPredicate>
638bool any_of(R &&range, UnaryPredicate P);
639
640template <typename T> bool all_equal(std::initializer_list<T> Values);
641
642template <typename R> constexpr size_t range_size(R &&Range);
643
644namespace detail {
645
646using std::declval;
647
648// We have to alias this since inlining the actual type at the usage site
649// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
650template<typename... Iters> struct ZipTupleType {
651 using type = std::tuple<decltype(*declval<Iters>())...>;
652};
653
654template <typename ZipType, typename ReferenceTupleType, typename... Iters>
656 ZipType,
657 std::common_type_t<
658 std::bidirectional_iterator_tag,
659 typename std::iterator_traits<Iters>::iterator_category...>,
660 // ^ TODO: Implement random access methods.
661 ReferenceTupleType,
662 typename std::iterator_traits<
663 std::tuple_element_t<0, std::tuple<Iters...>>>::difference_type,
664 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
665 // inner iterators have the same difference_type. It would fail if, for
666 // instance, the second field's difference_type were non-numeric while the
667 // first is.
668 ReferenceTupleType *, ReferenceTupleType>;
669
670template <typename ZipType, typename ReferenceTupleType, typename... Iters>
671struct zip_common : public zip_traits<ZipType, ReferenceTupleType, Iters...> {
672 using Base = zip_traits<ZipType, ReferenceTupleType, Iters...>;
673 using IndexSequence = std::index_sequence_for<Iters...>;
674 using value_type = typename Base::value_type;
675
676 std::tuple<Iters...> iterators;
677
678protected:
679 template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
680 return value_type(*std::get<Ns>(iterators)...);
681 }
682
683 template <size_t... Ns> void tup_inc(std::index_sequence<Ns...>) {
684 (++std::get<Ns>(iterators), ...);
685 }
686
687 template <size_t... Ns> void tup_dec(std::index_sequence<Ns...>) {
688 (--std::get<Ns>(iterators), ...);
689 }
690
691 template <size_t... Ns>
692 bool test_all_equals(const zip_common &other,
693 std::index_sequence<Ns...>) const {
694 return ((std::get<Ns>(this->iterators) == std::get<Ns>(other.iterators)) &&
695 ...);
696 }
697
698public:
699 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
700
702
703 ZipType &operator++() {
705 return static_cast<ZipType &>(*this);
706 }
707
708 ZipType &operator--() {
709 static_assert(Base::IsBidirectional,
710 "All inner iterators must be at least bidirectional.");
712 return static_cast<ZipType &>(*this);
713 }
714
715 /// Return true if all the iterator are matching `other`'s iterators.
716 bool all_equals(zip_common &other) {
717 return test_all_equals(other, IndexSequence{});
718 }
719};
720
721template <typename... Iters>
722struct zip_first : zip_common<zip_first<Iters...>,
723 typename ZipTupleType<Iters...>::type, Iters...> {
724 using zip_common<zip_first, typename ZipTupleType<Iters...>::type,
725 Iters...>::zip_common;
726
727 bool operator==(const zip_first &other) const {
728 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
729 }
730};
731
732template <typename... Iters>
734 : zip_common<zip_shortest<Iters...>, typename ZipTupleType<Iters...>::type,
735 Iters...> {
736 using zip_common<zip_shortest, typename ZipTupleType<Iters...>::type,
737 Iters...>::zip_common;
738
739 bool operator==(const zip_shortest &other) const {
740 return any_iterator_equals(other, std::index_sequence_for<Iters...>{});
741 }
742
743private:
744 template <size_t... Ns>
745 bool any_iterator_equals(const zip_shortest &other,
746 std::index_sequence<Ns...>) const {
747 return ((std::get<Ns>(this->iterators) == std::get<Ns>(other.iterators)) ||
748 ...);
749 }
750};
751
752/// Helper to obtain the iterator types for the tuple storage within `zippy`.
753template <template <typename...> class ItType, typename TupleStorageType,
754 typename IndexSequence>
756
757/// Partial specialization for non-const tuple storage.
758template <template <typename...> class ItType, typename... Args,
759 std::size_t... Ns>
760struct ZippyIteratorTuple<ItType, std::tuple<Args...>,
761 std::index_sequence<Ns...>> {
762 using type = ItType<decltype(adl_begin(
763 std::get<Ns>(declval<std::tuple<Args...> &>())))...>;
764};
765
766/// Partial specialization for const tuple storage.
767template <template <typename...> class ItType, typename... Args,
768 std::size_t... Ns>
769struct ZippyIteratorTuple<ItType, const std::tuple<Args...>,
770 std::index_sequence<Ns...>> {
771 using type = ItType<decltype(adl_begin(
772 std::get<Ns>(declval<const std::tuple<Args...> &>())))...>;
773};
774
775template <template <typename...> class ItType, typename... Args> class zippy {
776private:
777 std::tuple<Args...> storage;
778 using IndexSequence = std::index_sequence_for<Args...>;
779
780public:
781 using iterator = typename ZippyIteratorTuple<ItType, decltype(storage),
782 IndexSequence>::type;
784 typename ZippyIteratorTuple<ItType, const decltype(storage),
785 IndexSequence>::type;
786 using iterator_category = typename iterator::iterator_category;
787 using value_type = typename iterator::value_type;
788 using difference_type = typename iterator::difference_type;
789 using pointer = typename iterator::pointer;
790 using reference = typename iterator::reference;
791 using const_reference = typename const_iterator::reference;
792
793 zippy(Args &&...args) : storage(std::forward<Args>(args)...) {}
794
795 const_iterator begin() const { return begin_impl(IndexSequence{}); }
796 iterator begin() { return begin_impl(IndexSequence{}); }
797 const_iterator end() const { return end_impl(IndexSequence{}); }
798 iterator end() { return end_impl(IndexSequence{}); }
799
800private:
801 template <size_t... Ns>
802 const_iterator begin_impl(std::index_sequence<Ns...>) const {
803 return const_iterator(adl_begin(std::get<Ns>(storage))...);
804 }
805 template <size_t... Ns> iterator begin_impl(std::index_sequence<Ns...>) {
806 return iterator(adl_begin(std::get<Ns>(storage))...);
807 }
808
809 template <size_t... Ns>
810 const_iterator end_impl(std::index_sequence<Ns...>) const {
811 return const_iterator(adl_end(std::get<Ns>(storage))...);
812 }
813 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) {
814 return iterator(adl_end(std::get<Ns>(storage))...);
815 }
816};
817
818} // end namespace detail
819
820/// zip iterator for two or more iteratable types. Iteration continues until the
821/// end of the *shortest* iteratee is reached.
822template <typename T, typename U, typename... Args>
823detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
824 Args &&...args) {
825 return detail::zippy<detail::zip_shortest, T, U, Args...>(
826 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
827}
828
829/// zip iterator that assumes that all iteratees have the same length.
830/// In builds with assertions on, this assumption is checked before the
831/// iteration starts.
832template <typename T, typename U, typename... Args>
833detail::zippy<detail::zip_first, T, U, Args...> zip_equal(T &&t, U &&u,
834 Args &&...args) {
836 "Iteratees do not have equal length");
837 return detail::zippy<detail::zip_first, T, U, Args...>(
838 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
839}
840
841/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
842/// be the shortest. Iteration continues until the end of the first iteratee is
843/// reached. In builds with assertions on, we check that the assumption about
844/// the first iteratee being the shortest holds.
845template <typename T, typename U, typename... Args>
846detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
847 Args &&...args) {
848 assert(range_size(t) <= std::min({range_size(u), range_size(args)...}) &&
849 "First iteratee is not the shortest");
850
851 return detail::zippy<detail::zip_first, T, U, Args...>(
852 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
853}
854
855namespace detail {
856template <typename Iter>
857Iter next_or_end(const Iter &I, const Iter &End) {
858 if (I == End)
859 return End;
860 return std::next(I);
861}
862
863template <typename Iter>
864auto deref_or_none(const Iter &I, const Iter &End) -> std::optional<
865 std::remove_const_t<std::remove_reference_t<decltype(*I)>>> {
866 if (I == End)
867 return std::nullopt;
868 return *I;
869}
870
871template <typename Iter> struct ZipLongestItemType {
872 using type = std::optional<std::remove_const_t<
873 std::remove_reference_t<decltype(*std::declval<Iter>())>>>;
874};
875
876template <typename... Iters> struct ZipLongestTupleType {
877 using type = std::tuple<typename ZipLongestItemType<Iters>::type...>;
878};
879
880template <typename... Iters>
882 : public iterator_facade_base<
883 zip_longest_iterator<Iters...>,
884 std::common_type_t<
885 std::forward_iterator_tag,
886 typename std::iterator_traits<Iters>::iterator_category...>,
887 typename ZipLongestTupleType<Iters...>::type,
888 typename std::iterator_traits<
889 std::tuple_element_t<0, std::tuple<Iters...>>>::difference_type,
890 typename ZipLongestTupleType<Iters...>::type *,
891 typename ZipLongestTupleType<Iters...>::type> {
892public:
893 using value_type = typename ZipLongestTupleType<Iters...>::type;
894
895private:
896 std::tuple<Iters...> iterators;
897 std::tuple<Iters...> end_iterators;
898
899 template <size_t... Ns>
900 bool test(const zip_longest_iterator<Iters...> &other,
901 std::index_sequence<Ns...>) const {
902 return ((std::get<Ns>(this->iterators) != std::get<Ns>(other.iterators)) ||
903 ...);
904 }
905
906 template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
907 return value_type(
908 deref_or_none(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
909 }
910
911 template <size_t... Ns>
912 decltype(iterators) tup_inc(std::index_sequence<Ns...>) const {
913 return std::tuple<Iters...>(
914 next_or_end(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
915 }
916
917public:
918 zip_longest_iterator(std::pair<Iters &&, Iters &&>... ts)
919 : iterators(std::forward<Iters>(ts.first)...),
920 end_iterators(std::forward<Iters>(ts.second)...) {}
921
923 return deref(std::index_sequence_for<Iters...>{});
924 }
925
927 iterators = tup_inc(std::index_sequence_for<Iters...>{});
928 return *this;
929 }
930
932 return !test(other, std::index_sequence_for<Iters...>{});
933 }
934};
935
936template <typename... Args> class zip_longest_range {
937public:
938 using iterator =
943 using pointer = typename iterator::pointer;
945
946private:
947 std::tuple<Args...> ts;
948
949 template <size_t... Ns>
950 iterator begin_impl(std::index_sequence<Ns...>) const {
951 return iterator(std::make_pair(adl_begin(std::get<Ns>(ts)),
952 adl_end(std::get<Ns>(ts)))...);
953 }
954
955 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
956 return iterator(std::make_pair(adl_end(std::get<Ns>(ts)),
957 adl_end(std::get<Ns>(ts)))...);
958 }
959
960public:
961 zip_longest_range(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
962
963 iterator begin() const {
964 return begin_impl(std::index_sequence_for<Args...>{});
965 }
966 iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); }
967};
968} // namespace detail
969
970/// Iterate over two or more iterators at the same time. Iteration continues
971/// until all iterators reach the end. The std::optional only contains a value
972/// if the iterator has not reached the end.
973template <typename T, typename U, typename... Args>
974detail::zip_longest_range<T, U, Args...> zip_longest(T &&t, U &&u,
975 Args &&... args) {
976 return detail::zip_longest_range<T, U, Args...>(
977 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
978}
979
980/// Iterator wrapper that concatenates sequences together.
981///
982/// This can concatenate different iterators, even with different types, into
983/// a single iterator provided the value types of all the concatenated
984/// iterators expose `reference` and `pointer` types that can be converted to
985/// `ValueT &` and `ValueT *` respectively. It doesn't support more
986/// interesting/customized pointer or reference types.
987///
988/// Currently this only supports forward or higher iterator categories as
989/// inputs and always exposes a forward iterator interface.
990template <typename ValueT, typename... IterTs>
992 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
993 std::forward_iterator_tag, ValueT> {
994 using BaseT = typename concat_iterator::iterator_facade_base;
995
996 static constexpr bool ReturnsByValue =
997 !(std::is_reference_v<decltype(*std::declval<IterTs>())> && ...);
998
999 using reference_type =
1000 typename std::conditional_t<ReturnsByValue, ValueT, ValueT &>;
1001
1002 using handle_type =
1003 typename std::conditional_t<ReturnsByValue, std::optional<ValueT>,
1004 ValueT *>;
1005
1006 /// We store both the current and end iterators for each concatenated
1007 /// sequence in a tuple of pairs.
1008 ///
1009 /// Note that something like iterator_range seems nice at first here, but the
1010 /// range properties are of little benefit and end up getting in the way
1011 /// because we need to do mutation on the current iterators.
1012 std::tuple<IterTs...> Begins;
1013 std::tuple<IterTs...> Ends;
1014
1015 /// Attempts to increment a specific iterator.
1016 ///
1017 /// Returns true if it was able to increment the iterator. Returns false if
1018 /// the iterator is already at the end iterator.
1019 template <size_t Index> bool incrementHelper() {
1020 auto &Begin = std::get<Index>(Begins);
1021 auto &End = std::get<Index>(Ends);
1022 if (Begin == End)
1023 return false;
1024
1025 ++Begin;
1026 return true;
1027 }
1028
1029 /// Increments the first non-end iterator.
1030 ///
1031 /// It is an error to call this with all iterators at the end.
1032 template <size_t... Ns> void increment(std::index_sequence<Ns...>) {
1033 // Build a sequence of functions to increment each iterator if possible.
1034 bool (concat_iterator::*IncrementHelperFns[])() = {
1035 &concat_iterator::incrementHelper<Ns>...};
1036
1037 // Loop over them, and stop as soon as we succeed at incrementing one.
1038 for (auto &IncrementHelperFn : IncrementHelperFns)
1039 if ((this->*IncrementHelperFn)())
1040 return;
1041
1042 llvm_unreachable("Attempted to increment an end concat iterator!");
1043 }
1044
1045 /// Returns null if the specified iterator is at the end. Otherwise,
1046 /// dereferences the iterator and returns the address of the resulting
1047 /// reference.
1048 template <size_t Index> handle_type getHelper() const {
1049 auto &Begin = std::get<Index>(Begins);
1050 auto &End = std::get<Index>(Ends);
1051 if (Begin == End)
1052 return {};
1053
1054 if constexpr (ReturnsByValue)
1055 return *Begin;
1056 else
1057 return &*Begin;
1058 }
1059
1060 /// Finds the first non-end iterator, dereferences, and returns the resulting
1061 /// reference.
1062 ///
1063 /// It is an error to call this with all iterators at the end.
1064 template <size_t... Ns> reference_type get(std::index_sequence<Ns...>) const {
1065 // Build a sequence of functions to get from iterator if possible.
1066 handle_type (concat_iterator::*GetHelperFns[])()
1067 const = {&concat_iterator::getHelper<Ns>...};
1068
1069 // Loop over them, and return the first result we find.
1070 for (auto &GetHelperFn : GetHelperFns)
1071 if (auto P = (this->*GetHelperFn)())
1072 return *P;
1073
1074 llvm_unreachable("Attempted to get a pointer from an end concat iterator!");
1075 }
1076
1077public:
1078 /// Constructs an iterator from a sequence of ranges.
1079 ///
1080 /// We need the full range to know how to switch between each of the
1081 /// iterators.
1082 template <typename... RangeTs>
1083 explicit concat_iterator(RangeTs &&...Ranges)
1084 : Begins(adl_begin(Ranges)...), Ends(adl_end(Ranges)...) {}
1085
1086 using BaseT::operator++;
1087
1089 increment(std::index_sequence_for<IterTs...>());
1090 return *this;
1091 }
1092
1093 reference_type operator*() const {
1094 return get(std::index_sequence_for<IterTs...>());
1095 }
1096
1097 bool operator==(const concat_iterator &RHS) const {
1098 return Begins == RHS.Begins && Ends == RHS.Ends;
1099 }
1100};
1101
1102namespace detail {
1103
1104/// Helper to store a sequence of ranges being concatenated and access them.
1105///
1106/// This is designed to facilitate providing actual storage when temporaries
1107/// are passed into the constructor such that we can use it as part of range
1108/// based for loops.
1109template <typename ValueT, typename... RangeTs> class concat_range {
1110public:
1111 using iterator =
1113 decltype(adl_begin(std::declval<RangeTs &>()))...>;
1114
1115private:
1116 std::tuple<RangeTs...> Ranges;
1117
1118 template <size_t... Ns> iterator begin_impl(std::index_sequence<Ns...>) {
1119 return iterator(std::get<Ns>(Ranges)...);
1120 }
1121 template <size_t... Ns>
1122 iterator begin_impl(std::index_sequence<Ns...>) const {
1123 return iterator(std::get<Ns>(Ranges)...);
1124 }
1125 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) {
1126 return iterator(make_range(adl_end(std::get<Ns>(Ranges)),
1127 adl_end(std::get<Ns>(Ranges)))...);
1128 }
1129 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
1130 return iterator(make_range(adl_end(std::get<Ns>(Ranges)),
1131 adl_end(std::get<Ns>(Ranges)))...);
1132 }
1133
1134public:
1135 concat_range(RangeTs &&... Ranges)
1136 : Ranges(std::forward<RangeTs>(Ranges)...) {}
1137
1139 return begin_impl(std::index_sequence_for<RangeTs...>{});
1140 }
1141 iterator begin() const {
1142 return begin_impl(std::index_sequence_for<RangeTs...>{});
1143 }
1145 return end_impl(std::index_sequence_for<RangeTs...>{});
1146 }
1147 iterator end() const {
1148 return end_impl(std::index_sequence_for<RangeTs...>{});
1149 }
1150};
1151
1152} // end namespace detail
1153
1154/// Returns a concatenated range across two or more ranges. Does not modify the
1155/// ranges.
1156///
1157/// The desired value type must be explicitly specified.
1158template <typename ValueT, typename... RangeTs>
1159[[nodiscard]] detail::concat_range<ValueT, RangeTs...>
1160concat(RangeTs &&...Ranges) {
1161 static_assert(sizeof...(RangeTs) > 1,
1162 "Need more than one range to concatenate!");
1163 return detail::concat_range<ValueT, RangeTs...>(
1164 std::forward<RangeTs>(Ranges)...);
1165}
1166
1167/// A utility class used to implement an iterator that contains some base object
1168/// and an index. The iterator moves the index but keeps the base constant.
1169template <typename DerivedT, typename BaseT, typename T,
1170 typename PointerT = T *, typename ReferenceT = T &>
1172 : public llvm::iterator_facade_base<DerivedT,
1173 std::random_access_iterator_tag, T,
1174 std::ptrdiff_t, PointerT, ReferenceT> {
1175public:
1177 assert(base == rhs.base && "incompatible iterators");
1178 return index - rhs.index;
1179 }
1180 bool operator==(const indexed_accessor_iterator &rhs) const {
1181 assert(base == rhs.base && "incompatible iterators");
1182 return index == rhs.index;
1183 }
1184 bool operator<(const indexed_accessor_iterator &rhs) const {
1185 assert(base == rhs.base && "incompatible iterators");
1186 return index < rhs.index;
1187 }
1188
1189 DerivedT &operator+=(ptrdiff_t offset) {
1190 this->index += offset;
1191 return static_cast<DerivedT &>(*this);
1192 }
1193 DerivedT &operator-=(ptrdiff_t offset) {
1194 this->index -= offset;
1195 return static_cast<DerivedT &>(*this);
1196 }
1197
1198 /// Returns the current index of the iterator.
1199 ptrdiff_t getIndex() const { return index; }
1200
1201 /// Returns the current base of the iterator.
1202 const BaseT &getBase() const { return base; }
1203
1204protected:
1207 BaseT base;
1209};
1210
1211namespace detail {
1212/// The class represents the base of a range of indexed_accessor_iterators. It
1213/// provides support for many different range functionalities, e.g.
1214/// drop_front/slice/etc.. Derived range classes must implement the following
1215/// static methods:
1216/// * ReferenceT dereference_iterator(const BaseT &base, ptrdiff_t index)
1217/// - Dereference an iterator pointing to the base object at the given
1218/// index.
1219/// * BaseT offset_base(const BaseT &base, ptrdiff_t index)
1220/// - Return a new base that is offset from the provide base by 'index'
1221/// elements.
1222template <typename DerivedT, typename BaseT, typename T,
1223 typename PointerT = T *, typename ReferenceT = T &>
1225public:
1227
1228 /// An iterator element of this range.
1229 class iterator : public indexed_accessor_iterator<iterator, BaseT, T,
1230 PointerT, ReferenceT> {
1231 public:
1232 // Index into this iterator, invoking a static method on the derived type.
1233 ReferenceT operator*() const {
1234 return DerivedT::dereference_iterator(this->getBase(), this->getIndex());
1235 }
1236
1237 private:
1238 iterator(BaseT owner, ptrdiff_t curIndex)
1239 : iterator::indexed_accessor_iterator(owner, curIndex) {}
1240
1241 /// Allow access to the constructor.
1242 friend indexed_accessor_range_base<DerivedT, BaseT, T, PointerT,
1243 ReferenceT>;
1244 };
1245
1247 : base(offset_base(begin.getBase(), begin.getIndex())),
1248 count(end.getIndex() - begin.getIndex()) {}
1253
1254 iterator begin() const { return iterator(base, 0); }
1255 iterator end() const { return iterator(base, count); }
1256 ReferenceT operator[](size_t Index) const {
1257 assert(Index < size() && "invalid index for value range");
1258 return DerivedT::dereference_iterator(base, static_cast<ptrdiff_t>(Index));
1259 }
1260 ReferenceT front() const {
1261 assert(!empty() && "expected non-empty range");
1262 return (*this)[0];
1263 }
1264 ReferenceT back() const {
1265 assert(!empty() && "expected non-empty range");
1266 return (*this)[size() - 1];
1267 }
1268
1269 /// Return the size of this range.
1270 size_t size() const { return count; }
1271
1272 /// Return if the range is empty.
1273 bool empty() const { return size() == 0; }
1274
1275 /// Drop the first N elements, and keep M elements.
1276 DerivedT slice(size_t n, size_t m) const {
1277 assert(n + m <= size() && "invalid size specifiers");
1278 return DerivedT(offset_base(base, n), m);
1279 }
1280
1281 /// Drop the first n elements.
1282 DerivedT drop_front(size_t n = 1) const {
1283 assert(size() >= n && "Dropping more elements than exist");
1284 return slice(n, size() - n);
1285 }
1286 /// Drop the last n elements.
1287 DerivedT drop_back(size_t n = 1) const {
1288 assert(size() >= n && "Dropping more elements than exist");
1289 return DerivedT(base, size() - n);
1290 }
1291
1292 /// Take the first n elements.
1293 DerivedT take_front(size_t n = 1) const {
1294 return n < size() ? drop_back(size() - n)
1295 : static_cast<const DerivedT &>(*this);
1296 }
1297
1298 /// Take the last n elements.
1299 DerivedT take_back(size_t n = 1) const {
1300 return n < size() ? drop_front(size() - n)
1301 : static_cast<const DerivedT &>(*this);
1302 }
1303
1304 /// Allow conversion to any type accepting an iterator_range.
1305 template <typename RangeT, typename = std::enable_if_t<std::is_constructible<
1307 operator RangeT() const {
1308 return RangeT(iterator_range<iterator>(*this));
1309 }
1310
1311 /// Returns the base of this range.
1312 const BaseT &getBase() const { return base; }
1313
1314private:
1315 /// Offset the given base by the given amount.
1316 static BaseT offset_base(const BaseT &base, size_t n) {
1317 return n == 0 ? base : DerivedT::offset_base(base, n);
1318 }
1319
1320protected:
1325
1326 /// The base that owns the provided range of values.
1327 BaseT base;
1328 /// The size from the owning range.
1330};
1331/// Compare this range with another.
1332/// FIXME: Make me a member function instead of friend when it works in C++20.
1333template <typename OtherT, typename DerivedT, typename BaseT, typename T,
1334 typename PointerT, typename ReferenceT>
1335bool operator==(const indexed_accessor_range_base<DerivedT, BaseT, T, PointerT,
1336 ReferenceT> &lhs,
1337 const OtherT &rhs) {
1338 return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
1339}
1340
1341template <typename OtherT, typename DerivedT, typename BaseT, typename T,
1342 typename PointerT, typename ReferenceT>
1343bool operator!=(const indexed_accessor_range_base<DerivedT, BaseT, T, PointerT,
1344 ReferenceT> &lhs,
1345 const OtherT &rhs) {
1346 return !(lhs == rhs);
1347}
1348} // end namespace detail
1349
1350/// This class provides an implementation of a range of
1351/// indexed_accessor_iterators where the base is not indexable. Ranges with
1352/// bases that are offsetable should derive from indexed_accessor_range_base
1353/// instead. Derived range classes are expected to implement the following
1354/// static method:
1355/// * ReferenceT dereference(const BaseT &base, ptrdiff_t index)
1356/// - Dereference an iterator pointing to a parent base at the given index.
1357template <typename DerivedT, typename BaseT, typename T,
1358 typename PointerT = T *, typename ReferenceT = T &>
1361 DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT> {
1362public:
1365 DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT>(
1366 std::make_pair(base, startIndex), count) {}
1368 DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT,
1370
1371 /// Returns the current base of the range.
1372 const BaseT &getBase() const { return this->base.first; }
1373
1374 /// Returns the current start index of the range.
1375 ptrdiff_t getStartIndex() const { return this->base.second; }
1376
1377 /// See `detail::indexed_accessor_range_base` for details.
1378 static std::pair<BaseT, ptrdiff_t>
1379 offset_base(const std::pair<BaseT, ptrdiff_t> &base, ptrdiff_t index) {
1380 // We encode the internal base as a pair of the derived base and a start
1381 // index into the derived base.
1382 return std::make_pair(base.first, base.second + index);
1383 }
1384 /// See `detail::indexed_accessor_range_base` for details.
1385 static ReferenceT
1386 dereference_iterator(const std::pair<BaseT, ptrdiff_t> &base,
1387 ptrdiff_t index) {
1388 return DerivedT::dereference(base.first, base.second + index);
1389 }
1390};
1391
1392namespace detail {
1393/// Return a reference to the first or second member of a reference. Otherwise,
1394/// return a copy of the member of a temporary.
1395///
1396/// When passing a range whose iterators return values instead of references,
1397/// the reference must be dropped from `decltype((elt.first))`, which will
1398/// always be a reference, to avoid returning a reference to a temporary.
1399template <typename EltTy, typename FirstTy> class first_or_second_type {
1400public:
1401 using type = std::conditional_t<std::is_reference<EltTy>::value, FirstTy,
1402 std::remove_reference_t<FirstTy>>;
1403};
1404} // end namespace detail
1405
1406/// Given a container of pairs, return a range over the first elements.
1407template <typename ContainerTy> auto make_first_range(ContainerTy &&c) {
1408 using EltTy = decltype(*adl_begin(c));
1409 return llvm::map_range(std::forward<ContainerTy>(c),
1410 [](EltTy elt) -> typename detail::first_or_second_type<
1411 EltTy, decltype((elt.first))>::type {
1412 return elt.first;
1413 });
1414}
1415
1416/// Given a container of pairs, return a range over the second elements.
1417template <typename ContainerTy> auto make_second_range(ContainerTy &&c) {
1418 using EltTy = decltype(*adl_begin(c));
1419 return llvm::map_range(
1420 std::forward<ContainerTy>(c),
1421 [](EltTy elt) ->
1422 typename detail::first_or_second_type<EltTy,
1423 decltype((elt.second))>::type {
1424 return elt.second;
1425 });
1426}
1427
1428//===----------------------------------------------------------------------===//
1429// Extra additions to <utility>
1430//===----------------------------------------------------------------------===//
1431
1432/// Function object to check whether the first component of a container
1433/// supported by std::get (like std::pair and std::tuple) compares less than the
1434/// first component of another container.
1436 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
1437 return std::less<>()(std::get<0>(lhs), std::get<0>(rhs));
1438 }
1439};
1440
1441/// Function object to check whether the second component of a container
1442/// supported by std::get (like std::pair and std::tuple) compares less than the
1443/// second component of another container.
1445 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
1446 return std::less<>()(std::get<1>(lhs), std::get<1>(rhs));
1447 }
1448};
1449
1450/// \brief Function object to apply a binary function to the first component of
1451/// a std::pair.
1452template<typename FuncTy>
1453struct on_first {
1454 FuncTy func;
1455
1456 template <typename T>
1457 decltype(auto) operator()(const T &lhs, const T &rhs) const {
1458 return func(lhs.first, rhs.first);
1459 }
1460};
1461
1462/// Utility type to build an inheritance chain that makes it easy to rank
1463/// overload candidates.
1464template <int N> struct rank : rank<N - 1> {};
1465template <> struct rank<0> {};
1466
1467namespace detail {
1468template <typename... Ts> struct Visitor;
1469
1470template <typename HeadT, typename... TailTs>
1471struct Visitor<HeadT, TailTs...> : remove_cvref_t<HeadT>, Visitor<TailTs...> {
1472 explicit constexpr Visitor(HeadT &&Head, TailTs &&...Tail)
1473 : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)),
1474 Visitor<TailTs...>(std::forward<TailTs>(Tail)...) {}
1475 using remove_cvref_t<HeadT>::operator();
1476 using Visitor<TailTs...>::operator();
1477};
1478
1479template <typename HeadT> struct Visitor<HeadT> : remove_cvref_t<HeadT> {
1480 explicit constexpr Visitor(HeadT &&Head)
1481 : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)) {}
1482 using remove_cvref_t<HeadT>::operator();
1483};
1484} // namespace detail
1485
1486/// Returns an opaquely-typed Callable object whose operator() overload set is
1487/// the sum of the operator() overload sets of each CallableT in CallableTs.
1488///
1489/// The type of the returned object derives from each CallableT in CallableTs.
1490/// The returned object is constructed by invoking the appropriate copy or move
1491/// constructor of each CallableT, as selected by overload resolution on the
1492/// corresponding argument to makeVisitor.
1493///
1494/// Example:
1495///
1496/// \code
1497/// auto visitor = makeVisitor([](auto) { return "unhandled type"; },
1498/// [](int i) { return "int"; },
1499/// [](std::string s) { return "str"; });
1500/// auto a = visitor(42); // `a` is now "int".
1501/// auto b = visitor("foo"); // `b` is now "str".
1502/// auto c = visitor(3.14f); // `c` is now "unhandled type".
1503/// \endcode
1504///
1505/// Example of making a visitor with a lambda which captures a move-only type:
1506///
1507/// \code
1508/// std::unique_ptr<FooHandler> FH = /* ... */;
1509/// auto visitor = makeVisitor(
1510/// [FH{std::move(FH)}](Foo F) { return FH->handle(F); },
1511/// [](int i) { return i; },
1512/// [](std::string s) { return atoi(s); });
1513/// \endcode
1514template <typename... CallableTs>
1515constexpr decltype(auto) makeVisitor(CallableTs &&...Callables) {
1516 return detail::Visitor<CallableTs...>(std::forward<CallableTs>(Callables)...);
1517}
1518
1519//===----------------------------------------------------------------------===//
1520// Extra additions to <algorithm>
1521//===----------------------------------------------------------------------===//
1522
1523// We have a copy here so that LLVM behaves the same when using different
1524// standard libraries.
1525template <class Iterator, class RNG>
1526void shuffle(Iterator first, Iterator last, RNG &&g) {
1527 // It would be better to use a std::uniform_int_distribution,
1528 // but that would be stdlib dependent.
1529 typedef
1530 typename std::iterator_traits<Iterator>::difference_type difference_type;
1531 for (auto size = last - first; size > 1; ++first, (void)--size) {
1532 difference_type offset = g() % size;
1533 // Avoid self-assignment due to incorrect assertions in libstdc++
1534 // containers (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85828).
1535 if (offset != difference_type(0))
1536 std::iter_swap(first, first + offset);
1537 }
1538}
1539
1540/// Adapt std::less<T> for array_pod_sort.
1541template<typename T>
1542inline int array_pod_sort_comparator(const void *P1, const void *P2) {
1543 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
1544 *reinterpret_cast<const T*>(P2)))
1545 return -1;
1546 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
1547 *reinterpret_cast<const T*>(P1)))
1548 return 1;
1549 return 0;
1550}
1551
1552/// get_array_pod_sort_comparator - This is an internal helper function used to
1553/// get type deduction of T right.
1554template<typename T>
1555inline int (*get_array_pod_sort_comparator(const T &))
1556 (const void*, const void*) {
1558}
1559
1560#ifdef EXPENSIVE_CHECKS
1561namespace detail {
1562
1563inline unsigned presortShuffleEntropy() {
1564 static unsigned Result(std::random_device{}());
1565 return Result;
1566}
1567
1568template <class IteratorTy>
1569inline void presortShuffle(IteratorTy Start, IteratorTy End) {
1570 std::mt19937 Generator(presortShuffleEntropy());
1571 llvm::shuffle(Start, End, Generator);
1572}
1573
1574} // end namespace detail
1575#endif
1576
1577/// array_pod_sort - This sorts an array with the specified start and end
1578/// extent. This is just like std::sort, except that it calls qsort instead of
1579/// using an inlined template. qsort is slightly slower than std::sort, but
1580/// most sorts are not performance critical in LLVM and std::sort has to be
1581/// template instantiated for each type, leading to significant measured code
1582/// bloat. This function should generally be used instead of std::sort where
1583/// possible.
1584///
1585/// This function assumes that you have simple POD-like types that can be
1586/// compared with std::less and can be moved with memcpy. If this isn't true,
1587/// you should use std::sort.
1588///
1589/// NOTE: If qsort_r were portable, we could allow a custom comparator and
1590/// default to std::less.
1591template<class IteratorTy>
1592inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
1593 // Don't inefficiently call qsort with one element or trigger undefined
1594 // behavior with an empty sequence.
1595 auto NElts = End - Start;
1596 if (NElts <= 1) return;
1597#ifdef EXPENSIVE_CHECKS
1598 detail::presortShuffle<IteratorTy>(Start, End);
1599#endif
1600 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
1601}
1602
1603template <class IteratorTy>
1604inline void array_pod_sort(
1605 IteratorTy Start, IteratorTy End,
1606 int (*Compare)(
1607 const typename std::iterator_traits<IteratorTy>::value_type *,
1608 const typename std::iterator_traits<IteratorTy>::value_type *)) {
1609 // Don't inefficiently call qsort with one element or trigger undefined
1610 // behavior with an empty sequence.
1611 auto NElts = End - Start;
1612 if (NElts <= 1) return;
1613#ifdef EXPENSIVE_CHECKS
1614 detail::presortShuffle<IteratorTy>(Start, End);
1615#endif
1616 qsort(&*Start, NElts, sizeof(*Start),
1617 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
1618}
1619
1620namespace detail {
1621template <typename T>
1622// We can use qsort if the iterator type is a pointer and the underlying value
1623// is trivially copyable.
1624using sort_trivially_copyable = std::conjunction<
1625 std::is_pointer<T>,
1626 std::is_trivially_copyable<typename std::iterator_traits<T>::value_type>>;
1627} // namespace detail
1628
1629// Provide wrappers to std::sort which shuffle the elements before sorting
1630// to help uncover non-deterministic behavior (PR35135).
1631template <typename IteratorTy>
1632inline void sort(IteratorTy Start, IteratorTy End) {
1634 // Forward trivially copyable types to array_pod_sort. This avoids a large
1635 // amount of code bloat for a minor performance hit.
1636 array_pod_sort(Start, End);
1637 } else {
1638#ifdef EXPENSIVE_CHECKS
1639 detail::presortShuffle<IteratorTy>(Start, End);
1640#endif
1641 std::sort(Start, End);
1642 }
1643}
1644
1645template <typename Container> inline void sort(Container &&C) {
1647}
1648
1649template <typename IteratorTy, typename Compare>
1650inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
1651#ifdef EXPENSIVE_CHECKS
1652 detail::presortShuffle<IteratorTy>(Start, End);
1653#endif
1654 std::sort(Start, End, Comp);
1655}
1656
1657template <typename Container, typename Compare>
1658inline void sort(Container &&C, Compare Comp) {
1659 llvm::sort(adl_begin(C), adl_end(C), Comp);
1660}
1661
1662/// Get the size of a range. This is a wrapper function around std::distance
1663/// which is only enabled when the operation is O(1).
1664template <typename R>
1665auto size(R &&Range,
1666 std::enable_if_t<
1667 std::is_base_of<std::random_access_iterator_tag,
1668 typename std::iterator_traits<decltype(
1669 Range.begin())>::iterator_category>::value,
1670 void> * = nullptr) {
1671 return std::distance(Range.begin(), Range.end());
1672}
1673
1674namespace detail {
1675template <typename Range>
1677 decltype(adl_size(std::declval<Range &>()));
1678
1679template <typename Range>
1680static constexpr bool HasFreeFunctionSize =
1682} // namespace detail
1683
1684/// Returns the size of the \p Range, i.e., the number of elements. This
1685/// implementation takes inspiration from `std::ranges::size` from C++20 and
1686/// delegates the size check to `adl_size` or `std::distance`, in this order of
1687/// preference. Unlike `llvm::size`, this function does *not* guarantee O(1)
1688/// running time, and is intended to be used in generic code that does not know
1689/// the exact range type.
1690template <typename R> constexpr size_t range_size(R &&Range) {
1691 if constexpr (detail::HasFreeFunctionSize<R>)
1692 return adl_size(Range);
1693 else
1694 return static_cast<size_t>(std::distance(adl_begin(Range), adl_end(Range)));
1695}
1696
1697/// Provide wrappers to std::for_each which take ranges instead of having to
1698/// pass begin/end explicitly.
1699template <typename R, typename UnaryFunction>
1700UnaryFunction for_each(R &&Range, UnaryFunction F) {
1701 return std::for_each(adl_begin(Range), adl_end(Range), F);
1702}
1703
1704/// Provide wrappers to std::all_of which take ranges instead of having to pass
1705/// begin/end explicitly.
1706template <typename R, typename UnaryPredicate>
1707bool all_of(R &&Range, UnaryPredicate P) {
1708 return std::all_of(adl_begin(Range), adl_end(Range), P);
1709}
1710
1711/// Provide wrappers to std::any_of which take ranges instead of having to pass
1712/// begin/end explicitly.
1713template <typename R, typename UnaryPredicate>
1714bool any_of(R &&Range, UnaryPredicate P) {
1715 return std::any_of(adl_begin(Range), adl_end(Range), P);
1716}
1717
1718/// Provide wrappers to std::none_of which take ranges instead of having to pass
1719/// begin/end explicitly.
1720template <typename R, typename UnaryPredicate>
1721bool none_of(R &&Range, UnaryPredicate P) {
1722 return std::none_of(adl_begin(Range), adl_end(Range), P);
1723}
1724
1725/// Provide wrappers to std::fill which take ranges instead of having to pass
1726/// begin/end explicitly.
1727template <typename R, typename T> void fill(R &&Range, T &&Value) {
1728 std::fill(adl_begin(Range), adl_end(Range), std::forward<T>(Value));
1729}
1730
1731/// Provide wrappers to std::find which take ranges instead of having to pass
1732/// begin/end explicitly.
1733template <typename R, typename T> auto find(R &&Range, const T &Val) {
1734 return std::find(adl_begin(Range), adl_end(Range), Val);
1735}
1736
1737/// Provide wrappers to std::find_if which take ranges instead of having to pass
1738/// begin/end explicitly.
1739template <typename R, typename UnaryPredicate>
1740auto find_if(R &&Range, UnaryPredicate P) {
1741 return std::find_if(adl_begin(Range), adl_end(Range), P);
1742}
1743
1744template <typename R, typename UnaryPredicate>
1745auto find_if_not(R &&Range, UnaryPredicate P) {
1746 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
1747}
1748
1749/// Provide wrappers to std::remove_if which take ranges instead of having to
1750/// pass begin/end explicitly.
1751template <typename R, typename UnaryPredicate>
1752auto remove_if(R &&Range, UnaryPredicate P) {
1753 return std::remove_if(adl_begin(Range), adl_end(Range), P);
1754}
1755
1756/// Provide wrappers to std::copy_if which take ranges instead of having to
1757/// pass begin/end explicitly.
1758template <typename R, typename OutputIt, typename UnaryPredicate>
1759OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
1760 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
1761}
1762
1763/// Return the single value in \p Range that satisfies
1764/// \p P(<member of \p Range> *, AllowRepeats)->T * returning nullptr
1765/// when no values or multiple values were found.
1766/// When \p AllowRepeats is true, multiple values that compare equal
1767/// are allowed.
1768template <typename T, typename R, typename Predicate>
1769T *find_singleton(R &&Range, Predicate P, bool AllowRepeats = false) {
1770 T *RC = nullptr;
1771 for (auto &&A : Range) {
1772 if (T *PRC = P(A, AllowRepeats)) {
1773 if (RC) {
1774 if (!AllowRepeats || PRC != RC)
1775 return nullptr;
1776 } else {
1777 RC = PRC;
1778 }
1779 }
1780 }
1781 return RC;
1782}
1783
1784/// Return a pair consisting of the single value in \p Range that satisfies
1785/// \p P(<member of \p Range> *, AllowRepeats)->std::pair<T*, bool> returning
1786/// nullptr when no values or multiple values were found, and a bool indicating
1787/// whether multiple values were found to cause the nullptr.
1788/// When \p AllowRepeats is true, multiple values that compare equal are
1789/// allowed. The predicate \p P returns a pair<T *, bool> where T is the
1790/// singleton while the bool indicates whether multiples have already been
1791/// found. It is expected that first will be nullptr when second is true.
1792/// This allows using find_singleton_nested within the predicate \P.
1793template <typename T, typename R, typename Predicate>
1794std::pair<T *, bool> find_singleton_nested(R &&Range, Predicate P,
1795 bool AllowRepeats = false) {
1796 T *RC = nullptr;
1797 for (auto *A : Range) {
1798 std::pair<T *, bool> PRC = P(A, AllowRepeats);
1799 if (PRC.second) {
1800 assert(PRC.first == nullptr &&
1801 "Inconsistent return values in find_singleton_nested.");
1802 return PRC;
1803 }
1804 if (PRC.first) {
1805 if (RC) {
1806 if (!AllowRepeats || PRC.first != RC)
1807 return {nullptr, true};
1808 } else {
1809 RC = PRC.first;
1810 }
1811 }
1812 }
1813 return {RC, false};
1814}
1815
1816template <typename R, typename OutputIt>
1817OutputIt copy(R &&Range, OutputIt Out) {
1818 return std::copy(adl_begin(Range), adl_end(Range), Out);
1819}
1820
1821/// Provide wrappers to std::replace_copy_if which take ranges instead of having
1822/// to pass begin/end explicitly.
1823template <typename R, typename OutputIt, typename UnaryPredicate, typename T>
1824OutputIt replace_copy_if(R &&Range, OutputIt Out, UnaryPredicate P,
1825 const T &NewValue) {
1826 return std::replace_copy_if(adl_begin(Range), adl_end(Range), Out, P,
1827 NewValue);
1828}
1829
1830/// Provide wrappers to std::replace_copy which take ranges instead of having to
1831/// pass begin/end explicitly.
1832template <typename R, typename OutputIt, typename T>
1833OutputIt replace_copy(R &&Range, OutputIt Out, const T &OldValue,
1834 const T &NewValue) {
1835 return std::replace_copy(adl_begin(Range), adl_end(Range), Out, OldValue,
1836 NewValue);
1837}
1838
1839/// Provide wrappers to std::replace which take ranges instead of having to pass
1840/// begin/end explicitly.
1841template <typename R, typename T>
1842void replace(R &&Range, const T &OldValue, const T &NewValue) {
1843 std::replace(adl_begin(Range), adl_end(Range), OldValue, NewValue);
1844}
1845
1846/// Provide wrappers to std::move which take ranges instead of having to
1847/// pass begin/end explicitly.
1848template <typename R, typename OutputIt>
1849OutputIt move(R &&Range, OutputIt Out) {
1850 return std::move(adl_begin(Range), adl_end(Range), Out);
1851}
1852
1853namespace detail {
1854template <typename Range, typename Element>
1856 decltype(std::declval<Range &>().contains(std::declval<const Element &>()));
1857
1858template <typename Range, typename Element>
1859static constexpr bool HasMemberContains =
1861
1862template <typename Range, typename Element>
1864 decltype(std::declval<Range &>().find(std::declval<const Element &>()) !=
1865 std::declval<Range &>().end());
1866
1867template <typename Range, typename Element>
1868static constexpr bool HasMemberFind =
1870
1871} // namespace detail
1872
1873/// Returns true if \p Element is found in \p Range. Delegates the check to
1874/// either `.contains(Element)`, `.find(Element)`, or `std::find`, in this
1875/// order of preference. This is intended as the canonical way to check if an
1876/// element exists in a range in generic code or range type that does not
1877/// expose a `.contains(Element)` member.
1878template <typename R, typename E>
1879bool is_contained(R &&Range, const E &Element) {
1880 if constexpr (detail::HasMemberContains<R, E>)
1881 return Range.contains(Element);
1882 else if constexpr (detail::HasMemberFind<R, E>)
1883 return Range.find(Element) != Range.end();
1884 else
1885 return std::find(adl_begin(Range), adl_end(Range), Element) !=
1886 adl_end(Range);
1887}
1888
1889/// Returns true iff \p Element exists in \p Set. This overload takes \p Set as
1890/// an initializer list and is `constexpr`-friendly.
1891template <typename T, typename E>
1892constexpr bool is_contained(std::initializer_list<T> Set, const E &Element) {
1893 // TODO: Use std::find when we switch to C++20.
1894 for (const T &V : Set)
1895 if (V == Element)
1896 return true;
1897 return false;
1898}
1899
1900/// Wrapper function around std::is_sorted to check if elements in a range \p R
1901/// are sorted with respect to a comparator \p C.
1902template <typename R, typename Compare> bool is_sorted(R &&Range, Compare C) {
1903 return std::is_sorted(adl_begin(Range), adl_end(Range), C);
1904}
1905
1906/// Wrapper function around std::is_sorted to check if elements in a range \p R
1907/// are sorted in non-descending order.
1908template <typename R> bool is_sorted(R &&Range) {
1909 return std::is_sorted(adl_begin(Range), adl_end(Range));
1910}
1911
1912/// Provide wrappers to std::includes which take ranges instead of having to
1913/// pass begin/end explicitly.
1914/// This function checks if the sorted range \p R2 is a subsequence of the
1915/// sorted range \p R1. The ranges must be sorted in non-descending order.
1916template <typename R1, typename R2> bool includes(R1 &&Range1, R2 &&Range2) {
1917 assert(is_sorted(Range1) && "Range1 must be sorted in non-descending order");
1918 assert(is_sorted(Range2) && "Range2 must be sorted in non-descending order");
1919 return std::includes(adl_begin(Range1), adl_end(Range1), adl_begin(Range2),
1920 adl_end(Range2));
1921}
1922
1923/// This function checks if the sorted range \p R2 is a subsequence of the
1924/// sorted range \p R1. The ranges must be sorted with respect to a comparator
1925/// \p C.
1926template <typename R1, typename R2, typename Compare>
1927bool includes(R1 &&Range1, R2 &&Range2, Compare &&C) {
1928 assert(is_sorted(Range1, C) && "Range1 must be sorted with respect to C");
1929 assert(is_sorted(Range2, C) && "Range2 must be sorted with respect to C");
1930 return std::includes(adl_begin(Range1), adl_end(Range1), adl_begin(Range2),
1931 adl_end(Range2), std::forward<Compare>(C));
1932}
1933
1934/// Wrapper function around std::count to count the number of times an element
1935/// \p Element occurs in the given range \p Range.
1936template <typename R, typename E> auto count(R &&Range, const E &Element) {
1937 return std::count(adl_begin(Range), adl_end(Range), Element);
1938}
1939
1940/// Wrapper function around std::count_if to count the number of times an
1941/// element satisfying a given predicate occurs in a range.
1942template <typename R, typename UnaryPredicate>
1943auto count_if(R &&Range, UnaryPredicate P) {
1944 return std::count_if(adl_begin(Range), adl_end(Range), P);
1945}
1946
1947/// Wrapper function around std::transform to apply a function to a range and
1948/// store the result elsewhere.
1949template <typename R, typename OutputIt, typename UnaryFunction>
1950OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F) {
1951 return std::transform(adl_begin(Range), adl_end(Range), d_first, F);
1952}
1953
1954/// Provide wrappers to std::partition which take ranges instead of having to
1955/// pass begin/end explicitly.
1956template <typename R, typename UnaryPredicate>
1957auto partition(R &&Range, UnaryPredicate P) {
1958 return std::partition(adl_begin(Range), adl_end(Range), P);
1959}
1960
1961/// Provide wrappers to std::binary_search which take ranges instead of having
1962/// to pass begin/end explicitly.
1963template <typename R, typename T> auto binary_search(R &&Range, T &&Value) {
1964 return std::binary_search(adl_begin(Range), adl_end(Range),
1965 std::forward<T>(Value));
1966}
1967
1968template <typename R, typename T, typename Compare>
1969auto binary_search(R &&Range, T &&Value, Compare C) {
1970 return std::binary_search(adl_begin(Range), adl_end(Range),
1971 std::forward<T>(Value), C);
1972}
1973
1974/// Provide wrappers to std::lower_bound which take ranges instead of having to
1975/// pass begin/end explicitly.
1976template <typename R, typename T> auto lower_bound(R &&Range, T &&Value) {
1977 return std::lower_bound(adl_begin(Range), adl_end(Range),
1978 std::forward<T>(Value));
1979}
1980
1981template <typename R, typename T, typename Compare>
1982auto lower_bound(R &&Range, T &&Value, Compare C) {
1983 return std::lower_bound(adl_begin(Range), adl_end(Range),
1984 std::forward<T>(Value), C);
1985}
1986
1987/// Provide wrappers to std::upper_bound which take ranges instead of having to
1988/// pass begin/end explicitly.
1989template <typename R, typename T> auto upper_bound(R &&Range, T &&Value) {
1990 return std::upper_bound(adl_begin(Range), adl_end(Range),
1991 std::forward<T>(Value));
1992}
1993
1994template <typename R, typename T, typename Compare>
1995auto upper_bound(R &&Range, T &&Value, Compare C) {
1996 return std::upper_bound(adl_begin(Range), adl_end(Range),
1997 std::forward<T>(Value), C);
1998}
1999
2000/// Provide wrappers to std::min_element which take ranges instead of having to
2001/// pass begin/end explicitly.
2002template <typename R> auto min_element(R &&Range) {
2003 return std::min_element(adl_begin(Range), adl_end(Range));
2004}
2005
2006template <typename R, typename Compare> auto min_element(R &&Range, Compare C) {
2007 return std::min_element(adl_begin(Range), adl_end(Range), C);
2008}
2009
2010/// Provide wrappers to std::max_element which take ranges instead of having to
2011/// pass begin/end explicitly.
2012template <typename R> auto max_element(R &&Range) {
2013 return std::max_element(adl_begin(Range), adl_end(Range));
2014}
2015
2016template <typename R, typename Compare> auto max_element(R &&Range, Compare C) {
2017 return std::max_element(adl_begin(Range), adl_end(Range), C);
2018}
2019
2020/// Provide wrappers to std::mismatch which take ranges instead of having to
2021/// pass begin/end explicitly.
2022/// This function returns a pair of iterators for the first mismatching elements
2023/// from `R1` and `R2`. As an example, if:
2024///
2025/// R1 = [0, 1, 4, 6], R2 = [0, 1, 5, 6]
2026///
2027/// this function will return a pair of iterators, first pointing to R1[2] and
2028/// second pointing to R2[2].
2029template <typename R1, typename R2> auto mismatch(R1 &&Range1, R2 &&Range2) {
2030 return std::mismatch(adl_begin(Range1), adl_end(Range1), adl_begin(Range2),
2031 adl_end(Range2));
2032}
2033
2034template <typename R, typename IterTy>
2035auto uninitialized_copy(R &&Src, IterTy Dst) {
2036 return std::uninitialized_copy(adl_begin(Src), adl_end(Src), Dst);
2037}
2038
2039template <typename R>
2041 std::stable_sort(adl_begin(Range), adl_end(Range));
2042}
2043
2044template <typename R, typename Compare>
2045void stable_sort(R &&Range, Compare C) {
2046 std::stable_sort(adl_begin(Range), adl_end(Range), C);
2047}
2048
2049/// Binary search for the first iterator in a range where a predicate is false.
2050/// Requires that C is always true below some limit, and always false above it.
2051template <typename R, typename Predicate,
2052 typename Val = decltype(*adl_begin(std::declval<R>()))>
2054 return std::partition_point(adl_begin(Range), adl_end(Range), P);
2055}
2056
2057template<typename Range, typename Predicate>
2059 return std::unique(adl_begin(R), adl_end(R), P);
2060}
2061
2062/// Wrapper function around std::unique to allow calling unique on a
2063/// container without having to specify the begin/end iterators.
2064template <typename Range> auto unique(Range &&R) {
2065 return std::unique(adl_begin(R), adl_end(R));
2066}
2067
2068/// Wrapper function around std::equal to detect if pair-wise elements between
2069/// two ranges are the same.
2070template <typename L, typename R> bool equal(L &&LRange, R &&RRange) {
2071 return std::equal(adl_begin(LRange), adl_end(LRange), adl_begin(RRange),
2072 adl_end(RRange));
2073}
2074
2075template <typename L, typename R, typename BinaryPredicate>
2076bool equal(L &&LRange, R &&RRange, BinaryPredicate P) {
2077 return std::equal(adl_begin(LRange), adl_end(LRange), adl_begin(RRange),
2078 adl_end(RRange), P);
2079}
2080
2081/// Returns true if all elements in Range are equal or when the Range is empty.
2082template <typename R> bool all_equal(R &&Range) {
2083 auto Begin = adl_begin(Range);
2084 auto End = adl_end(Range);
2085 return Begin == End || std::equal(std::next(Begin), End, Begin);
2086}
2087
2088/// Returns true if all Values in the initializer lists are equal or the list
2089// is empty.
2090template <typename T> bool all_equal(std::initializer_list<T> Values) {
2091 return all_equal<std::initializer_list<T>>(std::move(Values));
2092}
2093
2094/// Provide a container algorithm similar to C++ Library Fundamentals v2's
2095/// `erase_if` which is equivalent to:
2096///
2097/// C.erase(remove_if(C, pred), C.end());
2098///
2099/// This version works for any container with an erase method call accepting
2100/// two iterators.
2101template <typename Container, typename UnaryPredicate>
2102void erase_if(Container &C, UnaryPredicate P) {
2103 C.erase(remove_if(C, P), C.end());
2104}
2105
2106/// Wrapper function to remove a value from a container:
2107///
2108/// C.erase(remove(C.begin(), C.end(), V), C.end());
2109template <typename Container, typename ValueType>
2110void erase(Container &C, ValueType V) {
2111 C.erase(std::remove(C.begin(), C.end(), V), C.end());
2112}
2113
2114/// Wrapper function to append range `R` to container `C`.
2115///
2116/// C.insert(C.end(), R.begin(), R.end());
2117template <typename Container, typename Range>
2118void append_range(Container &C, Range &&R) {
2119 C.insert(C.end(), adl_begin(R), adl_end(R));
2120}
2121
2122/// Appends all `Values` to container `C`.
2123template <typename Container, typename... Args>
2124void append_values(Container &C, Args &&...Values) {
2125 C.reserve(range_size(C) + sizeof...(Args));
2126 // Append all values one by one.
2127 ((void)C.insert(C.end(), std::forward<Args>(Values)), ...);
2128}
2129
2130/// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
2131/// the range [ValIt, ValEnd) (which is not from the same container).
2132template <typename Container, typename RandomAccessIterator>
2133void replace(Container &Cont, typename Container::iterator ContIt,
2134 typename Container::iterator ContEnd, RandomAccessIterator ValIt,
2135 RandomAccessIterator ValEnd) {
2136 while (true) {
2137 if (ValIt == ValEnd) {
2138 Cont.erase(ContIt, ContEnd);
2139 return;
2140 }
2141 if (ContIt == ContEnd) {
2142 Cont.insert(ContIt, ValIt, ValEnd);
2143 return;
2144 }
2145 *ContIt = *ValIt;
2146 ++ContIt;
2147 ++ValIt;
2148 }
2149}
2150
2151/// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
2152/// the range R.
2153template <typename Container, typename Range = std::initializer_list<
2154 typename Container::value_type>>
2155void replace(Container &Cont, typename Container::iterator ContIt,
2156 typename Container::iterator ContEnd, Range &&R) {
2157 replace(Cont, ContIt, ContEnd, adl_begin(R), adl_end(R));
2158}
2159
2160/// An STL-style algorithm similar to std::for_each that applies a second
2161/// functor between every pair of elements.
2162///
2163/// This provides the control flow logic to, for example, print a
2164/// comma-separated list:
2165/// \code
2166/// interleave(names.begin(), names.end(),
2167/// [&](StringRef name) { os << name; },
2168/// [&] { os << ", "; });
2169/// \endcode
2170template <typename ForwardIterator, typename UnaryFunctor,
2171 typename NullaryFunctor,
2172 typename = std::enable_if_t<
2173 !std::is_constructible<StringRef, UnaryFunctor>::value &&
2174 !std::is_constructible<StringRef, NullaryFunctor>::value>>
2175inline void interleave(ForwardIterator begin, ForwardIterator end,
2176 UnaryFunctor each_fn, NullaryFunctor between_fn) {
2177 if (begin == end)
2178 return;
2179 each_fn(*begin);
2180 ++begin;
2181 for (; begin != end; ++begin) {
2182 between_fn();
2183 each_fn(*begin);
2184 }
2185}
2186
2187template <typename Container, typename UnaryFunctor, typename NullaryFunctor,
2188 typename = std::enable_if_t<
2189 !std::is_constructible<StringRef, UnaryFunctor>::value &&
2190 !std::is_constructible<StringRef, NullaryFunctor>::value>>
2191inline void interleave(const Container &c, UnaryFunctor each_fn,
2192 NullaryFunctor between_fn) {
2193 interleave(adl_begin(c), adl_end(c), each_fn, between_fn);
2194}
2195
2196/// Overload of interleave for the common case of string separator.
2197template <typename Container, typename UnaryFunctor, typename StreamT,
2199inline void interleave(const Container &c, StreamT &os, UnaryFunctor each_fn,
2200 const StringRef &separator) {
2201 interleave(adl_begin(c), adl_end(c), each_fn, [&] { os << separator; });
2202}
2203template <typename Container, typename StreamT,
2205inline void interleave(const Container &c, StreamT &os,
2206 const StringRef &separator) {
2207 interleave(
2208 c, os, [&](const T &a) { os << a; }, separator);
2209}
2210
2211template <typename Container, typename UnaryFunctor, typename StreamT,
2213inline void interleaveComma(const Container &c, StreamT &os,
2214 UnaryFunctor each_fn) {
2215 interleave(c, os, each_fn, ", ");
2216}
2217template <typename Container, typename StreamT,
2219inline void interleaveComma(const Container &c, StreamT &os) {
2220 interleaveComma(c, os, [&](const T &a) { os << a; });
2221}
2222
2223//===----------------------------------------------------------------------===//
2224// Extra additions to <memory>
2225//===----------------------------------------------------------------------===//
2226
2228 void operator()(void* v) {
2229 ::free(v);
2230 }
2231};
2232
2233template<typename First, typename Second>
2235 size_t operator()(const std::pair<First, Second> &P) const {
2236 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
2237 }
2238};
2239
2240/// Binary functor that adapts to any other binary functor after dereferencing
2241/// operands.
2242template <typename T> struct deref {
2244
2245 // Could be further improved to cope with non-derivable functors and
2246 // non-binary functors (should be a variadic template member function
2247 // operator()).
2248 template <typename A, typename B> auto operator()(A &lhs, B &rhs) const {
2249 assert(lhs);
2250 assert(rhs);
2251 return func(*lhs, *rhs);
2252 }
2253};
2254
2255namespace detail {
2256
2257/// Tuple-like type for `zip_enumerator` dereference.
2258template <typename... Refs> struct enumerator_result;
2259
2260template <typename... Iters>
2262
2263/// Zippy iterator that uses the second iterator for comparisons. For the
2264/// increment to be safe, the second range has to be the shortest.
2265/// Returns `enumerator_result` on dereference to provide `.index()` and
2266/// `.value()` member functions.
2267/// Note: Because the dereference operator returns `enumerator_result` as a
2268/// value instead of a reference and does not strictly conform to the C++17's
2269/// definition of forward iterator. However, it satisfies all the
2270/// forward_iterator requirements that the `zip_common` and `zippy` depend on
2271/// and fully conforms to the C++20 definition of forward iterator.
2272/// This is similar to `std::vector<bool>::iterator` that returns bit reference
2273/// wrappers on dereference.
2274template <typename... Iters>
2275struct zip_enumerator : zip_common<zip_enumerator<Iters...>,
2276 EnumeratorTupleType<Iters...>, Iters...> {
2277 static_assert(sizeof...(Iters) >= 2, "Expected at least two iteratees");
2278 using zip_common<zip_enumerator<Iters...>, EnumeratorTupleType<Iters...>,
2279 Iters...>::zip_common;
2280
2281 bool operator==(const zip_enumerator &Other) const {
2282 return std::get<1>(this->iterators) == std::get<1>(Other.iterators);
2283 }
2284};
2285
2286template <typename... Refs> struct enumerator_result<std::size_t, Refs...> {
2287 static constexpr std::size_t NumRefs = sizeof...(Refs);
2288 static_assert(NumRefs != 0);
2289 // `NumValues` includes the index.
2290 static constexpr std::size_t NumValues = NumRefs + 1;
2291
2292 // Tuple type whose element types are references for each `Ref`.
2293 using range_reference_tuple = std::tuple<Refs...>;
2294 // Tuple type who elements are references to all values, including both
2295 // the index and `Refs` reference types.
2296 using value_reference_tuple = std::tuple<std::size_t, Refs...>;
2297
2298 enumerator_result(std::size_t Index, Refs &&...Rs)
2299 : Idx(Index), Storage(std::forward<Refs>(Rs)...) {}
2300
2301 /// Returns the 0-based index of the current position within the original
2302 /// input range(s).
2303 std::size_t index() const { return Idx; }
2304
2305 /// Returns the value(s) for the current iterator. This does not include the
2306 /// index.
2307 decltype(auto) value() const {
2308 if constexpr (NumRefs == 1)
2309 return std::get<0>(Storage);
2310 else
2311 return Storage;
2312 }
2313
2314 /// Returns the value at index `I`. This case covers the index.
2315 template <std::size_t I, typename = std::enable_if_t<I == 0>>
2316 friend std::size_t get(const enumerator_result &Result) {
2317 return Result.Idx;
2318 }
2319
2320 /// Returns the value at index `I`. This case covers references to the
2321 /// iteratees.
2322 template <std::size_t I, typename = std::enable_if_t<I != 0>>
2323 friend decltype(auto) get(const enumerator_result &Result) {
2324 // Note: This is a separate function from the other `get`, instead of an
2325 // `if constexpr` case, to work around an MSVC 19.31.31XXX compiler
2326 // (Visual Studio 2022 17.1) return type deduction bug.
2327 return std::get<I - 1>(Result.Storage);
2328 }
2329
2330 template <typename... Ts>
2331 friend bool operator==(const enumerator_result &Result,
2332 const std::tuple<std::size_t, Ts...> &Other) {
2333 static_assert(NumRefs == sizeof...(Ts), "Size mismatch");
2334 if (Result.Idx != std::get<0>(Other))
2335 return false;
2336 return Result.is_value_equal(Other, std::make_index_sequence<NumRefs>{});
2337 }
2338
2339private:
2340 template <typename Tuple, std::size_t... Idx>
2341 bool is_value_equal(const Tuple &Other, std::index_sequence<Idx...>) const {
2342 return ((std::get<Idx>(Storage) == std::get<Idx + 1>(Other)) && ...);
2343 }
2344
2345 std::size_t Idx;
2346 // Make this tuple mutable to avoid casts that obfuscate const-correctness
2347 // issues. Const-correctness of references is taken care of by `zippy` that
2348 // defines const-non and const iterator types that will propagate down to
2349 // `enumerator_result`'s `Refs`.
2350 // Note that unlike the results of `zip*` functions, `enumerate`'s result are
2351 // supposed to be modifiable even when defined as
2352 // `const`.
2353 mutable range_reference_tuple Storage;
2354};
2355
2357 : llvm::iterator_facade_base<index_iterator,
2358 std::random_access_iterator_tag, std::size_t> {
2359 index_iterator(std::size_t Index) : Index(Index) {}
2360
2361 index_iterator &operator+=(std::ptrdiff_t N) {
2362 Index += N;
2363 return *this;
2364 }
2365
2366 index_iterator &operator-=(std::ptrdiff_t N) {
2367 Index -= N;
2368 return *this;
2369 }
2370
2371 std::ptrdiff_t operator-(const index_iterator &R) const {
2372 return Index - R.Index;
2373 }
2374
2375 // Note: This dereference operator returns a value instead of a reference
2376 // and does not strictly conform to the C++17's definition of forward
2377 // iterator. However, it satisfies all the forward_iterator requirements
2378 // that the `zip_common` depends on and fully conforms to the C++20
2379 // definition of forward iterator.
2380 std::size_t operator*() const { return Index; }
2381
2382 friend bool operator==(const index_iterator &Lhs, const index_iterator &Rhs) {
2383 return Lhs.Index == Rhs.Index;
2384 }
2385
2386 friend bool operator<(const index_iterator &Lhs, const index_iterator &Rhs) {
2387 return Lhs.Index < Rhs.Index;
2388 }
2389
2390private:
2391 std::size_t Index;
2392};
2393
2394/// Infinite stream of increasing 0-based `size_t` indices.
2396 index_iterator begin() const { return {0}; }
2398 // We approximate 'infinity' with the max size_t value, which should be good
2399 // enough to index over any container.
2400 return index_iterator{std::numeric_limits<std::size_t>::max()};
2401 }
2402};
2403
2404} // end namespace detail
2405
2406/// Increasing range of `size_t` indices.
2408 std::size_t Begin;
2409 std::size_t End;
2410
2411public:
2412 index_range(std::size_t Begin, std::size_t End) : Begin(Begin), End(End) {}
2413 detail::index_iterator begin() const { return {Begin}; }
2414 detail::index_iterator end() const { return {End}; }
2415};
2416
2417/// Given two or more input ranges, returns a new range whose values are
2418/// tuples (A, B, C, ...), such that A is the 0-based index of the item in the
2419/// sequence, and B, C, ..., are the values from the original input ranges. All
2420/// input ranges are required to have equal lengths. Note that the returned
2421/// iterator allows for the values (B, C, ...) to be modified. Example:
2422///
2423/// ```c++
2424/// std::vector<char> Letters = {'A', 'B', 'C', 'D'};
2425/// std::vector<int> Vals = {10, 11, 12, 13};
2426///
2427/// for (auto [Index, Letter, Value] : enumerate(Letters, Vals)) {
2428/// printf("Item %zu - %c: %d\n", Index, Letter, Value);
2429/// Value -= 10;
2430/// }
2431/// ```
2432///
2433/// Output:
2434/// Item 0 - A: 10
2435/// Item 1 - B: 11
2436/// Item 2 - C: 12
2437/// Item 3 - D: 13
2438///
2439/// or using an iterator:
2440/// ```c++
2441/// for (auto it : enumerate(Vals)) {
2442/// it.value() += 10;
2443/// printf("Item %zu: %d\n", it.index(), it.value());
2444/// }
2445/// ```
2446///
2447/// Output:
2448/// Item 0: 20
2449/// Item 1: 21
2450/// Item 2: 22
2451/// Item 3: 23
2452///
2453template <typename FirstRange, typename... RestRanges>
2454auto enumerate(FirstRange &&First, RestRanges &&...Rest) {
2455 if constexpr (sizeof...(Rest) != 0) {
2456#ifndef NDEBUG
2457 // Note: Create an array instead of an initializer list to work around an
2458 // Apple clang 14 compiler bug.
2459 size_t sizes[] = {range_size(First), range_size(Rest)...};
2460 assert(all_equal(sizes) && "Ranges have different length");
2461#endif
2462 }
2464 FirstRange, RestRanges...>;
2465 return enumerator(detail::index_stream{}, std::forward<FirstRange>(First),
2466 std::forward<RestRanges>(Rest)...);
2467}
2468
2469namespace detail {
2470
2471template <typename Predicate, typename... Args>
2473 auto z = zip(args...);
2474 auto it = z.begin();
2475 auto end = z.end();
2476 while (it != end) {
2477 if (!std::apply([&](auto &&...args) { return P(args...); }, *it))
2478 return false;
2479 ++it;
2480 }
2481 return it.all_equals(end);
2482}
2483
2484// Just an adaptor to switch the order of argument and have the predicate before
2485// the zipped inputs.
2486template <typename... ArgsThenPredicate, size_t... InputIndexes>
2488 std::tuple<ArgsThenPredicate...> argsThenPredicate,
2489 std::index_sequence<InputIndexes...>) {
2490 auto constexpr OutputIndex =
2491 std::tuple_size<decltype(argsThenPredicate)>::value - 1;
2492 return all_of_zip_predicate_first(std::get<OutputIndex>(argsThenPredicate),
2493 std::get<InputIndexes>(argsThenPredicate)...);
2494}
2495
2496} // end namespace detail
2497
2498/// Compare two zipped ranges using the provided predicate (as last argument).
2499/// Return true if all elements satisfy the predicate and false otherwise.
2500// Return false if the zipped iterator aren't all at end (size mismatch).
2501template <typename... ArgsAndPredicate>
2502bool all_of_zip(ArgsAndPredicate &&...argsAndPredicate) {
2504 std::forward_as_tuple(argsAndPredicate...),
2505 std::make_index_sequence<sizeof...(argsAndPredicate) - 1>{});
2506}
2507
2508/// Return true if the sequence [Begin, End) has exactly N items. Runs in O(N)
2509/// time. Not meant for use with random-access iterators.
2510/// Can optionally take a predicate to filter lazily some items.
2511template <typename IterTy,
2512 typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
2514 IterTy &&Begin, IterTy &&End, unsigned N,
2515 Pred &&ShouldBeCounted =
2516 [](const decltype(*std::declval<IterTy>()) &) { return true; },
2517 std::enable_if_t<
2518 !std::is_base_of<std::random_access_iterator_tag,
2519 typename std::iterator_traits<std::remove_reference_t<
2520 decltype(Begin)>>::iterator_category>::value,
2521 void> * = nullptr) {
2522 for (; N; ++Begin) {
2523 if (Begin == End)
2524 return false; // Too few.
2525 N -= ShouldBeCounted(*Begin);
2526 }
2527 for (; Begin != End; ++Begin)
2528 if (ShouldBeCounted(*Begin))
2529 return false; // Too many.
2530 return true;
2531}
2532
2533/// Return true if the sequence [Begin, End) has N or more items. Runs in O(N)
2534/// time. Not meant for use with random-access iterators.
2535/// Can optionally take a predicate to lazily filter some items.
2536template <typename IterTy,
2537 typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
2539 IterTy &&Begin, IterTy &&End, unsigned N,
2540 Pred &&ShouldBeCounted =
2541 [](const decltype(*std::declval<IterTy>()) &) { return true; },
2542 std::enable_if_t<
2543 !std::is_base_of<std::random_access_iterator_tag,
2544 typename std::iterator_traits<std::remove_reference_t<
2545 decltype(Begin)>>::iterator_category>::value,
2546 void> * = nullptr) {
2547 for (; N; ++Begin) {
2548 if (Begin == End)
2549 return false; // Too few.
2550 N -= ShouldBeCounted(*Begin);
2551 }
2552 return true;
2553}
2554
2555/// Returns true if the sequence [Begin, End) has N or less items. Can
2556/// optionally take a predicate to lazily filter some items.
2557template <typename IterTy,
2558 typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
2560 IterTy &&Begin, IterTy &&End, unsigned N,
2561 Pred &&ShouldBeCounted = [](const decltype(*std::declval<IterTy>()) &) {
2562 return true;
2563 }) {
2564 assert(N != std::numeric_limits<unsigned>::max());
2565 return !hasNItemsOrMore(Begin, End, N + 1, ShouldBeCounted);
2566}
2567
2568/// Returns true if the given container has exactly N items
2569template <typename ContainerTy> bool hasNItems(ContainerTy &&C, unsigned N) {
2570 return hasNItems(adl_begin(C), adl_end(C), N);
2571}
2572
2573/// Returns true if the given container has N or more items
2574template <typename ContainerTy>
2575bool hasNItemsOrMore(ContainerTy &&C, unsigned N) {
2576 return hasNItemsOrMore(adl_begin(C), adl_end(C), N);
2577}
2578
2579/// Returns true if the given container has N or less items
2580template <typename ContainerTy>
2581bool hasNItemsOrLess(ContainerTy &&C, unsigned N) {
2582 return hasNItemsOrLess(adl_begin(C), adl_end(C), N);
2583}
2584
2585/// Returns a raw pointer that represents the same address as the argument.
2586///
2587/// This implementation can be removed once we move to C++20 where it's defined
2588/// as std::to_address().
2589///
2590/// The std::pointer_traits<>::to_address(p) variations of these overloads has
2591/// not been implemented.
2592template <class Ptr> auto to_address(const Ptr &P) { return P.operator->(); }
2593template <class T> constexpr T *to_address(T *P) { return P; }
2594
2595// Detect incomplete types, relying on the fact that their size is unknown.
2596namespace detail {
2597template <typename T> using has_sizeof = decltype(sizeof(T));
2598} // namespace detail
2599
2600/// Detects when type `T` is incomplete. This is true for forward declarations
2601/// and false for types with a full definition.
2602template <typename T>
2604
2605} // end namespace llvm
2606
2607namespace std {
2608template <typename... Refs>
2609struct tuple_size<llvm::detail::enumerator_result<Refs...>>
2610 : std::integral_constant<std::size_t, sizeof...(Refs)> {};
2611
2612template <std::size_t I, typename... Refs>
2613struct tuple_element<I, llvm::detail::enumerator_result<Refs...>>
2614 : std::tuple_element<I, std::tuple<Refs...>> {};
2615
2616template <std::size_t I, typename... Refs>
2617struct tuple_element<I, const llvm::detail::enumerator_result<Refs...>>
2618 : std::tuple_element<I, std::tuple<Refs...>> {};
2619
2620} // namespace std
2621
2622#endif // LLVM_ADT_STLEXTRAS_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
#define R2(n)
#define T
modulo schedule test
nvptx lower args
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
This file contains library features backported from future STL versions.
Value * RHS
Value * LHS
INLINE void g(uint32_t *state, size_t a, size_t b, size_t c, size_t d, uint32_t x, uint32_t y)
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
LLVM Value Representation.
Definition Value.h:75
decltype(auto) operator()(Pn &&...Params) const
Definition STLExtras.h:271
Templated storage wrapper for a callable.
Definition STLExtras.h:182
Callable & operator=(Callable &&Other)
Definition STLExtras.h:206
Callable(Callable const &Other)=default
Callable & operator=(Callable const &Other)
Definition STLExtras.h:199
Callable(Callable &&Other)=default
Iterator wrapper that concatenates sequences together.
Definition STLExtras.h:993
concat_iterator & operator++()
Definition STLExtras.h:1088
bool operator==(const concat_iterator &RHS) const
Definition STLExtras.h:1097
reference_type operator*() const
Definition STLExtras.h:1093
concat_iterator(RangeTs &&...Ranges)
Constructs an iterator from a sequence of ranges.
Definition STLExtras.h:1083
Helper to store a sequence of ranges being concatenated and access them.
Definition STLExtras.h:1109
concat_range(RangeTs &&... Ranges)
Definition STLExtras.h:1135
concat_iterator< ValueT, decltype(adl_begin(std::declval< RangeTs & >()))... > iterator
Definition STLExtras.h:1111
iterator begin() const
Definition STLExtras.h:1141
Return a reference to the first or second member of a reference.
Definition STLExtras.h:1399
std::conditional_t< std::is_reference< EltTy >::value, FirstTy, std::remove_reference_t< FirstTy > > type
Definition STLExtras.h:1401
An iterator element of this range.
Definition STLExtras.h:1230
The class represents the base of a range of indexed_accessor_iterators.
Definition STLExtras.h:1224
DerivedT slice(size_t n, size_t m) const
Drop the first N elements, and keep M elements.
Definition STLExtras.h:1276
size_t size() const
Return the size of this range.
Definition STLExtras.h:1270
bool empty() const
Return if the range is empty.
Definition STLExtras.h:1273
indexed_accessor_range_base & operator=(const indexed_accessor_range_base &)=default
DerivedT take_front(size_t n=1) const
Take the first n elements.
Definition STLExtras.h:1293
ReferenceT operator[](size_t Index) const
Definition STLExtras.h:1256
DerivedT drop_back(size_t n=1) const
Drop the last n elements.
Definition STLExtras.h:1287
indexed_accessor_range_base RangeBaseT
Definition STLExtras.h:1226
DerivedT take_back(size_t n=1) const
Take the last n elements.
Definition STLExtras.h:1299
DerivedT drop_front(size_t n=1) const
Drop the first n elements.
Definition STLExtras.h:1282
indexed_accessor_range_base(const indexed_accessor_range_base &)=default
indexed_accessor_range_base(BaseT base, ptrdiff_t count)
Definition STLExtras.h:1251
indexed_accessor_range_base(indexed_accessor_range_base &&)=default
indexed_accessor_range_base(iterator begin, iterator end)
Definition STLExtras.h:1246
ptrdiff_t count
The size from the owning range.
Definition STLExtras.h:1329
BaseT base
The base that owns the provided range of values.
Definition STLExtras.h:1327
indexed_accessor_range_base(const iterator_range< iterator > &range)
Definition STLExtras.h:1249
const BaseT & getBase() const
Returns the base of this range.
Definition STLExtras.h:1312
zip_longest_iterator(std::pair< Iters &&, Iters && >... ts)
Definition STLExtras.h:918
bool operator==(const zip_longest_iterator< Iters... > &other) const
Definition STLExtras.h:931
zip_longest_iterator< Iters... > & operator++()
Definition STLExtras.h:926
typename ZipLongestTupleType< Iters... >::type value_type
Definition STLExtras.h:893
typename iterator::iterator_category iterator_category
Definition STLExtras.h:940
typename iterator::pointer pointer
Definition STLExtras.h:943
typename iterator::difference_type difference_type
Definition STLExtras.h:942
zip_longest_iterator< decltype(adl_begin(std::declval< Args >()))... > iterator
Definition STLExtras.h:938
typename iterator::reference reference
Definition STLExtras.h:944
zip_longest_range(Args &&... ts_)
Definition STLExtras.h:961
typename iterator::value_type value_type
Definition STLExtras.h:941
typename ZippyIteratorTuple< ItType, decltype(storage), IndexSequence >::type iterator
Definition STLExtras.h:781
typename iterator::value_type value_type
Definition STLExtras.h:787
typename iterator::difference_type difference_type
Definition STLExtras.h:788
typename iterator::reference reference
Definition STLExtras.h:790
typename iterator::pointer pointer
Definition STLExtras.h:789
typename ZippyIteratorTuple< ItType, const decltype(storage), IndexSequence >::type const_iterator
Definition STLExtras.h:783
zippy(Args &&...args)
Definition STLExtras.h:793
typename const_iterator::reference const_reference
Definition STLExtras.h:791
const_iterator begin() const
Definition STLExtras.h:795
typename iterator::iterator_category iterator_category
Definition STLExtras.h:786
const_iterator end() const
Definition STLExtras.h:797
A pseudo-iterator adaptor that is designed to implement "early increment" style loops.
Definition STLExtras.h:572
friend bool operator==(const early_inc_iterator_impl &LHS, const early_inc_iterator_impl &RHS)
Definition STLExtras.h:603
early_inc_iterator_impl(WrappedIteratorT I)
Definition STLExtras.h:583
early_inc_iterator_impl & operator++()
Definition STLExtras.h:595
decltype(*std::declval< WrappedIteratorT >()) operator*()
Definition STLExtras.h:586
An iterator adaptor that filters the elements of given inner iterators.
Definition STLExtras.h:431
filter_iterator_base & operator++()
Definition STLExtras.h:457
WrappedIteratorT End
Definition STLExtras.h:435
filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
Definition STLExtras.h:448
filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
Definition STLExtras.h:505
Specialization of filter_iterator_base for forward iteration only.
Definition STLExtras.h:478
filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
Definition STLExtras.h:482
index_range(std::size_t Begin, std::size_t End)
Definition STLExtras.h:2412
detail::index_iterator begin() const
Definition STLExtras.h:2413
detail::index_iterator end() const
Definition STLExtras.h:2414
A utility class used to implement an iterator that contains some base object and an index.
Definition STLExtras.h:1174
DerivedT & operator+=(ptrdiff_t offset)
Definition STLExtras.h:1189
const BaseT & getBase() const
Returns the current base of the iterator.
Definition STLExtras.h:1202
bool operator==(const indexed_accessor_iterator &rhs) const
Definition STLExtras.h:1180
indexed_accessor_iterator(BaseT base, ptrdiff_t index)
Definition STLExtras.h:1205
DerivedT & operator-=(ptrdiff_t offset)
Definition STLExtras.h:1193
ptrdiff_t operator-(const indexed_accessor_iterator &rhs) const
Definition STLExtras.h:1176
bool operator<(const indexed_accessor_iterator &rhs) const
Definition STLExtras.h:1184
ptrdiff_t getIndex() const
Returns the current index of the iterator.
Definition STLExtras.h:1199
indexed_accessor_range(BaseT base, ptrdiff_t startIndex, ptrdiff_t count)
Definition STLExtras.h:1363
const BaseT & getBase() const
Returns the current base of the range.
Definition STLExtras.h:1372
ptrdiff_t getStartIndex() const
Returns the current start index of the range.
Definition STLExtras.h:1375
static ReferenceT dereference_iterator(const std::pair< BaseT, ptrdiff_t > &base, ptrdiff_t index)
See detail::indexed_accessor_range_base for details.
Definition STLExtras.h:1386
static std::pair< BaseT, ptrdiff_t > offset_base(const std::pair< BaseT, ptrdiff_t > &base, ptrdiff_t index)
See detail::indexed_accessor_range_base for details.
Definition STLExtras.h:1379
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
A range adaptor for a pair of iterators.
mapped_iterator_base BaseT
Definition STLExtras.h:376
ReferenceTy operator*() const
Definition STLExtras.h:383
const FuncTy & getFunction() const
Definition STLExtras.h:342
mapped_iterator(ItTy U, FuncTy F)
Definition STLExtras.h:337
ReferenceTy operator*() const
Definition STLExtras.h:344
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
decltype(adl_rbegin(std::declval< Range & >())) check_has_free_function_rbegin
Definition STLExtras.h:390
auto deref_or_none(const Iter &I, const Iter &End) -> std::optional< std::remove_const_t< std::remove_reference_t< decltype(*I)> > >
Definition STLExtras.h:864
enumerator_result< decltype(*declval< Iters >())... > EnumeratorTupleType
Definition STLExtras.h:2261
bool all_of_zip_predicate_first(Predicate &&P, Args &&...args)
Definition STLExtras.h:2472
const char unit< Period >::value[]
Definition Chrono.h:104
static constexpr bool HasMemberFind
Definition STLExtras.h:1868
static constexpr bool HasFreeFunctionRBegin
Definition STLExtras.h:394
decltype(adl_size(std::declval< Range & >())) check_has_free_function_size
Definition STLExtras.h:1676
bool operator!=(const DenseSetImpl< ValueT, MapTy, ValueInfoT > &LHS, const DenseSetImpl< ValueT, MapTy, ValueInfoT > &RHS)
Inequality comparison for DenseSet.
Definition DenseSet.h:248
static constexpr bool HasMemberContains
Definition STLExtras.h:1859
std::conditional_t< std::is_base_of_v< std::bidirectional_iterator_tag, typename std::iterator_traits< IterT >::iterator_category >, std::bidirectional_iterator_tag, std::forward_iterator_tag > fwd_or_bidi_tag
A type alias which is std::bidirectional_iterator_tag if the category of IterT derives from it,...
Definition STLExtras.h:521
bool all_of_zip_predicate_last(std::tuple< ArgsThenPredicate... > argsThenPredicate, std::index_sequence< InputIndexes... >)
Definition STLExtras.h:2487
decltype(std::declval< Range & >().contains(std::declval< const Element & >())) check_has_member_contains_t
Definition STLExtras.h:1855
decltype(sizeof(T)) has_sizeof
Definition STLExtras.h:2597
decltype(std::declval< Range & >().find(std::declval< const Element & >()) != std::declval< Range & >().end()) check_has_member_find_t
Definition STLExtras.h:1863
Iter next_or_end(const Iter &I, const Iter &End)
Definition STLExtras.h:857
iterator_facade_base< ZipType, std::common_type_t< std::bidirectional_iterator_tag, typename std::iterator_traits< Iters >::iterator_category... >, ReferenceTupleType, typename std::iterator_traits< std::tuple_element_t< 0, std::tuple< Iters... > > >::difference_type, ReferenceTupleType *, ReferenceTupleType > zip_traits
Definition STLExtras.h:655
static constexpr bool HasFreeFunctionSize
Definition STLExtras.h:1680
bool operator==(const DenseSetImpl< ValueT, MapTy, ValueInfoT > &LHS, const DenseSetImpl< ValueT, MapTy, ValueInfoT > &RHS)
Equality comparison for DenseSet.
Definition DenseSet.h:232
std::remove_reference_t< decltype(*adl_begin(std::declval< RangeT & >()))> ValueOfRange
Definition ADL.h:129
std::conjunction< std::is_pointer< T >, std::is_trivially_copyable< typename std::iterator_traits< T >::value_type > > sort_trivially_copyable
Definition STLExtras.h:1624
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:310
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:823
void stable_sort(R &&Range)
Definition STLExtras.h:2040
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1733
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1727
bool includes(R1 &&Range1, R2 &&Range2)
Provide wrappers to std::includes which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1916
auto min_element(R &&Range)
Provide wrappers to std::min_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2002
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1700
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1707
detail::zip_longest_range< T, U, Args... > zip_longest(T &&t, U &&u, Args &&... args)
Iterate over two or more iterators at the same time.
Definition STLExtras.h:974
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1665
int(*)(const void *, const void *) get_array_pod_sort_comparator(const T &)
get_array_pod_sort_comparator - This is an internal helper function used to get type deduction of T r...
Definition STLExtras.h:1555
constexpr bool is_incomplete_v
Detects when type T is incomplete.
Definition STLExtras.h:2603
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:833
constexpr auto adl_begin(RangeT &&range) -> decltype(adl_detail::begin_impl(std::forward< RangeT >(range)))
Returns the begin iterator to range using std::begin and function found through Argument-Dependent Lo...
Definition ADL.h:78
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2454
void interleave(ForwardIterator begin, ForwardIterator end, UnaryFunctor each_fn, NullaryFunctor between_fn)
An STL-style algorithm similar to std::for_each that applies a second functor between every pair of e...
Definition STLExtras.h:2175
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
Definition STLExtras.h:2053
int array_pod_sort_comparator(const void *P1, const void *P2)
Adapt std::less<T> for array_pod_sort.
Definition STLExtras.h:1542
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
mapped_iterator< ItTy, FuncTy > map_iterator(ItTy I, FuncTy F)
Definition STLExtras.h:353
decltype(auto) getSingleElement(ContainerTy &&C)
Asserts that the given container has a single element and returns that element.
Definition STLExtras.h:303
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2118
bool hasNItemsOrLess(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;})
Returns true if the sequence [Begin, End) has N or less items.
Definition STLExtras.h:2559
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2213
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:626
void shuffle(Iterator first, Iterator last, RNG &&g)
Definition STLExtras.h:1526
constexpr auto adl_end(RangeT &&range) -> decltype(adl_detail::end_impl(std::forward< RangeT >(range)))
Returns the end iterator to range using std::end and functions found through Argument-Dependent Looku...
Definition ADL.h:86
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2035
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2058
auto binary_search(R &&Range, T &&Value)
Provide wrappers to std::binary_search which take ranges instead of having to pass begin/end explicit...
Definition STLExtras.h:1963
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:1989
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1759
auto map_range(ContainerTy &&C, FuncTy F)
Definition STLExtras.h:358
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1160
constexpr auto adl_rbegin(RangeT &&range) -> decltype(adl_detail::rbegin_impl(std::forward< RangeT >(range)))
Returns the reverse-begin iterator to range using std::rbegin and function found through Argument-Dep...
Definition ADL.h:94
bool hasNItemsOrMore(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has N or more items.
Definition STLExtras.h:2538
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2110
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:1950
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1714
auto mismatch(R1 &&Range1, R2 &&Range2)
Provide wrappers to std::mismatch which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:2029
auto reverse(ContainerTy &&C)
Definition STLExtras.h:400
constexpr size_t range_size(R &&Range)
Returns the size of the Range, i.e., the number of elements.
Definition STLExtras.h:1690
detail::zippy< detail::zip_first, T, U, Args... > zip_first(T &&t, U &&u, Args &&...args)
zip iterator that, for the sake of efficiency, assumes the first iteratee to be the shortest.
Definition STLExtras.h:846
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1632
bool hasNItems(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has exactly N items.
Definition STLExtras.h:2513
auto find_if_not(R &&Range, UnaryPredicate P)
Definition STLExtras.h:1745
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1721
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1407
constexpr auto adl_size(RangeT &&range) -> decltype(adl_detail::size_impl(std::forward< RangeT >(range)))
Returns the size of range using std::size and functions found through Argument-Dependent Lookup (ADL)...
Definition ADL.h:118
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1902
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
Definition STLExtras.h:294
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:544
std::pair< T *, bool > find_singleton_nested(R &&Range, Predicate P, bool AllowRepeats=false)
Return a pair consisting of the single value in Range that satisfies P(<member of Range> ,...
Definition STLExtras.h:1794
T * find_singleton(R &&Range, Predicate P, bool AllowRepeats=false)
Return the single value in Range that satisfies P(<member of Range> *, AllowRepeats)->T * returning n...
Definition STLExtras.h:1769
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:317
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:71
auto remove_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1752
std::disjunction< std::is_same< T, Ts >... > is_one_of
traits class for checking whether type T is one of any of the given types in the variadic list.
Definition STLExtras.h:109
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:1976
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1842
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:1936
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2012
OutputIt replace_copy_if(R &&Range, OutputIt Out, UnaryPredicate P, const T &NewValue)
Provide wrappers to std::replace_copy_if which take ranges instead of having to pass begin/end explic...
Definition STLExtras.h:1824
auto to_address(const Ptr &P)
Returns a raw pointer that represents the same address as the argument.
Definition STLExtras.h:2592
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1817
auto partition(R &&Range, UnaryPredicate P)
Provide wrappers to std::partition which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1957
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1417
typename detail::detector< void, Op, Args... >::value_t is_detected
Detects if a given trait holds for some set of arguments 'Args'.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1849
OutputIt replace_copy(R &&Range, OutputIt Out, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace_copy which take ranges instead of having to pass begin/end explicitl...
Definition STLExtras.h:1833
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:1943
std::tuple_element_t< I, std::tuple< Ts... > > TypeAtIndex
Find the type at a given index in a list of types.
Definition STLExtras.h:151
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1740
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2102
constexpr auto adl_rend(RangeT &&range) -> decltype(adl_detail::rend_impl(std::forward< RangeT >(range)))
Returns the reverse-end iterator to range using std::rend and functions found through Argument-Depend...
Definition ADL.h:102
void append_values(Container &C, Args &&...Values)
Appends all Values to container C.
Definition STLExtras.h:2124
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1879
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2090
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1592
constexpr decltype(auto) makeVisitor(CallableTs &&...Callables)
Returns an opaquely-typed Callable object whose operator() overload set is the sum of the operator() ...
Definition STLExtras.h:1515
filter_iterator_impl< WrappedIteratorT, PredicateT, detail::fwd_or_bidi_tag< WrappedIteratorT > > filter_iterator
Defines filter_iterator to a suitable specialization of filter_iterator_impl, based on the underlying...
Definition STLExtras.h:531
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2070
std::conjunction< std::is_base_of< T, Ts >... > are_base_of
traits class for checking whether type T is a base class for all the given types in the variadic list...
Definition STLExtras.h:114
bool all_of_zip(ArgsAndPredicate &&...argsAndPredicate)
Compare two zipped ranges using the provided predicate (as last argument).
Definition STLExtras.h:2502
constexpr auto addEnumValues(EnumTy1 LHS, EnumTy2 RHS)
Helper which adds two underlying types of enumeration type.
Definition STLExtras.h:160
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:851
#define N
Find the first index where a type appears in a list of types.
Definition STLExtras.h:140
void operator()(void *v)
Definition STLExtras.h:2228
Determine if all types in Ts are distinct.
Definition STLExtras.h:123
Binary functor that adapts to any other binary functor after dereferencing operands.
Definition STLExtras.h:2242
auto operator()(A &lhs, B &rhs) const
Definition STLExtras.h:2248
constexpr Visitor(HeadT &&Head, TailTs &&...Tail)
Definition STLExtras.h:1472
constexpr Visitor(HeadT &&Head)
Definition STLExtras.h:1480
std::optional< std::remove_const_t< std::remove_reference_t< decltype(*std::declval< Iter >())> > > type
Definition STLExtras.h:872
std::tuple< typename ZipLongestItemType< Iters >::type... > type
Definition STLExtras.h:877
std::tuple< decltype(*declval< Iters >())... > type
Definition STLExtras.h:651
ItType< decltype(adl_begin( std::get< Ns >(declval< const std::tuple< Args... > & >())))... > type
Definition STLExtras.h:771
ItType< decltype(adl_begin( std::get< Ns >(declval< std::tuple< Args... > & >())))... > type
Definition STLExtras.h:762
Helper to obtain the iterator types for the tuple storage within zippy.
Definition STLExtras.h:755
decltype(auto) value() const
Returns the value(s) for the current iterator.
Definition STLExtras.h:2307
friend decltype(auto) get(const enumerator_result &Result)
Returns the value at index I.
Definition STLExtras.h:2323
std::tuple< std::size_t, Refs... > value_reference_tuple
Definition STLExtras.h:2296
friend bool operator==(const enumerator_result &Result, const std::tuple< std::size_t, Ts... > &Other)
Definition STLExtras.h:2331
std::size_t index() const
Returns the 0-based index of the current position within the original input range(s).
Definition STLExtras.h:2303
friend std::size_t get(const enumerator_result &Result)
Returns the value at index I. This case covers the index.
Definition STLExtras.h:2316
enumerator_result(std::size_t Index, Refs &&...Rs)
Definition STLExtras.h:2298
Tuple-like type for zip_enumerator dereference.
Definition STLExtras.h:2258
friend bool operator==(const index_iterator &Lhs, const index_iterator &Rhs)
Definition STLExtras.h:2382
std::ptrdiff_t operator-(const index_iterator &R) const
Definition STLExtras.h:2371
std::size_t operator*() const
Definition STLExtras.h:2380
friend bool operator<(const index_iterator &Lhs, const index_iterator &Rhs)
Definition STLExtras.h:2386
index_iterator & operator-=(std::ptrdiff_t N)
Definition STLExtras.h:2366
index_iterator & operator+=(std::ptrdiff_t N)
Definition STLExtras.h:2361
index_iterator(std::size_t Index)
Definition STLExtras.h:2359
Infinite stream of increasing 0-based size_t indices.
Definition STLExtras.h:2395
index_iterator begin() const
Definition STLExtras.h:2396
index_iterator end() const
Definition STLExtras.h:2397
zip_traits< ZipType, ReferenceTupleType, Iters... > Base
Definition STLExtras.h:672
std::index_sequence_for< Iters... > IndexSequence
Definition STLExtras.h:673
void tup_inc(std::index_sequence< Ns... >)
Definition STLExtras.h:683
zip_common(Iters &&... ts)
Definition STLExtras.h:699
bool test_all_equals(const zip_common &other, std::index_sequence< Ns... >) const
Definition STLExtras.h:692
std::tuple< Iters... > iterators
Definition STLExtras.h:676
value_type operator*() const
Definition STLExtras.h:701
typename Base::value_type value_type
Definition STLExtras.h:674
bool all_equals(zip_common &other)
Return true if all the iterator are matching other's iterators.
Definition STLExtras.h:716
void tup_dec(std::index_sequence< Ns... >)
Definition STLExtras.h:687
value_type deref(std::index_sequence< Ns... >) const
Definition STLExtras.h:679
Zippy iterator that uses the second iterator for comparisons.
Definition STLExtras.h:2276
bool operator==(const zip_enumerator &Other) const
Definition STLExtras.h:2281
bool operator==(const zip_first &other) const
Definition STLExtras.h:727
bool operator==(const zip_shortest &other) const
Definition STLExtras.h:739
std::tuple_element_t< Index, std::tuple< Args... > > arg_t
The type of an argument to this function.
Definition STLExtras.h:79
std::tuple_element_t< i, std::tuple< Args... > > arg_t
The type of an argument to this function.
Definition STLExtras.h:96
ReturnType result_t
The result type of this function.
Definition STLExtras.h:92
This class provides various trait information about a callable object.
Definition STLExtras.h:66
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1435
bool operator()(const T &lhs, const T &rhs) const
Definition STLExtras.h:1436
Function object to check whether the second component of a container supported by std::get (like std:...
Definition STLExtras.h:1444
bool operator()(const T &lhs, const T &rhs) const
Definition STLExtras.h:1445
std::add_pointer_t< std::add_const_t< T > > type
Definition STLExtras.h:54
std::add_lvalue_reference_t< std::add_const_t< T > > type
Definition STLExtras.h:58
Function object to apply a binary function to the first component of a std::pair.
Definition STLExtras.h:1453
size_t operator()(const std::pair< First, Second > &P) const
Definition STLExtras.h:2235
Utility type to build an inheritance chain that makes it easy to rank overload candidates.
Definition STLExtras.h:1464