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