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