10b57cec5SDimitry Andric //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 81fd87a68SDimitry Andric /// 91fd87a68SDimitry Andric /// \file 101fd87a68SDimitry Andric /// This file contains some templates that are useful if you are working with 111fd87a68SDimitry Andric /// the STL at all. 121fd87a68SDimitry Andric /// 131fd87a68SDimitry Andric /// No library is required when using these functions. 141fd87a68SDimitry Andric /// 150b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 160b57cec5SDimitry Andric 170b57cec5SDimitry Andric #ifndef LLVM_ADT_STLEXTRAS_H 180b57cec5SDimitry Andric #define LLVM_ADT_STLEXTRAS_H 190b57cec5SDimitry Andric 2006c3fb27SDimitry Andric #include "llvm/ADT/ADL.h" 21bdd1243dSDimitry Andric #include "llvm/ADT/Hashing.h" 22fe6060f1SDimitry Andric #include "llvm/ADT/STLForwardCompat.h" 2304eeddc0SDimitry Andric #include "llvm/ADT/STLFunctionalExtras.h" 240b57cec5SDimitry Andric #include "llvm/ADT/iterator.h" 250b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h" 260b57cec5SDimitry Andric #include "llvm/Config/abi-breaking.h" 270b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 280b57cec5SDimitry Andric #include <algorithm> 290b57cec5SDimitry Andric #include <cassert> 300b57cec5SDimitry Andric #include <cstddef> 310b57cec5SDimitry Andric #include <cstdint> 320b57cec5SDimitry Andric #include <cstdlib> 330b57cec5SDimitry Andric #include <functional> 340b57cec5SDimitry Andric #include <initializer_list> 350b57cec5SDimitry Andric #include <iterator> 360b57cec5SDimitry Andric #include <limits> 370b57cec5SDimitry Andric #include <memory> 38bdd1243dSDimitry Andric #include <optional> 390b57cec5SDimitry Andric #include <tuple> 400b57cec5SDimitry Andric #include <type_traits> 410b57cec5SDimitry Andric #include <utility> 420b57cec5SDimitry Andric 430b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS 440b57cec5SDimitry Andric #include <random> // for std::mt19937 450b57cec5SDimitry Andric #endif 460b57cec5SDimitry Andric 470b57cec5SDimitry Andric namespace llvm { 480b57cec5SDimitry Andric 490b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 500b57cec5SDimitry Andric // Extra additions to <type_traits> 510b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 520b57cec5SDimitry Andric 530b57cec5SDimitry Andric template <typename T> struct make_const_ptr { 54bdd1243dSDimitry Andric using type = std::add_pointer_t<std::add_const_t<T>>; 550b57cec5SDimitry Andric }; 560b57cec5SDimitry Andric 570b57cec5SDimitry Andric template <typename T> struct make_const_ref { 58bdd1243dSDimitry Andric using type = std::add_lvalue_reference_t<std::add_const_t<T>>; 590b57cec5SDimitry Andric }; 600b57cec5SDimitry Andric 615ffd83dbSDimitry Andric namespace detail { 625ffd83dbSDimitry Andric template <class, template <class...> class Op, class... Args> struct detector { 635ffd83dbSDimitry Andric using value_t = std::false_type; 645ffd83dbSDimitry Andric }; 655ffd83dbSDimitry Andric template <template <class...> class Op, class... Args> 66bdd1243dSDimitry Andric struct detector<std::void_t<Op<Args...>>, Op, Args...> { 675ffd83dbSDimitry Andric using value_t = std::true_type; 685ffd83dbSDimitry Andric }; 695ffd83dbSDimitry Andric } // end namespace detail 705ffd83dbSDimitry Andric 71fe6060f1SDimitry Andric /// Detects if a given trait holds for some set of arguments 'Args'. 72fe6060f1SDimitry Andric /// For example, the given trait could be used to detect if a given type 73fe6060f1SDimitry Andric /// has a copy assignment operator: 74fe6060f1SDimitry Andric /// template<class T> 75fe6060f1SDimitry Andric /// using has_copy_assign_t = decltype(std::declval<T&>() 76fe6060f1SDimitry Andric /// = std::declval<const T&>()); 77fe6060f1SDimitry Andric /// bool fooHasCopyAssign = is_detected<has_copy_assign_t, FooClass>::value; 785ffd83dbSDimitry Andric template <template <class...> class Op, class... Args> 795ffd83dbSDimitry Andric using is_detected = typename detail::detector<void, Op, Args...>::value_t; 805ffd83dbSDimitry Andric 815ffd83dbSDimitry Andric /// This class provides various trait information about a callable object. 825ffd83dbSDimitry Andric /// * To access the number of arguments: Traits::num_args 835ffd83dbSDimitry Andric /// * To access the type of an argument: Traits::arg_t<Index> 845ffd83dbSDimitry Andric /// * To access the type of the result: Traits::result_t 855ffd83dbSDimitry Andric template <typename T, bool isClass = std::is_class<T>::value> 865ffd83dbSDimitry Andric struct function_traits : public function_traits<decltype(&T::operator())> {}; 875ffd83dbSDimitry Andric 885ffd83dbSDimitry Andric /// Overload for class function types. 895ffd83dbSDimitry Andric template <typename ClassType, typename ReturnType, typename... Args> 905ffd83dbSDimitry Andric struct function_traits<ReturnType (ClassType::*)(Args...) const, false> { 915ffd83dbSDimitry Andric /// The number of arguments to this function. 925ffd83dbSDimitry Andric enum { num_args = sizeof...(Args) }; 935ffd83dbSDimitry Andric 945ffd83dbSDimitry Andric /// The result type of this function. 955ffd83dbSDimitry Andric using result_t = ReturnType; 965ffd83dbSDimitry Andric 975ffd83dbSDimitry Andric /// The type of an argument to this function. 985ffd83dbSDimitry Andric template <size_t Index> 99bdd1243dSDimitry Andric using arg_t = std::tuple_element_t<Index, std::tuple<Args...>>; 1005ffd83dbSDimitry Andric }; 1015ffd83dbSDimitry Andric /// Overload for class function types. 1025ffd83dbSDimitry Andric template <typename ClassType, typename ReturnType, typename... Args> 1035ffd83dbSDimitry Andric struct function_traits<ReturnType (ClassType::*)(Args...), false> 10481ad6265SDimitry Andric : public function_traits<ReturnType (ClassType::*)(Args...) const> {}; 1055ffd83dbSDimitry Andric /// Overload for non-class function types. 1065ffd83dbSDimitry Andric template <typename ReturnType, typename... Args> 1075ffd83dbSDimitry Andric struct function_traits<ReturnType (*)(Args...), false> { 1085ffd83dbSDimitry Andric /// The number of arguments to this function. 1095ffd83dbSDimitry Andric enum { num_args = sizeof...(Args) }; 1105ffd83dbSDimitry Andric 1115ffd83dbSDimitry Andric /// The result type of this function. 1125ffd83dbSDimitry Andric using result_t = ReturnType; 1135ffd83dbSDimitry Andric 1145ffd83dbSDimitry Andric /// The type of an argument to this function. 1155ffd83dbSDimitry Andric template <size_t i> 116bdd1243dSDimitry Andric using arg_t = std::tuple_element_t<i, std::tuple<Args...>>; 1175ffd83dbSDimitry Andric }; 11881ad6265SDimitry Andric template <typename ReturnType, typename... Args> 11981ad6265SDimitry Andric struct function_traits<ReturnType (*const)(Args...), false> 12081ad6265SDimitry Andric : public function_traits<ReturnType (*)(Args...)> {}; 1215ffd83dbSDimitry Andric /// Overload for non-class function type references. 1225ffd83dbSDimitry Andric template <typename ReturnType, typename... Args> 1235ffd83dbSDimitry Andric struct function_traits<ReturnType (&)(Args...), false> 1245ffd83dbSDimitry Andric : public function_traits<ReturnType (*)(Args...)> {}; 1255ffd83dbSDimitry Andric 1260eae32dcSDimitry Andric /// traits class for checking whether type T is one of any of the given 1270eae32dcSDimitry Andric /// types in the variadic list. 1280eae32dcSDimitry Andric template <typename T, typename... Ts> 129bdd1243dSDimitry Andric using is_one_of = std::disjunction<std::is_same<T, Ts>...>; 1300eae32dcSDimitry Andric 1310eae32dcSDimitry Andric /// traits class for checking whether type T is a base class for all 1320eae32dcSDimitry Andric /// the given types in the variadic list. 1330eae32dcSDimitry Andric template <typename T, typename... Ts> 134bdd1243dSDimitry Andric using are_base_of = std::conjunction<std::is_base_of<T, Ts>...>; 1350eae32dcSDimitry Andric 1360eae32dcSDimitry Andric namespace detail { 1370eae32dcSDimitry Andric template <typename T, typename... Us> struct TypesAreDistinct; 1380eae32dcSDimitry Andric template <typename T, typename... Us> 1390eae32dcSDimitry Andric struct TypesAreDistinct 1400eae32dcSDimitry Andric : std::integral_constant<bool, !is_one_of<T, Us...>::value && 1410eae32dcSDimitry Andric TypesAreDistinct<Us...>::value> {}; 1420eae32dcSDimitry Andric template <typename T> struct TypesAreDistinct<T> : std::true_type {}; 1430eae32dcSDimitry Andric } // namespace detail 1440eae32dcSDimitry Andric 1450eae32dcSDimitry Andric /// Determine if all types in Ts are distinct. 1460eae32dcSDimitry Andric /// 1470eae32dcSDimitry Andric /// Useful to statically assert when Ts is intended to describe a non-multi set 1480eae32dcSDimitry Andric /// of types. 1490eae32dcSDimitry Andric /// 1500eae32dcSDimitry Andric /// Expensive (currently quadratic in sizeof(Ts...)), and so should only be 1510eae32dcSDimitry Andric /// asserted once per instantiation of a type which requires it. 1520eae32dcSDimitry Andric template <typename... Ts> struct TypesAreDistinct; 1530eae32dcSDimitry Andric template <> struct TypesAreDistinct<> : std::true_type {}; 1540eae32dcSDimitry Andric template <typename... Ts> 1550eae32dcSDimitry Andric struct TypesAreDistinct 1560eae32dcSDimitry Andric : std::integral_constant<bool, detail::TypesAreDistinct<Ts...>::value> {}; 1570eae32dcSDimitry Andric 1580eae32dcSDimitry Andric /// Find the first index where a type appears in a list of types. 1590eae32dcSDimitry Andric /// 1600eae32dcSDimitry Andric /// FirstIndexOfType<T, Us...>::value is the first index of T in Us. 1610eae32dcSDimitry Andric /// 1620eae32dcSDimitry Andric /// Typically only meaningful when it is otherwise statically known that the 1630eae32dcSDimitry Andric /// type pack has no duplicate types. This should be guaranteed explicitly with 1640eae32dcSDimitry Andric /// static_assert(TypesAreDistinct<Us...>::value). 1650eae32dcSDimitry Andric /// 1660eae32dcSDimitry Andric /// It is a compile-time error to instantiate when T is not present in Us, i.e. 1670eae32dcSDimitry Andric /// if is_one_of<T, Us...>::value is false. 1680eae32dcSDimitry Andric template <typename T, typename... Us> struct FirstIndexOfType; 1690eae32dcSDimitry Andric template <typename T, typename U, typename... Us> 1700eae32dcSDimitry Andric struct FirstIndexOfType<T, U, Us...> 1710eae32dcSDimitry Andric : std::integral_constant<size_t, 1 + FirstIndexOfType<T, Us...>::value> {}; 1720eae32dcSDimitry Andric template <typename T, typename... Us> 1730eae32dcSDimitry Andric struct FirstIndexOfType<T, T, Us...> : std::integral_constant<size_t, 0> {}; 1740eae32dcSDimitry Andric 1750eae32dcSDimitry Andric /// Find the type at a given index in a list of types. 1760eae32dcSDimitry Andric /// 1770eae32dcSDimitry Andric /// TypeAtIndex<I, Ts...> is the type at index I in Ts. 1780eae32dcSDimitry Andric template <size_t I, typename... Ts> 1790eae32dcSDimitry Andric using TypeAtIndex = std::tuple_element_t<I, std::tuple<Ts...>>; 1800eae32dcSDimitry Andric 18181ad6265SDimitry Andric /// Helper which adds two underlying types of enumeration type. 18281ad6265SDimitry Andric /// Implicit conversion to a common type is accepted. 18381ad6265SDimitry Andric template <typename EnumTy1, typename EnumTy2, 18481ad6265SDimitry Andric typename UT1 = std::enable_if_t<std::is_enum<EnumTy1>::value, 18581ad6265SDimitry Andric std::underlying_type_t<EnumTy1>>, 18681ad6265SDimitry Andric typename UT2 = std::enable_if_t<std::is_enum<EnumTy2>::value, 18781ad6265SDimitry Andric std::underlying_type_t<EnumTy2>>> 18881ad6265SDimitry Andric constexpr auto addEnumValues(EnumTy1 LHS, EnumTy2 RHS) { 18981ad6265SDimitry Andric return static_cast<UT1>(LHS) + static_cast<UT2>(RHS); 19081ad6265SDimitry Andric } 19181ad6265SDimitry Andric 1920b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 1930b57cec5SDimitry Andric // Extra additions to <iterator> 1940b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 1950b57cec5SDimitry Andric 196bdd1243dSDimitry Andric namespace callable_detail { 197bdd1243dSDimitry Andric 198bdd1243dSDimitry Andric /// Templated storage wrapper for a callable. 199bdd1243dSDimitry Andric /// 200bdd1243dSDimitry Andric /// This class is consistently default constructible, copy / move 201bdd1243dSDimitry Andric /// constructible / assignable. 202bdd1243dSDimitry Andric /// 203bdd1243dSDimitry Andric /// Supported callable types: 204bdd1243dSDimitry Andric /// - Function pointer 205bdd1243dSDimitry Andric /// - Function reference 206bdd1243dSDimitry Andric /// - Lambda 207bdd1243dSDimitry Andric /// - Function object 208bdd1243dSDimitry Andric template <typename T, 209bdd1243dSDimitry Andric bool = std::is_function_v<std::remove_pointer_t<remove_cvref_t<T>>>> 210bdd1243dSDimitry Andric class Callable { 211bdd1243dSDimitry Andric using value_type = std::remove_reference_t<T>; 212bdd1243dSDimitry Andric using reference = value_type &; 213bdd1243dSDimitry Andric using const_reference = value_type const &; 214bdd1243dSDimitry Andric 215bdd1243dSDimitry Andric std::optional<value_type> Obj; 216bdd1243dSDimitry Andric 217bdd1243dSDimitry Andric static_assert(!std::is_pointer_v<value_type>, 218bdd1243dSDimitry Andric "Pointers to non-functions are not callable."); 219bdd1243dSDimitry Andric 220bdd1243dSDimitry Andric public: 221bdd1243dSDimitry Andric Callable() = default; 222bdd1243dSDimitry Andric Callable(T const &O) : Obj(std::in_place, O) {} 223bdd1243dSDimitry Andric 224bdd1243dSDimitry Andric Callable(Callable const &Other) = default; 225bdd1243dSDimitry Andric Callable(Callable &&Other) = default; 226bdd1243dSDimitry Andric 227bdd1243dSDimitry Andric Callable &operator=(Callable const &Other) { 228bdd1243dSDimitry Andric Obj = std::nullopt; 229bdd1243dSDimitry Andric if (Other.Obj) 230bdd1243dSDimitry Andric Obj.emplace(*Other.Obj); 231bdd1243dSDimitry Andric return *this; 232bdd1243dSDimitry Andric } 233bdd1243dSDimitry Andric 234bdd1243dSDimitry Andric Callable &operator=(Callable &&Other) { 235bdd1243dSDimitry Andric Obj = std::nullopt; 236bdd1243dSDimitry Andric if (Other.Obj) 237bdd1243dSDimitry Andric Obj.emplace(std::move(*Other.Obj)); 238bdd1243dSDimitry Andric return *this; 239bdd1243dSDimitry Andric } 240bdd1243dSDimitry Andric 241bdd1243dSDimitry Andric template <typename... Pn, 242bdd1243dSDimitry Andric std::enable_if_t<std::is_invocable_v<T, Pn...>, int> = 0> 243bdd1243dSDimitry Andric decltype(auto) operator()(Pn &&...Params) { 244bdd1243dSDimitry Andric return (*Obj)(std::forward<Pn>(Params)...); 245bdd1243dSDimitry Andric } 246bdd1243dSDimitry Andric 247bdd1243dSDimitry Andric template <typename... Pn, 248bdd1243dSDimitry Andric std::enable_if_t<std::is_invocable_v<T const, Pn...>, int> = 0> 249bdd1243dSDimitry Andric decltype(auto) operator()(Pn &&...Params) const { 250bdd1243dSDimitry Andric return (*Obj)(std::forward<Pn>(Params)...); 251bdd1243dSDimitry Andric } 252bdd1243dSDimitry Andric 253bdd1243dSDimitry Andric bool valid() const { return Obj != std::nullopt; } 254bdd1243dSDimitry Andric bool reset() { return Obj = std::nullopt; } 255bdd1243dSDimitry Andric 256bdd1243dSDimitry Andric operator reference() { return *Obj; } 257bdd1243dSDimitry Andric operator const_reference() const { return *Obj; } 258bdd1243dSDimitry Andric }; 259bdd1243dSDimitry Andric 260bdd1243dSDimitry Andric // Function specialization. No need to waste extra space wrapping with a 261bdd1243dSDimitry Andric // std::optional. 262bdd1243dSDimitry Andric template <typename T> class Callable<T, true> { 263bdd1243dSDimitry Andric static constexpr bool IsPtr = std::is_pointer_v<remove_cvref_t<T>>; 264bdd1243dSDimitry Andric 265bdd1243dSDimitry Andric using StorageT = std::conditional_t<IsPtr, T, std::remove_reference_t<T> *>; 266bdd1243dSDimitry Andric using CastT = std::conditional_t<IsPtr, T, T &>; 267bdd1243dSDimitry Andric 268bdd1243dSDimitry Andric private: 269bdd1243dSDimitry Andric StorageT Func = nullptr; 270bdd1243dSDimitry Andric 271bdd1243dSDimitry Andric private: 272bdd1243dSDimitry Andric template <typename In> static constexpr auto convertIn(In &&I) { 273bdd1243dSDimitry Andric if constexpr (IsPtr) { 274bdd1243dSDimitry Andric // Pointer... just echo it back. 275bdd1243dSDimitry Andric return I; 276bdd1243dSDimitry Andric } else { 277bdd1243dSDimitry Andric // Must be a function reference. Return its address. 278bdd1243dSDimitry Andric return &I; 279bdd1243dSDimitry Andric } 280bdd1243dSDimitry Andric } 281bdd1243dSDimitry Andric 282bdd1243dSDimitry Andric public: 283bdd1243dSDimitry Andric Callable() = default; 284bdd1243dSDimitry Andric 285bdd1243dSDimitry Andric // Construct from a function pointer or reference. 286bdd1243dSDimitry Andric // 287bdd1243dSDimitry Andric // Disable this constructor for references to 'Callable' so we don't violate 288bdd1243dSDimitry Andric // the rule of 0. 289bdd1243dSDimitry Andric template < // clang-format off 290bdd1243dSDimitry Andric typename FnPtrOrRef, 291bdd1243dSDimitry Andric std::enable_if_t< 292bdd1243dSDimitry Andric !std::is_same_v<remove_cvref_t<FnPtrOrRef>, Callable>, int 293bdd1243dSDimitry Andric > = 0 294bdd1243dSDimitry Andric > // clang-format on 295bdd1243dSDimitry Andric Callable(FnPtrOrRef &&F) : Func(convertIn(F)) {} 296bdd1243dSDimitry Andric 297bdd1243dSDimitry Andric template <typename... Pn, 298bdd1243dSDimitry Andric std::enable_if_t<std::is_invocable_v<T, Pn...>, int> = 0> 299bdd1243dSDimitry Andric decltype(auto) operator()(Pn &&...Params) const { 300bdd1243dSDimitry Andric return Func(std::forward<Pn>(Params)...); 301bdd1243dSDimitry Andric } 302bdd1243dSDimitry Andric 303bdd1243dSDimitry Andric bool valid() const { return Func != nullptr; } 304bdd1243dSDimitry Andric void reset() { Func = nullptr; } 305bdd1243dSDimitry Andric 306bdd1243dSDimitry Andric operator T const &() const { 307bdd1243dSDimitry Andric if constexpr (IsPtr) { 308bdd1243dSDimitry Andric // T is a pointer... just echo it back. 309bdd1243dSDimitry Andric return Func; 310bdd1243dSDimitry Andric } else { 311bdd1243dSDimitry Andric static_assert(std::is_reference_v<T>, 312bdd1243dSDimitry Andric "Expected a reference to a function."); 313bdd1243dSDimitry Andric // T is a function reference... dereference the stored pointer. 314bdd1243dSDimitry Andric return *Func; 315bdd1243dSDimitry Andric } 316bdd1243dSDimitry Andric } 317bdd1243dSDimitry Andric }; 318bdd1243dSDimitry Andric 319bdd1243dSDimitry Andric } // namespace callable_detail 320bdd1243dSDimitry Andric 3215ffd83dbSDimitry Andric /// Returns true if the given container only contains a single element. 3225ffd83dbSDimitry Andric template <typename ContainerTy> bool hasSingleElement(ContainerTy &&C) { 3235ffd83dbSDimitry Andric auto B = std::begin(C), E = std::end(C); 3245ffd83dbSDimitry Andric return B != E && std::next(B) == E; 3255ffd83dbSDimitry Andric } 3265ffd83dbSDimitry Andric 327480093f4SDimitry Andric /// Return a range covering \p RangeOrContainer with the first N elements 328480093f4SDimitry Andric /// excluded. 329e8d8bef9SDimitry Andric template <typename T> auto drop_begin(T &&RangeOrContainer, size_t N = 1) { 330480093f4SDimitry Andric return make_range(std::next(adl_begin(RangeOrContainer), N), 331480093f4SDimitry Andric adl_end(RangeOrContainer)); 332480093f4SDimitry Andric } 333480093f4SDimitry Andric 33481ad6265SDimitry Andric /// Return a range covering \p RangeOrContainer with the last N elements 33581ad6265SDimitry Andric /// excluded. 33681ad6265SDimitry Andric template <typename T> auto drop_end(T &&RangeOrContainer, size_t N = 1) { 33781ad6265SDimitry Andric return make_range(adl_begin(RangeOrContainer), 33881ad6265SDimitry Andric std::prev(adl_end(RangeOrContainer), N)); 33981ad6265SDimitry Andric } 34081ad6265SDimitry Andric 3410b57cec5SDimitry Andric // mapped_iterator - This is a simple iterator adapter that causes a function to 3420b57cec5SDimitry Andric // be applied whenever operator* is invoked on the iterator. 3430b57cec5SDimitry Andric 3440b57cec5SDimitry Andric template <typename ItTy, typename FuncTy, 345349cc55cSDimitry Andric typename ReferenceTy = 3460b57cec5SDimitry Andric decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))> 3470b57cec5SDimitry Andric class mapped_iterator 3480b57cec5SDimitry Andric : public iterator_adaptor_base< 3490b57cec5SDimitry Andric mapped_iterator<ItTy, FuncTy>, ItTy, 3500b57cec5SDimitry Andric typename std::iterator_traits<ItTy>::iterator_category, 351349cc55cSDimitry Andric std::remove_reference_t<ReferenceTy>, 352349cc55cSDimitry Andric typename std::iterator_traits<ItTy>::difference_type, 353349cc55cSDimitry Andric std::remove_reference_t<ReferenceTy> *, ReferenceTy> { 3540b57cec5SDimitry Andric public: 355bdd1243dSDimitry Andric mapped_iterator() = default; 3560b57cec5SDimitry Andric mapped_iterator(ItTy U, FuncTy F) 3570b57cec5SDimitry Andric : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {} 3580b57cec5SDimitry Andric 3590b57cec5SDimitry Andric ItTy getCurrent() { return this->I; } 3600b57cec5SDimitry Andric 361349cc55cSDimitry Andric const FuncTy &getFunction() const { return F; } 362349cc55cSDimitry Andric 363349cc55cSDimitry Andric ReferenceTy operator*() const { return F(*this->I); } 3640b57cec5SDimitry Andric 3650b57cec5SDimitry Andric private: 366bdd1243dSDimitry Andric callable_detail::Callable<FuncTy> F{}; 3670b57cec5SDimitry Andric }; 3680b57cec5SDimitry Andric 3690b57cec5SDimitry Andric // map_iterator - Provide a convenient way to create mapped_iterators, just like 3700b57cec5SDimitry Andric // make_pair is useful for creating pairs... 3710b57cec5SDimitry Andric template <class ItTy, class FuncTy> 3720b57cec5SDimitry Andric inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) { 3730b57cec5SDimitry Andric return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F)); 3740b57cec5SDimitry Andric } 3750b57cec5SDimitry Andric 3760b57cec5SDimitry Andric template <class ContainerTy, class FuncTy> 3775ffd83dbSDimitry Andric auto map_range(ContainerTy &&C, FuncTy F) { 37806c3fb27SDimitry Andric return make_range(map_iterator(std::begin(C), F), 37906c3fb27SDimitry Andric map_iterator(std::end(C), F)); 3800b57cec5SDimitry Andric } 3810b57cec5SDimitry Andric 382349cc55cSDimitry Andric /// A base type of mapped iterator, that is useful for building derived 383349cc55cSDimitry Andric /// iterators that do not need/want to store the map function (as in 384349cc55cSDimitry Andric /// mapped_iterator). These iterators must simply provide a `mapElement` method 385349cc55cSDimitry Andric /// that defines how to map a value of the iterator to the provided reference 386349cc55cSDimitry Andric /// type. 387349cc55cSDimitry Andric template <typename DerivedT, typename ItTy, typename ReferenceTy> 388349cc55cSDimitry Andric class mapped_iterator_base 389349cc55cSDimitry Andric : public iterator_adaptor_base< 390349cc55cSDimitry Andric DerivedT, ItTy, 391349cc55cSDimitry Andric typename std::iterator_traits<ItTy>::iterator_category, 392349cc55cSDimitry Andric std::remove_reference_t<ReferenceTy>, 393349cc55cSDimitry Andric typename std::iterator_traits<ItTy>::difference_type, 394349cc55cSDimitry Andric std::remove_reference_t<ReferenceTy> *, ReferenceTy> { 395349cc55cSDimitry Andric public: 396349cc55cSDimitry Andric using BaseT = mapped_iterator_base; 397349cc55cSDimitry Andric 398349cc55cSDimitry Andric mapped_iterator_base(ItTy U) 399349cc55cSDimitry Andric : mapped_iterator_base::iterator_adaptor_base(std::move(U)) {} 400349cc55cSDimitry Andric 401349cc55cSDimitry Andric ItTy getCurrent() { return this->I; } 402349cc55cSDimitry Andric 403349cc55cSDimitry Andric ReferenceTy operator*() const { 404349cc55cSDimitry Andric return static_cast<const DerivedT &>(*this).mapElement(*this->I); 405349cc55cSDimitry Andric } 406349cc55cSDimitry Andric }; 407349cc55cSDimitry Andric 4080b57cec5SDimitry Andric /// Helper to determine if type T has a member called rbegin(). 4090b57cec5SDimitry Andric template <typename Ty> class has_rbegin_impl { 4100b57cec5SDimitry Andric using yes = char[1]; 4110b57cec5SDimitry Andric using no = char[2]; 4120b57cec5SDimitry Andric 4130b57cec5SDimitry Andric template <typename Inner> 4140b57cec5SDimitry Andric static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr); 4150b57cec5SDimitry Andric 4160b57cec5SDimitry Andric template <typename> 4170b57cec5SDimitry Andric static no& test(...); 4180b57cec5SDimitry Andric 4190b57cec5SDimitry Andric public: 4200b57cec5SDimitry Andric static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes); 4210b57cec5SDimitry Andric }; 4220b57cec5SDimitry Andric 4230b57cec5SDimitry Andric /// Metafunction to determine if T& or T has a member called rbegin(). 4240b57cec5SDimitry Andric template <typename Ty> 425bdd1243dSDimitry Andric struct has_rbegin : has_rbegin_impl<std::remove_reference_t<Ty>> {}; 4260b57cec5SDimitry Andric 4270b57cec5SDimitry Andric // Returns an iterator_range over the given container which iterates in reverse. 428bdd1243dSDimitry Andric template <typename ContainerTy> auto reverse(ContainerTy &&C) { 429bdd1243dSDimitry Andric if constexpr (has_rbegin<ContainerTy>::value) 4300b57cec5SDimitry Andric return make_range(C.rbegin(), C.rend()); 431bdd1243dSDimitry Andric else 43204eeddc0SDimitry Andric return make_range(std::make_reverse_iterator(std::end(C)), 43304eeddc0SDimitry Andric std::make_reverse_iterator(std::begin(C))); 4340b57cec5SDimitry Andric } 4350b57cec5SDimitry Andric 4360b57cec5SDimitry Andric /// An iterator adaptor that filters the elements of given inner iterators. 4370b57cec5SDimitry Andric /// 4380b57cec5SDimitry Andric /// The predicate parameter should be a callable object that accepts the wrapped 4390b57cec5SDimitry Andric /// iterator's reference type and returns a bool. When incrementing or 4400b57cec5SDimitry Andric /// decrementing the iterator, it will call the predicate on each element and 4410b57cec5SDimitry Andric /// skip any where it returns false. 4420b57cec5SDimitry Andric /// 4430b57cec5SDimitry Andric /// \code 4440b57cec5SDimitry Andric /// int A[] = { 1, 2, 3, 4 }; 4450b57cec5SDimitry Andric /// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; }); 4460b57cec5SDimitry Andric /// // R contains { 1, 3 }. 4470b57cec5SDimitry Andric /// \endcode 4480b57cec5SDimitry Andric /// 4490b57cec5SDimitry Andric /// Note: filter_iterator_base implements support for forward iteration. 4500b57cec5SDimitry Andric /// filter_iterator_impl exists to provide support for bidirectional iteration, 4510b57cec5SDimitry Andric /// conditional on whether the wrapped iterator supports it. 4520b57cec5SDimitry Andric template <typename WrappedIteratorT, typename PredicateT, typename IterTag> 4530b57cec5SDimitry Andric class filter_iterator_base 4540b57cec5SDimitry Andric : public iterator_adaptor_base< 4550b57cec5SDimitry Andric filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>, 4560b57cec5SDimitry Andric WrappedIteratorT, 457bdd1243dSDimitry Andric std::common_type_t<IterTag, 458bdd1243dSDimitry Andric typename std::iterator_traits< 459bdd1243dSDimitry Andric WrappedIteratorT>::iterator_category>> { 460349cc55cSDimitry Andric using BaseT = typename filter_iterator_base::iterator_adaptor_base; 4610b57cec5SDimitry Andric 4620b57cec5SDimitry Andric protected: 4630b57cec5SDimitry Andric WrappedIteratorT End; 4640b57cec5SDimitry Andric PredicateT Pred; 4650b57cec5SDimitry Andric 4660b57cec5SDimitry Andric void findNextValid() { 4670b57cec5SDimitry Andric while (this->I != End && !Pred(*this->I)) 4680b57cec5SDimitry Andric BaseT::operator++(); 4690b57cec5SDimitry Andric } 4700b57cec5SDimitry Andric 471bdd1243dSDimitry Andric filter_iterator_base() = default; 472bdd1243dSDimitry Andric 4730b57cec5SDimitry Andric // Construct the iterator. The begin iterator needs to know where the end 4740b57cec5SDimitry Andric // is, so that it can properly stop when it gets there. The end iterator only 4750b57cec5SDimitry Andric // needs the predicate to support bidirectional iteration. 4760b57cec5SDimitry Andric filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End, 4770b57cec5SDimitry Andric PredicateT Pred) 4780b57cec5SDimitry Andric : BaseT(Begin), End(End), Pred(Pred) { 4790b57cec5SDimitry Andric findNextValid(); 4800b57cec5SDimitry Andric } 4810b57cec5SDimitry Andric 4820b57cec5SDimitry Andric public: 4830b57cec5SDimitry Andric using BaseT::operator++; 4840b57cec5SDimitry Andric 4850b57cec5SDimitry Andric filter_iterator_base &operator++() { 4860b57cec5SDimitry Andric BaseT::operator++(); 4870b57cec5SDimitry Andric findNextValid(); 4880b57cec5SDimitry Andric return *this; 4890b57cec5SDimitry Andric } 49081ad6265SDimitry Andric 49181ad6265SDimitry Andric decltype(auto) operator*() const { 49281ad6265SDimitry Andric assert(BaseT::wrapped() != End && "Cannot dereference end iterator!"); 49381ad6265SDimitry Andric return BaseT::operator*(); 49481ad6265SDimitry Andric } 49581ad6265SDimitry Andric 49681ad6265SDimitry Andric decltype(auto) operator->() const { 49781ad6265SDimitry Andric assert(BaseT::wrapped() != End && "Cannot dereference end iterator!"); 49881ad6265SDimitry Andric return BaseT::operator->(); 49981ad6265SDimitry Andric } 5000b57cec5SDimitry Andric }; 5010b57cec5SDimitry Andric 5020b57cec5SDimitry Andric /// Specialization of filter_iterator_base for forward iteration only. 5030b57cec5SDimitry Andric template <typename WrappedIteratorT, typename PredicateT, 5040b57cec5SDimitry Andric typename IterTag = std::forward_iterator_tag> 5050b57cec5SDimitry Andric class filter_iterator_impl 5060b57cec5SDimitry Andric : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> { 5070b57cec5SDimitry Andric public: 508bdd1243dSDimitry Andric filter_iterator_impl() = default; 509bdd1243dSDimitry Andric 5100b57cec5SDimitry Andric filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, 5110b57cec5SDimitry Andric PredicateT Pred) 512349cc55cSDimitry Andric : filter_iterator_impl::filter_iterator_base(Begin, End, Pred) {} 5130b57cec5SDimitry Andric }; 5140b57cec5SDimitry Andric 5150b57cec5SDimitry Andric /// Specialization of filter_iterator_base for bidirectional iteration. 5160b57cec5SDimitry Andric template <typename WrappedIteratorT, typename PredicateT> 5170b57cec5SDimitry Andric class filter_iterator_impl<WrappedIteratorT, PredicateT, 5180b57cec5SDimitry Andric std::bidirectional_iterator_tag> 5190b57cec5SDimitry Andric : public filter_iterator_base<WrappedIteratorT, PredicateT, 5200b57cec5SDimitry Andric std::bidirectional_iterator_tag> { 521349cc55cSDimitry Andric using BaseT = typename filter_iterator_impl::filter_iterator_base; 522349cc55cSDimitry Andric 5230b57cec5SDimitry Andric void findPrevValid() { 5240b57cec5SDimitry Andric while (!this->Pred(*this->I)) 5250b57cec5SDimitry Andric BaseT::operator--(); 5260b57cec5SDimitry Andric } 5270b57cec5SDimitry Andric 5280b57cec5SDimitry Andric public: 5290b57cec5SDimitry Andric using BaseT::operator--; 5300b57cec5SDimitry Andric 531bdd1243dSDimitry Andric filter_iterator_impl() = default; 532bdd1243dSDimitry Andric 5330b57cec5SDimitry Andric filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, 5340b57cec5SDimitry Andric PredicateT Pred) 5350b57cec5SDimitry Andric : BaseT(Begin, End, Pred) {} 5360b57cec5SDimitry Andric 5370b57cec5SDimitry Andric filter_iterator_impl &operator--() { 5380b57cec5SDimitry Andric BaseT::operator--(); 5390b57cec5SDimitry Andric findPrevValid(); 5400b57cec5SDimitry Andric return *this; 5410b57cec5SDimitry Andric } 5420b57cec5SDimitry Andric }; 5430b57cec5SDimitry Andric 5440b57cec5SDimitry Andric namespace detail { 5450b57cec5SDimitry Andric 5460b57cec5SDimitry Andric template <bool is_bidirectional> struct fwd_or_bidi_tag_impl { 5470b57cec5SDimitry Andric using type = std::forward_iterator_tag; 5480b57cec5SDimitry Andric }; 5490b57cec5SDimitry Andric 5500b57cec5SDimitry Andric template <> struct fwd_or_bidi_tag_impl<true> { 5510b57cec5SDimitry Andric using type = std::bidirectional_iterator_tag; 5520b57cec5SDimitry Andric }; 5530b57cec5SDimitry Andric 5540b57cec5SDimitry Andric /// Helper which sets its type member to forward_iterator_tag if the category 5550b57cec5SDimitry Andric /// of \p IterT does not derive from bidirectional_iterator_tag, and to 5560b57cec5SDimitry Andric /// bidirectional_iterator_tag otherwise. 5570b57cec5SDimitry Andric template <typename IterT> struct fwd_or_bidi_tag { 5580b57cec5SDimitry Andric using type = typename fwd_or_bidi_tag_impl<std::is_base_of< 5590b57cec5SDimitry Andric std::bidirectional_iterator_tag, 5600b57cec5SDimitry Andric typename std::iterator_traits<IterT>::iterator_category>::value>::type; 5610b57cec5SDimitry Andric }; 5620b57cec5SDimitry Andric 5630b57cec5SDimitry Andric } // namespace detail 5640b57cec5SDimitry Andric 5650b57cec5SDimitry Andric /// Defines filter_iterator to a suitable specialization of 5660b57cec5SDimitry Andric /// filter_iterator_impl, based on the underlying iterator's category. 5670b57cec5SDimitry Andric template <typename WrappedIteratorT, typename PredicateT> 5680b57cec5SDimitry Andric using filter_iterator = filter_iterator_impl< 5690b57cec5SDimitry Andric WrappedIteratorT, PredicateT, 5700b57cec5SDimitry Andric typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>; 5710b57cec5SDimitry Andric 5720b57cec5SDimitry Andric /// Convenience function that takes a range of elements and a predicate, 5730b57cec5SDimitry Andric /// and return a new filter_iterator range. 5740b57cec5SDimitry Andric /// 5750b57cec5SDimitry Andric /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the 5760b57cec5SDimitry Andric /// lifetime of that temporary is not kept by the returned range object, and the 5770b57cec5SDimitry Andric /// temporary is going to be dropped on the floor after the make_iterator_range 5780b57cec5SDimitry Andric /// full expression that contains this function call. 5790b57cec5SDimitry Andric template <typename RangeT, typename PredicateT> 5800b57cec5SDimitry Andric iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>> 5810b57cec5SDimitry Andric make_filter_range(RangeT &&Range, PredicateT Pred) { 5820b57cec5SDimitry Andric using FilterIteratorT = 5830b57cec5SDimitry Andric filter_iterator<detail::IterOfRange<RangeT>, PredicateT>; 5840b57cec5SDimitry Andric return make_range( 5850b57cec5SDimitry Andric FilterIteratorT(std::begin(std::forward<RangeT>(Range)), 5860b57cec5SDimitry Andric std::end(std::forward<RangeT>(Range)), Pred), 5870b57cec5SDimitry Andric FilterIteratorT(std::end(std::forward<RangeT>(Range)), 5880b57cec5SDimitry Andric std::end(std::forward<RangeT>(Range)), Pred)); 5890b57cec5SDimitry Andric } 5900b57cec5SDimitry Andric 5910b57cec5SDimitry Andric /// A pseudo-iterator adaptor that is designed to implement "early increment" 5920b57cec5SDimitry Andric /// style loops. 5930b57cec5SDimitry Andric /// 5940b57cec5SDimitry Andric /// This is *not a normal iterator* and should almost never be used directly. It 5950b57cec5SDimitry Andric /// is intended primarily to be used with range based for loops and some range 5960b57cec5SDimitry Andric /// algorithms. 5970b57cec5SDimitry Andric /// 5980b57cec5SDimitry Andric /// The iterator isn't quite an `OutputIterator` or an `InputIterator` but 5990b57cec5SDimitry Andric /// somewhere between them. The constraints of these iterators are: 6000b57cec5SDimitry Andric /// 6010b57cec5SDimitry Andric /// - On construction or after being incremented, it is comparable and 6020b57cec5SDimitry Andric /// dereferencable. It is *not* incrementable. 6030b57cec5SDimitry Andric /// - After being dereferenced, it is neither comparable nor dereferencable, it 6040b57cec5SDimitry Andric /// is only incrementable. 6050b57cec5SDimitry Andric /// 6060b57cec5SDimitry Andric /// This means you can only dereference the iterator once, and you can only 6070b57cec5SDimitry Andric /// increment it once between dereferences. 6080b57cec5SDimitry Andric template <typename WrappedIteratorT> 6090b57cec5SDimitry Andric class early_inc_iterator_impl 6100b57cec5SDimitry Andric : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>, 6110b57cec5SDimitry Andric WrappedIteratorT, std::input_iterator_tag> { 612349cc55cSDimitry Andric using BaseT = typename early_inc_iterator_impl::iterator_adaptor_base; 6130b57cec5SDimitry Andric 6140b57cec5SDimitry Andric using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer; 6150b57cec5SDimitry Andric 6160b57cec5SDimitry Andric protected: 6170b57cec5SDimitry Andric #if LLVM_ENABLE_ABI_BREAKING_CHECKS 6180b57cec5SDimitry Andric bool IsEarlyIncremented = false; 6190b57cec5SDimitry Andric #endif 6200b57cec5SDimitry Andric 6210b57cec5SDimitry Andric public: 6220b57cec5SDimitry Andric early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {} 6230b57cec5SDimitry Andric 6240b57cec5SDimitry Andric using BaseT::operator*; 625e8d8bef9SDimitry Andric decltype(*std::declval<WrappedIteratorT>()) operator*() { 6260b57cec5SDimitry Andric #if LLVM_ENABLE_ABI_BREAKING_CHECKS 6270b57cec5SDimitry Andric assert(!IsEarlyIncremented && "Cannot dereference twice!"); 6280b57cec5SDimitry Andric IsEarlyIncremented = true; 6290b57cec5SDimitry Andric #endif 6300b57cec5SDimitry Andric return *(this->I)++; 6310b57cec5SDimitry Andric } 6320b57cec5SDimitry Andric 6330b57cec5SDimitry Andric using BaseT::operator++; 6340b57cec5SDimitry Andric early_inc_iterator_impl &operator++() { 6350b57cec5SDimitry Andric #if LLVM_ENABLE_ABI_BREAKING_CHECKS 6360b57cec5SDimitry Andric assert(IsEarlyIncremented && "Cannot increment before dereferencing!"); 6370b57cec5SDimitry Andric IsEarlyIncremented = false; 6380b57cec5SDimitry Andric #endif 6390b57cec5SDimitry Andric return *this; 6400b57cec5SDimitry Andric } 6410b57cec5SDimitry Andric 642e8d8bef9SDimitry Andric friend bool operator==(const early_inc_iterator_impl &LHS, 643e8d8bef9SDimitry Andric const early_inc_iterator_impl &RHS) { 6440b57cec5SDimitry Andric #if LLVM_ENABLE_ABI_BREAKING_CHECKS 645e8d8bef9SDimitry Andric assert(!LHS.IsEarlyIncremented && "Cannot compare after dereferencing!"); 6460b57cec5SDimitry Andric #endif 647e8d8bef9SDimitry Andric return (const BaseT &)LHS == (const BaseT &)RHS; 6480b57cec5SDimitry Andric } 6490b57cec5SDimitry Andric }; 6500b57cec5SDimitry Andric 6510b57cec5SDimitry Andric /// Make a range that does early increment to allow mutation of the underlying 6520b57cec5SDimitry Andric /// range without disrupting iteration. 6530b57cec5SDimitry Andric /// 6540b57cec5SDimitry Andric /// The underlying iterator will be incremented immediately after it is 6550b57cec5SDimitry Andric /// dereferenced, allowing deletion of the current node or insertion of nodes to 6560b57cec5SDimitry Andric /// not disrupt iteration provided they do not invalidate the *next* iterator -- 6570b57cec5SDimitry Andric /// the current iterator can be invalidated. 6580b57cec5SDimitry Andric /// 6590b57cec5SDimitry Andric /// This requires a very exact pattern of use that is only really suitable to 6600b57cec5SDimitry Andric /// range based for loops and other range algorithms that explicitly guarantee 6610b57cec5SDimitry Andric /// to dereference exactly once each element, and to increment exactly once each 6620b57cec5SDimitry Andric /// element. 6630b57cec5SDimitry Andric template <typename RangeT> 6640b57cec5SDimitry Andric iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>> 6650b57cec5SDimitry Andric make_early_inc_range(RangeT &&Range) { 6660b57cec5SDimitry Andric using EarlyIncIteratorT = 6670b57cec5SDimitry Andric early_inc_iterator_impl<detail::IterOfRange<RangeT>>; 6680b57cec5SDimitry Andric return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))), 6690b57cec5SDimitry Andric EarlyIncIteratorT(std::end(std::forward<RangeT>(Range)))); 6700b57cec5SDimitry Andric } 6710b57cec5SDimitry Andric 672bdd1243dSDimitry Andric // Forward declarations required by zip_shortest/zip_equal/zip_first/zip_longest 6730b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 6740b57cec5SDimitry Andric bool all_of(R &&range, UnaryPredicate P); 675bdd1243dSDimitry Andric 6760b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 6770b57cec5SDimitry Andric bool any_of(R &&range, UnaryPredicate P); 6780b57cec5SDimitry Andric 679bdd1243dSDimitry Andric template <typename T> bool all_equal(std::initializer_list<T> Values); 680bdd1243dSDimitry Andric 68106c3fb27SDimitry Andric template <typename R> constexpr size_t range_size(R &&Range); 68206c3fb27SDimitry Andric 6830b57cec5SDimitry Andric namespace detail { 6840b57cec5SDimitry Andric 6850b57cec5SDimitry Andric using std::declval; 6860b57cec5SDimitry Andric 6870b57cec5SDimitry Andric // We have to alias this since inlining the actual type at the usage site 6880b57cec5SDimitry Andric // in the parameter list of iterator_facade_base<> below ICEs MSVC 2017. 6890b57cec5SDimitry Andric template<typename... Iters> struct ZipTupleType { 6900b57cec5SDimitry Andric using type = std::tuple<decltype(*declval<Iters>())...>; 6910b57cec5SDimitry Andric }; 6920b57cec5SDimitry Andric 69306c3fb27SDimitry Andric template <typename ZipType, typename ReferenceTupleType, typename... Iters> 6940b57cec5SDimitry Andric using zip_traits = iterator_facade_base< 695bdd1243dSDimitry Andric ZipType, 696bdd1243dSDimitry Andric std::common_type_t< 697bdd1243dSDimitry Andric std::bidirectional_iterator_tag, 698bdd1243dSDimitry Andric typename std::iterator_traits<Iters>::iterator_category...>, 6990b57cec5SDimitry Andric // ^ TODO: Implement random access methods. 70006c3fb27SDimitry Andric ReferenceTupleType, 701bdd1243dSDimitry Andric typename std::iterator_traits< 702bdd1243dSDimitry Andric std::tuple_element_t<0, std::tuple<Iters...>>>::difference_type, 7030b57cec5SDimitry Andric // ^ FIXME: This follows boost::make_zip_iterator's assumption that all 7040b57cec5SDimitry Andric // inner iterators have the same difference_type. It would fail if, for 7050b57cec5SDimitry Andric // instance, the second field's difference_type were non-numeric while the 7060b57cec5SDimitry Andric // first is. 70706c3fb27SDimitry Andric ReferenceTupleType *, ReferenceTupleType>; 7080b57cec5SDimitry Andric 70906c3fb27SDimitry Andric template <typename ZipType, typename ReferenceTupleType, typename... Iters> 71006c3fb27SDimitry Andric struct zip_common : public zip_traits<ZipType, ReferenceTupleType, Iters...> { 71106c3fb27SDimitry Andric using Base = zip_traits<ZipType, ReferenceTupleType, Iters...>; 71206c3fb27SDimitry Andric using IndexSequence = std::index_sequence_for<Iters...>; 7130b57cec5SDimitry Andric using value_type = typename Base::value_type; 7140b57cec5SDimitry Andric 7150b57cec5SDimitry Andric std::tuple<Iters...> iterators; 7160b57cec5SDimitry Andric 7170b57cec5SDimitry Andric protected: 7188bcb0991SDimitry Andric template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const { 7190b57cec5SDimitry Andric return value_type(*std::get<Ns>(iterators)...); 7200b57cec5SDimitry Andric } 7210b57cec5SDimitry Andric 72206c3fb27SDimitry Andric template <size_t... Ns> void tup_inc(std::index_sequence<Ns...>) { 72306c3fb27SDimitry Andric (++std::get<Ns>(iterators), ...); 7240b57cec5SDimitry Andric } 7250b57cec5SDimitry Andric 72606c3fb27SDimitry Andric template <size_t... Ns> void tup_dec(std::index_sequence<Ns...>) { 72706c3fb27SDimitry Andric (--std::get<Ns>(iterators), ...); 7280b57cec5SDimitry Andric } 7290b57cec5SDimitry Andric 730349cc55cSDimitry Andric template <size_t... Ns> 731349cc55cSDimitry Andric bool test_all_equals(const zip_common &other, 732349cc55cSDimitry Andric std::index_sequence<Ns...>) const { 733bdd1243dSDimitry Andric return ((std::get<Ns>(this->iterators) == std::get<Ns>(other.iterators)) && 734bdd1243dSDimitry Andric ...); 735349cc55cSDimitry Andric } 736349cc55cSDimitry Andric 7370b57cec5SDimitry Andric public: 7380b57cec5SDimitry Andric zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {} 7390b57cec5SDimitry Andric 74006c3fb27SDimitry Andric value_type operator*() const { return deref(IndexSequence{}); } 7410b57cec5SDimitry Andric 7420b57cec5SDimitry Andric ZipType &operator++() { 74306c3fb27SDimitry Andric tup_inc(IndexSequence{}); 74406c3fb27SDimitry Andric return static_cast<ZipType &>(*this); 7450b57cec5SDimitry Andric } 7460b57cec5SDimitry Andric 7470b57cec5SDimitry Andric ZipType &operator--() { 7480b57cec5SDimitry Andric static_assert(Base::IsBidirectional, 7490b57cec5SDimitry Andric "All inner iterators must be at least bidirectional."); 75006c3fb27SDimitry Andric tup_dec(IndexSequence{}); 75106c3fb27SDimitry Andric return static_cast<ZipType &>(*this); 7520b57cec5SDimitry Andric } 753349cc55cSDimitry Andric 754349cc55cSDimitry Andric /// Return true if all the iterator are matching `other`'s iterators. 755349cc55cSDimitry Andric bool all_equals(zip_common &other) { 75606c3fb27SDimitry Andric return test_all_equals(other, IndexSequence{}); 757349cc55cSDimitry Andric } 7580b57cec5SDimitry Andric }; 7590b57cec5SDimitry Andric 7600b57cec5SDimitry Andric template <typename... Iters> 76106c3fb27SDimitry Andric struct zip_first : zip_common<zip_first<Iters...>, 76206c3fb27SDimitry Andric typename ZipTupleType<Iters...>::type, Iters...> { 76306c3fb27SDimitry Andric using zip_common<zip_first, typename ZipTupleType<Iters...>::type, 76406c3fb27SDimitry Andric Iters...>::zip_common; 7650b57cec5SDimitry Andric 76606c3fb27SDimitry Andric bool operator==(const zip_first &other) const { 7670b57cec5SDimitry Andric return std::get<0>(this->iterators) == std::get<0>(other.iterators); 7680b57cec5SDimitry Andric } 7690b57cec5SDimitry Andric }; 7700b57cec5SDimitry Andric 7710b57cec5SDimitry Andric template <typename... Iters> 77206c3fb27SDimitry Andric struct zip_shortest 77306c3fb27SDimitry Andric : zip_common<zip_shortest<Iters...>, typename ZipTupleType<Iters...>::type, 77406c3fb27SDimitry Andric Iters...> { 77506c3fb27SDimitry Andric using zip_common<zip_shortest, typename ZipTupleType<Iters...>::type, 77606c3fb27SDimitry Andric Iters...>::zip_common; 77706c3fb27SDimitry Andric 77806c3fb27SDimitry Andric bool operator==(const zip_shortest &other) const { 77906c3fb27SDimitry Andric return any_iterator_equals(other, std::index_sequence_for<Iters...>{}); 78006c3fb27SDimitry Andric } 78106c3fb27SDimitry Andric 78206c3fb27SDimitry Andric private: 7830b57cec5SDimitry Andric template <size_t... Ns> 78406c3fb27SDimitry Andric bool any_iterator_equals(const zip_shortest &other, 7858bcb0991SDimitry Andric std::index_sequence<Ns...>) const { 78606c3fb27SDimitry Andric return ((std::get<Ns>(this->iterators) == std::get<Ns>(other.iterators)) || 787bdd1243dSDimitry Andric ...); 7880b57cec5SDimitry Andric } 78906c3fb27SDimitry Andric }; 7900b57cec5SDimitry Andric 79106c3fb27SDimitry Andric /// Helper to obtain the iterator types for the tuple storage within `zippy`. 79206c3fb27SDimitry Andric template <template <typename...> class ItType, typename TupleStorageType, 79306c3fb27SDimitry Andric typename IndexSequence> 79406c3fb27SDimitry Andric struct ZippyIteratorTuple; 7950b57cec5SDimitry Andric 79606c3fb27SDimitry Andric /// Partial specialization for non-const tuple storage. 79706c3fb27SDimitry Andric template <template <typename...> class ItType, typename... Args, 79806c3fb27SDimitry Andric std::size_t... Ns> 79906c3fb27SDimitry Andric struct ZippyIteratorTuple<ItType, std::tuple<Args...>, 80006c3fb27SDimitry Andric std::index_sequence<Ns...>> { 80106c3fb27SDimitry Andric using type = ItType<decltype(adl_begin( 80206c3fb27SDimitry Andric std::get<Ns>(declval<std::tuple<Args...> &>())))...>; 80306c3fb27SDimitry Andric }; 8040b57cec5SDimitry Andric 80506c3fb27SDimitry Andric /// Partial specialization for const tuple storage. 80606c3fb27SDimitry Andric template <template <typename...> class ItType, typename... Args, 80706c3fb27SDimitry Andric std::size_t... Ns> 80806c3fb27SDimitry Andric struct ZippyIteratorTuple<ItType, const std::tuple<Args...>, 80906c3fb27SDimitry Andric std::index_sequence<Ns...>> { 81006c3fb27SDimitry Andric using type = ItType<decltype(adl_begin( 81106c3fb27SDimitry Andric std::get<Ns>(declval<const std::tuple<Args...> &>())))...>; 8120b57cec5SDimitry Andric }; 8130b57cec5SDimitry Andric 8140b57cec5SDimitry Andric template <template <typename...> class ItType, typename... Args> class zippy { 81506c3fb27SDimitry Andric private: 81606c3fb27SDimitry Andric std::tuple<Args...> storage; 81706c3fb27SDimitry Andric using IndexSequence = std::index_sequence_for<Args...>; 81806c3fb27SDimitry Andric 8190b57cec5SDimitry Andric public: 82006c3fb27SDimitry Andric using iterator = typename ZippyIteratorTuple<ItType, decltype(storage), 82106c3fb27SDimitry Andric IndexSequence>::type; 82206c3fb27SDimitry Andric using const_iterator = 82306c3fb27SDimitry Andric typename ZippyIteratorTuple<ItType, const decltype(storage), 82406c3fb27SDimitry Andric IndexSequence>::type; 8250b57cec5SDimitry Andric using iterator_category = typename iterator::iterator_category; 8260b57cec5SDimitry Andric using value_type = typename iterator::value_type; 8270b57cec5SDimitry Andric using difference_type = typename iterator::difference_type; 8280b57cec5SDimitry Andric using pointer = typename iterator::pointer; 8290b57cec5SDimitry Andric using reference = typename iterator::reference; 83006c3fb27SDimitry Andric using const_reference = typename const_iterator::reference; 83106c3fb27SDimitry Andric 83206c3fb27SDimitry Andric zippy(Args &&...args) : storage(std::forward<Args>(args)...) {} 83306c3fb27SDimitry Andric 83406c3fb27SDimitry Andric const_iterator begin() const { return begin_impl(IndexSequence{}); } 83506c3fb27SDimitry Andric iterator begin() { return begin_impl(IndexSequence{}); } 83606c3fb27SDimitry Andric const_iterator end() const { return end_impl(IndexSequence{}); } 83706c3fb27SDimitry Andric iterator end() { return end_impl(IndexSequence{}); } 8380b57cec5SDimitry Andric 8390b57cec5SDimitry Andric private: 84006c3fb27SDimitry Andric template <size_t... Ns> 84106c3fb27SDimitry Andric const_iterator begin_impl(std::index_sequence<Ns...>) const { 84206c3fb27SDimitry Andric return const_iterator(adl_begin(std::get<Ns>(storage))...); 84306c3fb27SDimitry Andric } 84406c3fb27SDimitry Andric template <size_t... Ns> iterator begin_impl(std::index_sequence<Ns...>) { 84506c3fb27SDimitry Andric return iterator(adl_begin(std::get<Ns>(storage))...); 84606c3fb27SDimitry Andric } 8470b57cec5SDimitry Andric 8488bcb0991SDimitry Andric template <size_t... Ns> 84906c3fb27SDimitry Andric const_iterator end_impl(std::index_sequence<Ns...>) const { 85006c3fb27SDimitry Andric return const_iterator(adl_end(std::get<Ns>(storage))...); 8510b57cec5SDimitry Andric } 85206c3fb27SDimitry Andric template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) { 85306c3fb27SDimitry Andric return iterator(adl_end(std::get<Ns>(storage))...); 8540b57cec5SDimitry Andric } 8550b57cec5SDimitry Andric }; 8560b57cec5SDimitry Andric 8570b57cec5SDimitry Andric } // end namespace detail 8580b57cec5SDimitry Andric 859bdd1243dSDimitry Andric /// zip iterator for two or more iteratable types. Iteration continues until the 860bdd1243dSDimitry Andric /// end of the *shortest* iteratee is reached. 8610b57cec5SDimitry Andric template <typename T, typename U, typename... Args> 8620b57cec5SDimitry Andric detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u, 8630b57cec5SDimitry Andric Args &&...args) { 8640b57cec5SDimitry Andric return detail::zippy<detail::zip_shortest, T, U, Args...>( 8650b57cec5SDimitry Andric std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); 8660b57cec5SDimitry Andric } 8670b57cec5SDimitry Andric 868bdd1243dSDimitry Andric /// zip iterator that assumes that all iteratees have the same length. 869bdd1243dSDimitry Andric /// In builds with assertions on, this assumption is checked before the 870bdd1243dSDimitry Andric /// iteration starts. 871bdd1243dSDimitry Andric template <typename T, typename U, typename... Args> 872bdd1243dSDimitry Andric detail::zippy<detail::zip_first, T, U, Args...> zip_equal(T &&t, U &&u, 873bdd1243dSDimitry Andric Args &&...args) { 87406c3fb27SDimitry Andric assert(all_equal({range_size(t), range_size(u), range_size(args)...}) && 875bdd1243dSDimitry Andric "Iteratees do not have equal length"); 876bdd1243dSDimitry Andric return detail::zippy<detail::zip_first, T, U, Args...>( 877bdd1243dSDimitry Andric std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); 878bdd1243dSDimitry Andric } 879bdd1243dSDimitry Andric 8800b57cec5SDimitry Andric /// zip iterator that, for the sake of efficiency, assumes the first iteratee to 881bdd1243dSDimitry Andric /// be the shortest. Iteration continues until the end of the first iteratee is 882bdd1243dSDimitry Andric /// reached. In builds with assertions on, we check that the assumption about 883bdd1243dSDimitry Andric /// the first iteratee being the shortest holds. 8840b57cec5SDimitry Andric template <typename T, typename U, typename... Args> 8850b57cec5SDimitry Andric detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u, 8860b57cec5SDimitry Andric Args &&...args) { 88706c3fb27SDimitry Andric assert(range_size(t) <= std::min({range_size(u), range_size(args)...}) && 888bdd1243dSDimitry Andric "First iteratee is not the shortest"); 889bdd1243dSDimitry Andric 8900b57cec5SDimitry Andric return detail::zippy<detail::zip_first, T, U, Args...>( 8910b57cec5SDimitry Andric std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); 8920b57cec5SDimitry Andric } 8930b57cec5SDimitry Andric 8940b57cec5SDimitry Andric namespace detail { 8950b57cec5SDimitry Andric template <typename Iter> 8965ffd83dbSDimitry Andric Iter next_or_end(const Iter &I, const Iter &End) { 8970b57cec5SDimitry Andric if (I == End) 8980b57cec5SDimitry Andric return End; 8990b57cec5SDimitry Andric return std::next(I); 9000b57cec5SDimitry Andric } 9010b57cec5SDimitry Andric 9020b57cec5SDimitry Andric template <typename Iter> 903bdd1243dSDimitry Andric auto deref_or_none(const Iter &I, const Iter &End) -> std::optional< 9045ffd83dbSDimitry Andric std::remove_const_t<std::remove_reference_t<decltype(*I)>>> { 9050b57cec5SDimitry Andric if (I == End) 906bdd1243dSDimitry Andric return std::nullopt; 9070b57cec5SDimitry Andric return *I; 9080b57cec5SDimitry Andric } 9090b57cec5SDimitry Andric 9100b57cec5SDimitry Andric template <typename Iter> struct ZipLongestItemType { 911bdd1243dSDimitry Andric using type = std::optional<std::remove_const_t< 912bdd1243dSDimitry Andric std::remove_reference_t<decltype(*std::declval<Iter>())>>>; 9130b57cec5SDimitry Andric }; 9140b57cec5SDimitry Andric 9150b57cec5SDimitry Andric template <typename... Iters> struct ZipLongestTupleType { 9160b57cec5SDimitry Andric using type = std::tuple<typename ZipLongestItemType<Iters>::type...>; 9170b57cec5SDimitry Andric }; 9180b57cec5SDimitry Andric 9190b57cec5SDimitry Andric template <typename... Iters> 9200b57cec5SDimitry Andric class zip_longest_iterator 9210b57cec5SDimitry Andric : public iterator_facade_base< 9220b57cec5SDimitry Andric zip_longest_iterator<Iters...>, 923bdd1243dSDimitry Andric std::common_type_t< 9240b57cec5SDimitry Andric std::forward_iterator_tag, 925bdd1243dSDimitry Andric typename std::iterator_traits<Iters>::iterator_category...>, 9260b57cec5SDimitry Andric typename ZipLongestTupleType<Iters...>::type, 927bdd1243dSDimitry Andric typename std::iterator_traits< 928bdd1243dSDimitry Andric std::tuple_element_t<0, std::tuple<Iters...>>>::difference_type, 9290b57cec5SDimitry Andric typename ZipLongestTupleType<Iters...>::type *, 9300b57cec5SDimitry Andric typename ZipLongestTupleType<Iters...>::type> { 9310b57cec5SDimitry Andric public: 9320b57cec5SDimitry Andric using value_type = typename ZipLongestTupleType<Iters...>::type; 9330b57cec5SDimitry Andric 9340b57cec5SDimitry Andric private: 9350b57cec5SDimitry Andric std::tuple<Iters...> iterators; 9360b57cec5SDimitry Andric std::tuple<Iters...> end_iterators; 9370b57cec5SDimitry Andric 9380b57cec5SDimitry Andric template <size_t... Ns> 9390b57cec5SDimitry Andric bool test(const zip_longest_iterator<Iters...> &other, 9408bcb0991SDimitry Andric std::index_sequence<Ns...>) const { 941bdd1243dSDimitry Andric return ((std::get<Ns>(this->iterators) != std::get<Ns>(other.iterators)) || 942bdd1243dSDimitry Andric ...); 9430b57cec5SDimitry Andric } 9440b57cec5SDimitry Andric 9458bcb0991SDimitry Andric template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const { 9460b57cec5SDimitry Andric return value_type( 9470b57cec5SDimitry Andric deref_or_none(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...); 9480b57cec5SDimitry Andric } 9490b57cec5SDimitry Andric 9500b57cec5SDimitry Andric template <size_t... Ns> 9518bcb0991SDimitry Andric decltype(iterators) tup_inc(std::index_sequence<Ns...>) const { 9520b57cec5SDimitry Andric return std::tuple<Iters...>( 9530b57cec5SDimitry Andric next_or_end(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...); 9540b57cec5SDimitry Andric } 9550b57cec5SDimitry Andric 9560b57cec5SDimitry Andric public: 9570b57cec5SDimitry Andric zip_longest_iterator(std::pair<Iters &&, Iters &&>... ts) 9580b57cec5SDimitry Andric : iterators(std::forward<Iters>(ts.first)...), 9590b57cec5SDimitry Andric end_iterators(std::forward<Iters>(ts.second)...) {} 9600b57cec5SDimitry Andric 9618bcb0991SDimitry Andric value_type operator*() const { 9628bcb0991SDimitry Andric return deref(std::index_sequence_for<Iters...>{}); 9638bcb0991SDimitry Andric } 9640b57cec5SDimitry Andric 9650b57cec5SDimitry Andric zip_longest_iterator<Iters...> &operator++() { 9668bcb0991SDimitry Andric iterators = tup_inc(std::index_sequence_for<Iters...>{}); 9670b57cec5SDimitry Andric return *this; 9680b57cec5SDimitry Andric } 9690b57cec5SDimitry Andric 9700b57cec5SDimitry Andric bool operator==(const zip_longest_iterator<Iters...> &other) const { 9718bcb0991SDimitry Andric return !test(other, std::index_sequence_for<Iters...>{}); 9720b57cec5SDimitry Andric } 9730b57cec5SDimitry Andric }; 9740b57cec5SDimitry Andric 9750b57cec5SDimitry Andric template <typename... Args> class zip_longest_range { 9760b57cec5SDimitry Andric public: 9770b57cec5SDimitry Andric using iterator = 9780b57cec5SDimitry Andric zip_longest_iterator<decltype(adl_begin(std::declval<Args>()))...>; 9790b57cec5SDimitry Andric using iterator_category = typename iterator::iterator_category; 9800b57cec5SDimitry Andric using value_type = typename iterator::value_type; 9810b57cec5SDimitry Andric using difference_type = typename iterator::difference_type; 9820b57cec5SDimitry Andric using pointer = typename iterator::pointer; 9830b57cec5SDimitry Andric using reference = typename iterator::reference; 9840b57cec5SDimitry Andric 9850b57cec5SDimitry Andric private: 9860b57cec5SDimitry Andric std::tuple<Args...> ts; 9870b57cec5SDimitry Andric 9888bcb0991SDimitry Andric template <size_t... Ns> 9898bcb0991SDimitry Andric iterator begin_impl(std::index_sequence<Ns...>) const { 9900b57cec5SDimitry Andric return iterator(std::make_pair(adl_begin(std::get<Ns>(ts)), 9910b57cec5SDimitry Andric adl_end(std::get<Ns>(ts)))...); 9920b57cec5SDimitry Andric } 9930b57cec5SDimitry Andric 9948bcb0991SDimitry Andric template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const { 9950b57cec5SDimitry Andric return iterator(std::make_pair(adl_end(std::get<Ns>(ts)), 9960b57cec5SDimitry Andric adl_end(std::get<Ns>(ts)))...); 9970b57cec5SDimitry Andric } 9980b57cec5SDimitry Andric 9990b57cec5SDimitry Andric public: 10000b57cec5SDimitry Andric zip_longest_range(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {} 10010b57cec5SDimitry Andric 10028bcb0991SDimitry Andric iterator begin() const { 10038bcb0991SDimitry Andric return begin_impl(std::index_sequence_for<Args...>{}); 10048bcb0991SDimitry Andric } 10058bcb0991SDimitry Andric iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); } 10060b57cec5SDimitry Andric }; 10070b57cec5SDimitry Andric } // namespace detail 10080b57cec5SDimitry Andric 10090b57cec5SDimitry Andric /// Iterate over two or more iterators at the same time. Iteration continues 1010bdd1243dSDimitry Andric /// until all iterators reach the end. The std::optional only contains a value 10110b57cec5SDimitry Andric /// if the iterator has not reached the end. 10120b57cec5SDimitry Andric template <typename T, typename U, typename... Args> 10130b57cec5SDimitry Andric detail::zip_longest_range<T, U, Args...> zip_longest(T &&t, U &&u, 10140b57cec5SDimitry Andric Args &&... args) { 10150b57cec5SDimitry Andric return detail::zip_longest_range<T, U, Args...>( 10160b57cec5SDimitry Andric std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); 10170b57cec5SDimitry Andric } 10180b57cec5SDimitry Andric 10190b57cec5SDimitry Andric /// Iterator wrapper that concatenates sequences together. 10200b57cec5SDimitry Andric /// 10210b57cec5SDimitry Andric /// This can concatenate different iterators, even with different types, into 10220b57cec5SDimitry Andric /// a single iterator provided the value types of all the concatenated 10230b57cec5SDimitry Andric /// iterators expose `reference` and `pointer` types that can be converted to 10240b57cec5SDimitry Andric /// `ValueT &` and `ValueT *` respectively. It doesn't support more 10250b57cec5SDimitry Andric /// interesting/customized pointer or reference types. 10260b57cec5SDimitry Andric /// 10270b57cec5SDimitry Andric /// Currently this only supports forward or higher iterator categories as 10280b57cec5SDimitry Andric /// inputs and always exposes a forward iterator interface. 10290b57cec5SDimitry Andric template <typename ValueT, typename... IterTs> 10300b57cec5SDimitry Andric class concat_iterator 10310b57cec5SDimitry Andric : public iterator_facade_base<concat_iterator<ValueT, IterTs...>, 10320b57cec5SDimitry Andric std::forward_iterator_tag, ValueT> { 10330b57cec5SDimitry Andric using BaseT = typename concat_iterator::iterator_facade_base; 10340b57cec5SDimitry Andric 10350b57cec5SDimitry Andric /// We store both the current and end iterators for each concatenated 10360b57cec5SDimitry Andric /// sequence in a tuple of pairs. 10370b57cec5SDimitry Andric /// 10380b57cec5SDimitry Andric /// Note that something like iterator_range seems nice at first here, but the 10390b57cec5SDimitry Andric /// range properties are of little benefit and end up getting in the way 10400b57cec5SDimitry Andric /// because we need to do mutation on the current iterators. 10410b57cec5SDimitry Andric std::tuple<IterTs...> Begins; 10420b57cec5SDimitry Andric std::tuple<IterTs...> Ends; 10430b57cec5SDimitry Andric 10440b57cec5SDimitry Andric /// Attempts to increment a specific iterator. 10450b57cec5SDimitry Andric /// 10460b57cec5SDimitry Andric /// Returns true if it was able to increment the iterator. Returns false if 10470b57cec5SDimitry Andric /// the iterator is already at the end iterator. 10480b57cec5SDimitry Andric template <size_t Index> bool incrementHelper() { 10490b57cec5SDimitry Andric auto &Begin = std::get<Index>(Begins); 10500b57cec5SDimitry Andric auto &End = std::get<Index>(Ends); 10510b57cec5SDimitry Andric if (Begin == End) 10520b57cec5SDimitry Andric return false; 10530b57cec5SDimitry Andric 10540b57cec5SDimitry Andric ++Begin; 10550b57cec5SDimitry Andric return true; 10560b57cec5SDimitry Andric } 10570b57cec5SDimitry Andric 10580b57cec5SDimitry Andric /// Increments the first non-end iterator. 10590b57cec5SDimitry Andric /// 10600b57cec5SDimitry Andric /// It is an error to call this with all iterators at the end. 10618bcb0991SDimitry Andric template <size_t... Ns> void increment(std::index_sequence<Ns...>) { 10620b57cec5SDimitry Andric // Build a sequence of functions to increment each iterator if possible. 10630b57cec5SDimitry Andric bool (concat_iterator::*IncrementHelperFns[])() = { 10640b57cec5SDimitry Andric &concat_iterator::incrementHelper<Ns>...}; 10650b57cec5SDimitry Andric 10660b57cec5SDimitry Andric // Loop over them, and stop as soon as we succeed at incrementing one. 10670b57cec5SDimitry Andric for (auto &IncrementHelperFn : IncrementHelperFns) 10680b57cec5SDimitry Andric if ((this->*IncrementHelperFn)()) 10690b57cec5SDimitry Andric return; 10700b57cec5SDimitry Andric 10710b57cec5SDimitry Andric llvm_unreachable("Attempted to increment an end concat iterator!"); 10720b57cec5SDimitry Andric } 10730b57cec5SDimitry Andric 10740b57cec5SDimitry Andric /// Returns null if the specified iterator is at the end. Otherwise, 10750b57cec5SDimitry Andric /// dereferences the iterator and returns the address of the resulting 10760b57cec5SDimitry Andric /// reference. 10770b57cec5SDimitry Andric template <size_t Index> ValueT *getHelper() const { 10780b57cec5SDimitry Andric auto &Begin = std::get<Index>(Begins); 10790b57cec5SDimitry Andric auto &End = std::get<Index>(Ends); 10800b57cec5SDimitry Andric if (Begin == End) 10810b57cec5SDimitry Andric return nullptr; 10820b57cec5SDimitry Andric 10830b57cec5SDimitry Andric return &*Begin; 10840b57cec5SDimitry Andric } 10850b57cec5SDimitry Andric 10860b57cec5SDimitry Andric /// Finds the first non-end iterator, dereferences, and returns the resulting 10870b57cec5SDimitry Andric /// reference. 10880b57cec5SDimitry Andric /// 10890b57cec5SDimitry Andric /// It is an error to call this with all iterators at the end. 10908bcb0991SDimitry Andric template <size_t... Ns> ValueT &get(std::index_sequence<Ns...>) const { 10910b57cec5SDimitry Andric // Build a sequence of functions to get from iterator if possible. 10920b57cec5SDimitry Andric ValueT *(concat_iterator::*GetHelperFns[])() const = { 10930b57cec5SDimitry Andric &concat_iterator::getHelper<Ns>...}; 10940b57cec5SDimitry Andric 10950b57cec5SDimitry Andric // Loop over them, and return the first result we find. 10960b57cec5SDimitry Andric for (auto &GetHelperFn : GetHelperFns) 10970b57cec5SDimitry Andric if (ValueT *P = (this->*GetHelperFn)()) 10980b57cec5SDimitry Andric return *P; 10990b57cec5SDimitry Andric 11000b57cec5SDimitry Andric llvm_unreachable("Attempted to get a pointer from an end concat iterator!"); 11010b57cec5SDimitry Andric } 11020b57cec5SDimitry Andric 11030b57cec5SDimitry Andric public: 11045ffd83dbSDimitry Andric /// Constructs an iterator from a sequence of ranges. 11050b57cec5SDimitry Andric /// 11060b57cec5SDimitry Andric /// We need the full range to know how to switch between each of the 11070b57cec5SDimitry Andric /// iterators. 11080b57cec5SDimitry Andric template <typename... RangeTs> 11090b57cec5SDimitry Andric explicit concat_iterator(RangeTs &&... Ranges) 11100b57cec5SDimitry Andric : Begins(std::begin(Ranges)...), Ends(std::end(Ranges)...) {} 11110b57cec5SDimitry Andric 11120b57cec5SDimitry Andric using BaseT::operator++; 11130b57cec5SDimitry Andric 11140b57cec5SDimitry Andric concat_iterator &operator++() { 11158bcb0991SDimitry Andric increment(std::index_sequence_for<IterTs...>()); 11160b57cec5SDimitry Andric return *this; 11170b57cec5SDimitry Andric } 11180b57cec5SDimitry Andric 11198bcb0991SDimitry Andric ValueT &operator*() const { 11208bcb0991SDimitry Andric return get(std::index_sequence_for<IterTs...>()); 11218bcb0991SDimitry Andric } 11220b57cec5SDimitry Andric 11230b57cec5SDimitry Andric bool operator==(const concat_iterator &RHS) const { 11240b57cec5SDimitry Andric return Begins == RHS.Begins && Ends == RHS.Ends; 11250b57cec5SDimitry Andric } 11260b57cec5SDimitry Andric }; 11270b57cec5SDimitry Andric 11280b57cec5SDimitry Andric namespace detail { 11290b57cec5SDimitry Andric 11300b57cec5SDimitry Andric /// Helper to store a sequence of ranges being concatenated and access them. 11310b57cec5SDimitry Andric /// 11320b57cec5SDimitry Andric /// This is designed to facilitate providing actual storage when temporaries 11330b57cec5SDimitry Andric /// are passed into the constructor such that we can use it as part of range 11340b57cec5SDimitry Andric /// based for loops. 11350b57cec5SDimitry Andric template <typename ValueT, typename... RangeTs> class concat_range { 11360b57cec5SDimitry Andric public: 11370b57cec5SDimitry Andric using iterator = 11380b57cec5SDimitry Andric concat_iterator<ValueT, 11390b57cec5SDimitry Andric decltype(std::begin(std::declval<RangeTs &>()))...>; 11400b57cec5SDimitry Andric 11410b57cec5SDimitry Andric private: 11420b57cec5SDimitry Andric std::tuple<RangeTs...> Ranges; 11430b57cec5SDimitry Andric 11444824e7fdSDimitry Andric template <size_t... Ns> 11454824e7fdSDimitry Andric iterator begin_impl(std::index_sequence<Ns...>) { 11464824e7fdSDimitry Andric return iterator(std::get<Ns>(Ranges)...); 11474824e7fdSDimitry Andric } 11484824e7fdSDimitry Andric template <size_t... Ns> 11494824e7fdSDimitry Andric iterator begin_impl(std::index_sequence<Ns...>) const { 11500b57cec5SDimitry Andric return iterator(std::get<Ns>(Ranges)...); 11510b57cec5SDimitry Andric } 11528bcb0991SDimitry Andric template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) { 11530b57cec5SDimitry Andric return iterator(make_range(std::end(std::get<Ns>(Ranges)), 11540b57cec5SDimitry Andric std::end(std::get<Ns>(Ranges)))...); 11550b57cec5SDimitry Andric } 11564824e7fdSDimitry Andric template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const { 11574824e7fdSDimitry Andric return iterator(make_range(std::end(std::get<Ns>(Ranges)), 11584824e7fdSDimitry Andric std::end(std::get<Ns>(Ranges)))...); 11594824e7fdSDimitry Andric } 11600b57cec5SDimitry Andric 11610b57cec5SDimitry Andric public: 11620b57cec5SDimitry Andric concat_range(RangeTs &&... Ranges) 11630b57cec5SDimitry Andric : Ranges(std::forward<RangeTs>(Ranges)...) {} 11640b57cec5SDimitry Andric 11654824e7fdSDimitry Andric iterator begin() { 11664824e7fdSDimitry Andric return begin_impl(std::index_sequence_for<RangeTs...>{}); 11674824e7fdSDimitry Andric } 11684824e7fdSDimitry Andric iterator begin() const { 11694824e7fdSDimitry Andric return begin_impl(std::index_sequence_for<RangeTs...>{}); 11704824e7fdSDimitry Andric } 11714824e7fdSDimitry Andric iterator end() { 11724824e7fdSDimitry Andric return end_impl(std::index_sequence_for<RangeTs...>{}); 11734824e7fdSDimitry Andric } 11744824e7fdSDimitry Andric iterator end() const { 11754824e7fdSDimitry Andric return end_impl(std::index_sequence_for<RangeTs...>{}); 11764824e7fdSDimitry Andric } 11770b57cec5SDimitry Andric }; 11780b57cec5SDimitry Andric 11790b57cec5SDimitry Andric } // end namespace detail 11800b57cec5SDimitry Andric 11810b57cec5SDimitry Andric /// Concatenated range across two or more ranges. 11820b57cec5SDimitry Andric /// 11830b57cec5SDimitry Andric /// The desired value type must be explicitly specified. 11840b57cec5SDimitry Andric template <typename ValueT, typename... RangeTs> 11850b57cec5SDimitry Andric detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) { 11860b57cec5SDimitry Andric static_assert(sizeof...(RangeTs) > 1, 11870b57cec5SDimitry Andric "Need more than one range to concatenate!"); 11880b57cec5SDimitry Andric return detail::concat_range<ValueT, RangeTs...>( 11890b57cec5SDimitry Andric std::forward<RangeTs>(Ranges)...); 11900b57cec5SDimitry Andric } 11910b57cec5SDimitry Andric 11925ffd83dbSDimitry Andric /// A utility class used to implement an iterator that contains some base object 11935ffd83dbSDimitry Andric /// and an index. The iterator moves the index but keeps the base constant. 11945ffd83dbSDimitry Andric template <typename DerivedT, typename BaseT, typename T, 11955ffd83dbSDimitry Andric typename PointerT = T *, typename ReferenceT = T &> 11965ffd83dbSDimitry Andric class indexed_accessor_iterator 11975ffd83dbSDimitry Andric : public llvm::iterator_facade_base<DerivedT, 11985ffd83dbSDimitry Andric std::random_access_iterator_tag, T, 11995ffd83dbSDimitry Andric std::ptrdiff_t, PointerT, ReferenceT> { 12005ffd83dbSDimitry Andric public: 12015ffd83dbSDimitry Andric ptrdiff_t operator-(const indexed_accessor_iterator &rhs) const { 12025ffd83dbSDimitry Andric assert(base == rhs.base && "incompatible iterators"); 12035ffd83dbSDimitry Andric return index - rhs.index; 12045ffd83dbSDimitry Andric } 12055ffd83dbSDimitry Andric bool operator==(const indexed_accessor_iterator &rhs) const { 12065ffd83dbSDimitry Andric return base == rhs.base && index == rhs.index; 12075ffd83dbSDimitry Andric } 12085ffd83dbSDimitry Andric bool operator<(const indexed_accessor_iterator &rhs) const { 12095ffd83dbSDimitry Andric assert(base == rhs.base && "incompatible iterators"); 12105ffd83dbSDimitry Andric return index < rhs.index; 12115ffd83dbSDimitry Andric } 12125ffd83dbSDimitry Andric 12135ffd83dbSDimitry Andric DerivedT &operator+=(ptrdiff_t offset) { 12145ffd83dbSDimitry Andric this->index += offset; 12155ffd83dbSDimitry Andric return static_cast<DerivedT &>(*this); 12165ffd83dbSDimitry Andric } 12175ffd83dbSDimitry Andric DerivedT &operator-=(ptrdiff_t offset) { 12185ffd83dbSDimitry Andric this->index -= offset; 12195ffd83dbSDimitry Andric return static_cast<DerivedT &>(*this); 12205ffd83dbSDimitry Andric } 12215ffd83dbSDimitry Andric 12225ffd83dbSDimitry Andric /// Returns the current index of the iterator. 12235ffd83dbSDimitry Andric ptrdiff_t getIndex() const { return index; } 12245ffd83dbSDimitry Andric 12255ffd83dbSDimitry Andric /// Returns the current base of the iterator. 12265ffd83dbSDimitry Andric const BaseT &getBase() const { return base; } 12275ffd83dbSDimitry Andric 12285ffd83dbSDimitry Andric protected: 12295ffd83dbSDimitry Andric indexed_accessor_iterator(BaseT base, ptrdiff_t index) 12305ffd83dbSDimitry Andric : base(base), index(index) {} 12315ffd83dbSDimitry Andric BaseT base; 12325ffd83dbSDimitry Andric ptrdiff_t index; 12335ffd83dbSDimitry Andric }; 12345ffd83dbSDimitry Andric 12355ffd83dbSDimitry Andric namespace detail { 12365ffd83dbSDimitry Andric /// The class represents the base of a range of indexed_accessor_iterators. It 12375ffd83dbSDimitry Andric /// provides support for many different range functionalities, e.g. 12385ffd83dbSDimitry Andric /// drop_front/slice/etc.. Derived range classes must implement the following 12395ffd83dbSDimitry Andric /// static methods: 12405ffd83dbSDimitry Andric /// * ReferenceT dereference_iterator(const BaseT &base, ptrdiff_t index) 12415ffd83dbSDimitry Andric /// - Dereference an iterator pointing to the base object at the given 12425ffd83dbSDimitry Andric /// index. 12435ffd83dbSDimitry Andric /// * BaseT offset_base(const BaseT &base, ptrdiff_t index) 12445ffd83dbSDimitry Andric /// - Return a new base that is offset from the provide base by 'index' 12455ffd83dbSDimitry Andric /// elements. 12465ffd83dbSDimitry Andric template <typename DerivedT, typename BaseT, typename T, 12475ffd83dbSDimitry Andric typename PointerT = T *, typename ReferenceT = T &> 12485ffd83dbSDimitry Andric class indexed_accessor_range_base { 12495ffd83dbSDimitry Andric public: 1250349cc55cSDimitry Andric using RangeBaseT = indexed_accessor_range_base; 12515ffd83dbSDimitry Andric 12525ffd83dbSDimitry Andric /// An iterator element of this range. 12535ffd83dbSDimitry Andric class iterator : public indexed_accessor_iterator<iterator, BaseT, T, 12545ffd83dbSDimitry Andric PointerT, ReferenceT> { 12555ffd83dbSDimitry Andric public: 12565ffd83dbSDimitry Andric // Index into this iterator, invoking a static method on the derived type. 12575ffd83dbSDimitry Andric ReferenceT operator*() const { 12585ffd83dbSDimitry Andric return DerivedT::dereference_iterator(this->getBase(), this->getIndex()); 12595ffd83dbSDimitry Andric } 12605ffd83dbSDimitry Andric 12615ffd83dbSDimitry Andric private: 12625ffd83dbSDimitry Andric iterator(BaseT owner, ptrdiff_t curIndex) 1263349cc55cSDimitry Andric : iterator::indexed_accessor_iterator(owner, curIndex) {} 12645ffd83dbSDimitry Andric 12655ffd83dbSDimitry Andric /// Allow access to the constructor. 12665ffd83dbSDimitry Andric friend indexed_accessor_range_base<DerivedT, BaseT, T, PointerT, 12675ffd83dbSDimitry Andric ReferenceT>; 12685ffd83dbSDimitry Andric }; 12695ffd83dbSDimitry Andric 12705ffd83dbSDimitry Andric indexed_accessor_range_base(iterator begin, iterator end) 12715ffd83dbSDimitry Andric : base(offset_base(begin.getBase(), begin.getIndex())), 12725ffd83dbSDimitry Andric count(end.getIndex() - begin.getIndex()) {} 12735ffd83dbSDimitry Andric indexed_accessor_range_base(const iterator_range<iterator> &range) 12745ffd83dbSDimitry Andric : indexed_accessor_range_base(range.begin(), range.end()) {} 12755ffd83dbSDimitry Andric indexed_accessor_range_base(BaseT base, ptrdiff_t count) 12765ffd83dbSDimitry Andric : base(base), count(count) {} 12775ffd83dbSDimitry Andric 12785ffd83dbSDimitry Andric iterator begin() const { return iterator(base, 0); } 12795ffd83dbSDimitry Andric iterator end() const { return iterator(base, count); } 1280fe6060f1SDimitry Andric ReferenceT operator[](size_t Index) const { 1281fe6060f1SDimitry Andric assert(Index < size() && "invalid index for value range"); 1282fe6060f1SDimitry Andric return DerivedT::dereference_iterator(base, static_cast<ptrdiff_t>(Index)); 12835ffd83dbSDimitry Andric } 12845ffd83dbSDimitry Andric ReferenceT front() const { 12855ffd83dbSDimitry Andric assert(!empty() && "expected non-empty range"); 12865ffd83dbSDimitry Andric return (*this)[0]; 12875ffd83dbSDimitry Andric } 12885ffd83dbSDimitry Andric ReferenceT back() const { 12895ffd83dbSDimitry Andric assert(!empty() && "expected non-empty range"); 12905ffd83dbSDimitry Andric return (*this)[size() - 1]; 12915ffd83dbSDimitry Andric } 12925ffd83dbSDimitry Andric 12935ffd83dbSDimitry Andric /// Compare this range with another. 129481ad6265SDimitry Andric template <typename OtherT> 129581ad6265SDimitry Andric friend bool operator==(const indexed_accessor_range_base &lhs, 129681ad6265SDimitry Andric const OtherT &rhs) { 129781ad6265SDimitry Andric return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); 12985ffd83dbSDimitry Andric } 129981ad6265SDimitry Andric template <typename OtherT> 130081ad6265SDimitry Andric friend bool operator!=(const indexed_accessor_range_base &lhs, 130181ad6265SDimitry Andric const OtherT &rhs) { 130281ad6265SDimitry Andric return !(lhs == rhs); 13035ffd83dbSDimitry Andric } 13045ffd83dbSDimitry Andric 13055ffd83dbSDimitry Andric /// Return the size of this range. 13065ffd83dbSDimitry Andric size_t size() const { return count; } 13075ffd83dbSDimitry Andric 13085ffd83dbSDimitry Andric /// Return if the range is empty. 13095ffd83dbSDimitry Andric bool empty() const { return size() == 0; } 13105ffd83dbSDimitry Andric 13115ffd83dbSDimitry Andric /// Drop the first N elements, and keep M elements. 13125ffd83dbSDimitry Andric DerivedT slice(size_t n, size_t m) const { 13135ffd83dbSDimitry Andric assert(n + m <= size() && "invalid size specifiers"); 13145ffd83dbSDimitry Andric return DerivedT(offset_base(base, n), m); 13155ffd83dbSDimitry Andric } 13165ffd83dbSDimitry Andric 13175ffd83dbSDimitry Andric /// Drop the first n elements. 13185ffd83dbSDimitry Andric DerivedT drop_front(size_t n = 1) const { 13195ffd83dbSDimitry Andric assert(size() >= n && "Dropping more elements than exist"); 13205ffd83dbSDimitry Andric return slice(n, size() - n); 13215ffd83dbSDimitry Andric } 13225ffd83dbSDimitry Andric /// Drop the last n elements. 13235ffd83dbSDimitry Andric DerivedT drop_back(size_t n = 1) const { 13245ffd83dbSDimitry Andric assert(size() >= n && "Dropping more elements than exist"); 13255ffd83dbSDimitry Andric return DerivedT(base, size() - n); 13265ffd83dbSDimitry Andric } 13275ffd83dbSDimitry Andric 13285ffd83dbSDimitry Andric /// Take the first n elements. 13295ffd83dbSDimitry Andric DerivedT take_front(size_t n = 1) const { 13305ffd83dbSDimitry Andric return n < size() ? drop_back(size() - n) 13315ffd83dbSDimitry Andric : static_cast<const DerivedT &>(*this); 13325ffd83dbSDimitry Andric } 13335ffd83dbSDimitry Andric 13345ffd83dbSDimitry Andric /// Take the last n elements. 13355ffd83dbSDimitry Andric DerivedT take_back(size_t n = 1) const { 13365ffd83dbSDimitry Andric return n < size() ? drop_front(size() - n) 13375ffd83dbSDimitry Andric : static_cast<const DerivedT &>(*this); 13385ffd83dbSDimitry Andric } 13395ffd83dbSDimitry Andric 13405ffd83dbSDimitry Andric /// Allow conversion to any type accepting an iterator_range. 13415ffd83dbSDimitry Andric template <typename RangeT, typename = std::enable_if_t<std::is_constructible< 13425ffd83dbSDimitry Andric RangeT, iterator_range<iterator>>::value>> 13435ffd83dbSDimitry Andric operator RangeT() const { 13445ffd83dbSDimitry Andric return RangeT(iterator_range<iterator>(*this)); 13455ffd83dbSDimitry Andric } 13465ffd83dbSDimitry Andric 13475ffd83dbSDimitry Andric /// Returns the base of this range. 13485ffd83dbSDimitry Andric const BaseT &getBase() const { return base; } 13495ffd83dbSDimitry Andric 13505ffd83dbSDimitry Andric private: 13515ffd83dbSDimitry Andric /// Offset the given base by the given amount. 13525ffd83dbSDimitry Andric static BaseT offset_base(const BaseT &base, size_t n) { 13535ffd83dbSDimitry Andric return n == 0 ? base : DerivedT::offset_base(base, n); 13545ffd83dbSDimitry Andric } 13555ffd83dbSDimitry Andric 13565ffd83dbSDimitry Andric protected: 13575ffd83dbSDimitry Andric indexed_accessor_range_base(const indexed_accessor_range_base &) = default; 13585ffd83dbSDimitry Andric indexed_accessor_range_base(indexed_accessor_range_base &&) = default; 13595ffd83dbSDimitry Andric indexed_accessor_range_base & 13605ffd83dbSDimitry Andric operator=(const indexed_accessor_range_base &) = default; 13615ffd83dbSDimitry Andric 13625ffd83dbSDimitry Andric /// The base that owns the provided range of values. 13635ffd83dbSDimitry Andric BaseT base; 13645ffd83dbSDimitry Andric /// The size from the owning range. 13655ffd83dbSDimitry Andric ptrdiff_t count; 13665ffd83dbSDimitry Andric }; 13675ffd83dbSDimitry Andric } // end namespace detail 13685ffd83dbSDimitry Andric 13695ffd83dbSDimitry Andric /// This class provides an implementation of a range of 13705ffd83dbSDimitry Andric /// indexed_accessor_iterators where the base is not indexable. Ranges with 13715ffd83dbSDimitry Andric /// bases that are offsetable should derive from indexed_accessor_range_base 13725ffd83dbSDimitry Andric /// instead. Derived range classes are expected to implement the following 13735ffd83dbSDimitry Andric /// static method: 13745ffd83dbSDimitry Andric /// * ReferenceT dereference(const BaseT &base, ptrdiff_t index) 13755ffd83dbSDimitry Andric /// - Dereference an iterator pointing to a parent base at the given index. 13765ffd83dbSDimitry Andric template <typename DerivedT, typename BaseT, typename T, 13775ffd83dbSDimitry Andric typename PointerT = T *, typename ReferenceT = T &> 13785ffd83dbSDimitry Andric class indexed_accessor_range 13795ffd83dbSDimitry Andric : public detail::indexed_accessor_range_base< 13805ffd83dbSDimitry Andric DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT> { 13815ffd83dbSDimitry Andric public: 13825ffd83dbSDimitry Andric indexed_accessor_range(BaseT base, ptrdiff_t startIndex, ptrdiff_t count) 13835ffd83dbSDimitry Andric : detail::indexed_accessor_range_base< 13845ffd83dbSDimitry Andric DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT>( 13855ffd83dbSDimitry Andric std::make_pair(base, startIndex), count) {} 13865ffd83dbSDimitry Andric using detail::indexed_accessor_range_base< 13875ffd83dbSDimitry Andric DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, 13885ffd83dbSDimitry Andric ReferenceT>::indexed_accessor_range_base; 13895ffd83dbSDimitry Andric 13905ffd83dbSDimitry Andric /// Returns the current base of the range. 13915ffd83dbSDimitry Andric const BaseT &getBase() const { return this->base.first; } 13925ffd83dbSDimitry Andric 13935ffd83dbSDimitry Andric /// Returns the current start index of the range. 13945ffd83dbSDimitry Andric ptrdiff_t getStartIndex() const { return this->base.second; } 13955ffd83dbSDimitry Andric 13965ffd83dbSDimitry Andric /// See `detail::indexed_accessor_range_base` for details. 13975ffd83dbSDimitry Andric static std::pair<BaseT, ptrdiff_t> 13985ffd83dbSDimitry Andric offset_base(const std::pair<BaseT, ptrdiff_t> &base, ptrdiff_t index) { 13995ffd83dbSDimitry Andric // We encode the internal base as a pair of the derived base and a start 14005ffd83dbSDimitry Andric // index into the derived base. 14015ffd83dbSDimitry Andric return std::make_pair(base.first, base.second + index); 14025ffd83dbSDimitry Andric } 14035ffd83dbSDimitry Andric /// See `detail::indexed_accessor_range_base` for details. 14045ffd83dbSDimitry Andric static ReferenceT 14055ffd83dbSDimitry Andric dereference_iterator(const std::pair<BaseT, ptrdiff_t> &base, 14065ffd83dbSDimitry Andric ptrdiff_t index) { 14075ffd83dbSDimitry Andric return DerivedT::dereference(base.first, base.second + index); 14085ffd83dbSDimitry Andric } 14095ffd83dbSDimitry Andric }; 14105ffd83dbSDimitry Andric 1411349cc55cSDimitry Andric namespace detail { 1412349cc55cSDimitry Andric /// Return a reference to the first or second member of a reference. Otherwise, 1413349cc55cSDimitry Andric /// return a copy of the member of a temporary. 1414349cc55cSDimitry Andric /// 1415349cc55cSDimitry Andric /// When passing a range whose iterators return values instead of references, 1416349cc55cSDimitry Andric /// the reference must be dropped from `decltype((elt.first))`, which will 1417349cc55cSDimitry Andric /// always be a reference, to avoid returning a reference to a temporary. 1418349cc55cSDimitry Andric template <typename EltTy, typename FirstTy> class first_or_second_type { 1419349cc55cSDimitry Andric public: 1420bdd1243dSDimitry Andric using type = std::conditional_t<std::is_reference<EltTy>::value, FirstTy, 1421349cc55cSDimitry Andric std::remove_reference_t<FirstTy>>; 1422349cc55cSDimitry Andric }; 1423349cc55cSDimitry Andric } // end namespace detail 1424349cc55cSDimitry Andric 1425e8d8bef9SDimitry Andric /// Given a container of pairs, return a range over the first elements. 1426e8d8bef9SDimitry Andric template <typename ContainerTy> auto make_first_range(ContainerTy &&c) { 1427349cc55cSDimitry Andric using EltTy = decltype((*std::begin(c))); 1428349cc55cSDimitry Andric return llvm::map_range(std::forward<ContainerTy>(c), 1429349cc55cSDimitry Andric [](EltTy elt) -> typename detail::first_or_second_type< 1430349cc55cSDimitry Andric EltTy, decltype((elt.first))>::type { 1431e8d8bef9SDimitry Andric return elt.first; 1432e8d8bef9SDimitry Andric }); 1433e8d8bef9SDimitry Andric } 1434e8d8bef9SDimitry Andric 14355ffd83dbSDimitry Andric /// Given a container of pairs, return a range over the second elements. 14365ffd83dbSDimitry Andric template <typename ContainerTy> auto make_second_range(ContainerTy &&c) { 1437349cc55cSDimitry Andric using EltTy = decltype((*std::begin(c))); 14385ffd83dbSDimitry Andric return llvm::map_range( 14395ffd83dbSDimitry Andric std::forward<ContainerTy>(c), 1440349cc55cSDimitry Andric [](EltTy elt) -> 1441349cc55cSDimitry Andric typename detail::first_or_second_type<EltTy, 1442349cc55cSDimitry Andric decltype((elt.second))>::type { 14435ffd83dbSDimitry Andric return elt.second; 14445ffd83dbSDimitry Andric }); 14455ffd83dbSDimitry Andric } 14465ffd83dbSDimitry Andric 14470b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 14480b57cec5SDimitry Andric // Extra additions to <utility> 14490b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 14500b57cec5SDimitry Andric 145106c3fb27SDimitry Andric /// Function object to check whether the first component of a container 145206c3fb27SDimitry Andric /// supported by std::get (like std::pair and std::tuple) compares less than the 145306c3fb27SDimitry Andric /// first component of another container. 14540b57cec5SDimitry Andric struct less_first { 14550b57cec5SDimitry Andric template <typename T> bool operator()(const T &lhs, const T &rhs) const { 145606c3fb27SDimitry Andric return std::less<>()(std::get<0>(lhs), std::get<0>(rhs)); 14570b57cec5SDimitry Andric } 14580b57cec5SDimitry Andric }; 14590b57cec5SDimitry Andric 146006c3fb27SDimitry Andric /// Function object to check whether the second component of a container 146106c3fb27SDimitry Andric /// supported by std::get (like std::pair and std::tuple) compares less than the 146206c3fb27SDimitry Andric /// second component of another container. 14630b57cec5SDimitry Andric struct less_second { 14640b57cec5SDimitry Andric template <typename T> bool operator()(const T &lhs, const T &rhs) const { 146506c3fb27SDimitry Andric return std::less<>()(std::get<1>(lhs), std::get<1>(rhs)); 14660b57cec5SDimitry Andric } 14670b57cec5SDimitry Andric }; 14680b57cec5SDimitry Andric 14690b57cec5SDimitry Andric /// \brief Function object to apply a binary function to the first component of 14700b57cec5SDimitry Andric /// a std::pair. 14710b57cec5SDimitry Andric template<typename FuncTy> 14720b57cec5SDimitry Andric struct on_first { 14730b57cec5SDimitry Andric FuncTy func; 14740b57cec5SDimitry Andric 14750b57cec5SDimitry Andric template <typename T> 14765ffd83dbSDimitry Andric decltype(auto) operator()(const T &lhs, const T &rhs) const { 14770b57cec5SDimitry Andric return func(lhs.first, rhs.first); 14780b57cec5SDimitry Andric } 14790b57cec5SDimitry Andric }; 14800b57cec5SDimitry Andric 14810b57cec5SDimitry Andric /// Utility type to build an inheritance chain that makes it easy to rank 14820b57cec5SDimitry Andric /// overload candidates. 14830b57cec5SDimitry Andric template <int N> struct rank : rank<N - 1> {}; 14840b57cec5SDimitry Andric template <> struct rank<0> {}; 14850b57cec5SDimitry Andric 1486fe6060f1SDimitry Andric namespace detail { 1487fe6060f1SDimitry Andric template <typename... Ts> struct Visitor; 1488fe6060f1SDimitry Andric 1489fe6060f1SDimitry Andric template <typename HeadT, typename... TailTs> 1490fe6060f1SDimitry Andric struct Visitor<HeadT, TailTs...> : remove_cvref_t<HeadT>, Visitor<TailTs...> { 1491fe6060f1SDimitry Andric explicit constexpr Visitor(HeadT &&Head, TailTs &&...Tail) 1492fe6060f1SDimitry Andric : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)), 1493fe6060f1SDimitry Andric Visitor<TailTs...>(std::forward<TailTs>(Tail)...) {} 1494fe6060f1SDimitry Andric using remove_cvref_t<HeadT>::operator(); 1495fe6060f1SDimitry Andric using Visitor<TailTs...>::operator(); 14960b57cec5SDimitry Andric }; 14970b57cec5SDimitry Andric 1498fe6060f1SDimitry Andric template <typename HeadT> struct Visitor<HeadT> : remove_cvref_t<HeadT> { 1499fe6060f1SDimitry Andric explicit constexpr Visitor(HeadT &&Head) 1500fe6060f1SDimitry Andric : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)) {} 1501fe6060f1SDimitry Andric using remove_cvref_t<HeadT>::operator(); 15020b57cec5SDimitry Andric }; 1503fe6060f1SDimitry Andric } // namespace detail 1504fe6060f1SDimitry Andric 1505fe6060f1SDimitry Andric /// Returns an opaquely-typed Callable object whose operator() overload set is 1506fe6060f1SDimitry Andric /// the sum of the operator() overload sets of each CallableT in CallableTs. 1507fe6060f1SDimitry Andric /// 1508fe6060f1SDimitry Andric /// The type of the returned object derives from each CallableT in CallableTs. 1509fe6060f1SDimitry Andric /// The returned object is constructed by invoking the appropriate copy or move 1510fe6060f1SDimitry Andric /// constructor of each CallableT, as selected by overload resolution on the 1511fe6060f1SDimitry Andric /// corresponding argument to makeVisitor. 1512fe6060f1SDimitry Andric /// 1513fe6060f1SDimitry Andric /// Example: 1514fe6060f1SDimitry Andric /// 1515fe6060f1SDimitry Andric /// \code 1516fe6060f1SDimitry Andric /// auto visitor = makeVisitor([](auto) { return "unhandled type"; }, 1517fe6060f1SDimitry Andric /// [](int i) { return "int"; }, 1518fe6060f1SDimitry Andric /// [](std::string s) { return "str"; }); 1519fe6060f1SDimitry Andric /// auto a = visitor(42); // `a` is now "int". 1520fe6060f1SDimitry Andric /// auto b = visitor("foo"); // `b` is now "str". 1521fe6060f1SDimitry Andric /// auto c = visitor(3.14f); // `c` is now "unhandled type". 1522fe6060f1SDimitry Andric /// \endcode 1523fe6060f1SDimitry Andric /// 1524fe6060f1SDimitry Andric /// Example of making a visitor with a lambda which captures a move-only type: 1525fe6060f1SDimitry Andric /// 1526fe6060f1SDimitry Andric /// \code 1527fe6060f1SDimitry Andric /// std::unique_ptr<FooHandler> FH = /* ... */; 1528fe6060f1SDimitry Andric /// auto visitor = makeVisitor( 1529fe6060f1SDimitry Andric /// [FH{std::move(FH)}](Foo F) { return FH->handle(F); }, 1530fe6060f1SDimitry Andric /// [](int i) { return i; }, 1531fe6060f1SDimitry Andric /// [](std::string s) { return atoi(s); }); 1532fe6060f1SDimitry Andric /// \endcode 1533fe6060f1SDimitry Andric template <typename... CallableTs> 1534fe6060f1SDimitry Andric constexpr decltype(auto) makeVisitor(CallableTs &&...Callables) { 1535fe6060f1SDimitry Andric return detail::Visitor<CallableTs...>(std::forward<CallableTs>(Callables)...); 1536fe6060f1SDimitry Andric } 15370b57cec5SDimitry Andric 15380b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 15391fd87a68SDimitry Andric // Extra additions to <algorithm> 15400b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 15410b57cec5SDimitry Andric 15425ffd83dbSDimitry Andric // We have a copy here so that LLVM behaves the same when using different 15435ffd83dbSDimitry Andric // standard libraries. 15445ffd83dbSDimitry Andric template <class Iterator, class RNG> 15455ffd83dbSDimitry Andric void shuffle(Iterator first, Iterator last, RNG &&g) { 15465ffd83dbSDimitry Andric // It would be better to use a std::uniform_int_distribution, 15475ffd83dbSDimitry Andric // but that would be stdlib dependent. 1548fe6060f1SDimitry Andric typedef 1549fe6060f1SDimitry Andric typename std::iterator_traits<Iterator>::difference_type difference_type; 1550fe6060f1SDimitry Andric for (auto size = last - first; size > 1; ++first, (void)--size) { 1551fe6060f1SDimitry Andric difference_type offset = g() % size; 1552fe6060f1SDimitry Andric // Avoid self-assignment due to incorrect assertions in libstdc++ 1553fe6060f1SDimitry Andric // containers (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85828). 1554fe6060f1SDimitry Andric if (offset != difference_type(0)) 1555fe6060f1SDimitry Andric std::iter_swap(first, first + offset); 1556fe6060f1SDimitry Andric } 15575ffd83dbSDimitry Andric } 15585ffd83dbSDimitry Andric 15590b57cec5SDimitry Andric /// Adapt std::less<T> for array_pod_sort. 15600b57cec5SDimitry Andric template<typename T> 15610b57cec5SDimitry Andric inline int array_pod_sort_comparator(const void *P1, const void *P2) { 15620b57cec5SDimitry Andric if (std::less<T>()(*reinterpret_cast<const T*>(P1), 15630b57cec5SDimitry Andric *reinterpret_cast<const T*>(P2))) 15640b57cec5SDimitry Andric return -1; 15650b57cec5SDimitry Andric if (std::less<T>()(*reinterpret_cast<const T*>(P2), 15660b57cec5SDimitry Andric *reinterpret_cast<const T*>(P1))) 15670b57cec5SDimitry Andric return 1; 15680b57cec5SDimitry Andric return 0; 15690b57cec5SDimitry Andric } 15700b57cec5SDimitry Andric 15710b57cec5SDimitry Andric /// get_array_pod_sort_comparator - This is an internal helper function used to 15720b57cec5SDimitry Andric /// get type deduction of T right. 15730b57cec5SDimitry Andric template<typename T> 15740b57cec5SDimitry Andric inline int (*get_array_pod_sort_comparator(const T &)) 15750b57cec5SDimitry Andric (const void*, const void*) { 15760b57cec5SDimitry Andric return array_pod_sort_comparator<T>; 15770b57cec5SDimitry Andric } 15780b57cec5SDimitry Andric 1579480093f4SDimitry Andric #ifdef EXPENSIVE_CHECKS 1580480093f4SDimitry Andric namespace detail { 1581480093f4SDimitry Andric 1582480093f4SDimitry Andric inline unsigned presortShuffleEntropy() { 1583480093f4SDimitry Andric static unsigned Result(std::random_device{}()); 1584480093f4SDimitry Andric return Result; 1585480093f4SDimitry Andric } 1586480093f4SDimitry Andric 1587480093f4SDimitry Andric template <class IteratorTy> 1588480093f4SDimitry Andric inline void presortShuffle(IteratorTy Start, IteratorTy End) { 1589480093f4SDimitry Andric std::mt19937 Generator(presortShuffleEntropy()); 1590fe6060f1SDimitry Andric llvm::shuffle(Start, End, Generator); 1591480093f4SDimitry Andric } 1592480093f4SDimitry Andric 1593480093f4SDimitry Andric } // end namespace detail 1594480093f4SDimitry Andric #endif 1595480093f4SDimitry Andric 15960b57cec5SDimitry Andric /// array_pod_sort - This sorts an array with the specified start and end 15970b57cec5SDimitry Andric /// extent. This is just like std::sort, except that it calls qsort instead of 15980b57cec5SDimitry Andric /// using an inlined template. qsort is slightly slower than std::sort, but 15990b57cec5SDimitry Andric /// most sorts are not performance critical in LLVM and std::sort has to be 16000b57cec5SDimitry Andric /// template instantiated for each type, leading to significant measured code 16010b57cec5SDimitry Andric /// bloat. This function should generally be used instead of std::sort where 16020b57cec5SDimitry Andric /// possible. 16030b57cec5SDimitry Andric /// 16040b57cec5SDimitry Andric /// This function assumes that you have simple POD-like types that can be 16050b57cec5SDimitry Andric /// compared with std::less and can be moved with memcpy. If this isn't true, 16060b57cec5SDimitry Andric /// you should use std::sort. 16070b57cec5SDimitry Andric /// 16080b57cec5SDimitry Andric /// NOTE: If qsort_r were portable, we could allow a custom comparator and 16090b57cec5SDimitry Andric /// default to std::less. 16100b57cec5SDimitry Andric template<class IteratorTy> 16110b57cec5SDimitry Andric inline void array_pod_sort(IteratorTy Start, IteratorTy End) { 16120b57cec5SDimitry Andric // Don't inefficiently call qsort with one element or trigger undefined 16130b57cec5SDimitry Andric // behavior with an empty sequence. 16140b57cec5SDimitry Andric auto NElts = End - Start; 16150b57cec5SDimitry Andric if (NElts <= 1) return; 16160b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS 1617480093f4SDimitry Andric detail::presortShuffle<IteratorTy>(Start, End); 16180b57cec5SDimitry Andric #endif 16190b57cec5SDimitry Andric qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start)); 16200b57cec5SDimitry Andric } 16210b57cec5SDimitry Andric 16220b57cec5SDimitry Andric template <class IteratorTy> 16230b57cec5SDimitry Andric inline void array_pod_sort( 16240b57cec5SDimitry Andric IteratorTy Start, IteratorTy End, 16250b57cec5SDimitry Andric int (*Compare)( 16260b57cec5SDimitry Andric const typename std::iterator_traits<IteratorTy>::value_type *, 16270b57cec5SDimitry Andric const typename std::iterator_traits<IteratorTy>::value_type *)) { 16280b57cec5SDimitry Andric // Don't inefficiently call qsort with one element or trigger undefined 16290b57cec5SDimitry Andric // behavior with an empty sequence. 16300b57cec5SDimitry Andric auto NElts = End - Start; 16310b57cec5SDimitry Andric if (NElts <= 1) return; 16320b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS 1633480093f4SDimitry Andric detail::presortShuffle<IteratorTy>(Start, End); 16340b57cec5SDimitry Andric #endif 16350b57cec5SDimitry Andric qsort(&*Start, NElts, sizeof(*Start), 16360b57cec5SDimitry Andric reinterpret_cast<int (*)(const void *, const void *)>(Compare)); 16370b57cec5SDimitry Andric } 16380b57cec5SDimitry Andric 16395ffd83dbSDimitry Andric namespace detail { 16405ffd83dbSDimitry Andric template <typename T> 16415ffd83dbSDimitry Andric // We can use qsort if the iterator type is a pointer and the underlying value 16425ffd83dbSDimitry Andric // is trivially copyable. 1643bdd1243dSDimitry Andric using sort_trivially_copyable = std::conjunction< 16445ffd83dbSDimitry Andric std::is_pointer<T>, 1645e8d8bef9SDimitry Andric std::is_trivially_copyable<typename std::iterator_traits<T>::value_type>>; 16465ffd83dbSDimitry Andric } // namespace detail 16475ffd83dbSDimitry Andric 16480b57cec5SDimitry Andric // Provide wrappers to std::sort which shuffle the elements before sorting 16490b57cec5SDimitry Andric // to help uncover non-deterministic behavior (PR35135). 1650bdd1243dSDimitry Andric template <typename IteratorTy> 16510b57cec5SDimitry Andric inline void sort(IteratorTy Start, IteratorTy End) { 1652bdd1243dSDimitry Andric if constexpr (detail::sort_trivially_copyable<IteratorTy>::value) { 1653bdd1243dSDimitry Andric // Forward trivially copyable types to array_pod_sort. This avoids a large 1654bdd1243dSDimitry Andric // amount of code bloat for a minor performance hit. 1655bdd1243dSDimitry Andric array_pod_sort(Start, End); 1656bdd1243dSDimitry Andric } else { 16570b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS 1658480093f4SDimitry Andric detail::presortShuffle<IteratorTy>(Start, End); 16590b57cec5SDimitry Andric #endif 16600b57cec5SDimitry Andric std::sort(Start, End); 16610b57cec5SDimitry Andric } 16625ffd83dbSDimitry Andric } 16635ffd83dbSDimitry Andric 16640b57cec5SDimitry Andric template <typename Container> inline void sort(Container &&C) { 16650b57cec5SDimitry Andric llvm::sort(adl_begin(C), adl_end(C)); 16660b57cec5SDimitry Andric } 16670b57cec5SDimitry Andric 16680b57cec5SDimitry Andric template <typename IteratorTy, typename Compare> 16690b57cec5SDimitry Andric inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) { 16700b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS 1671480093f4SDimitry Andric detail::presortShuffle<IteratorTy>(Start, End); 16720b57cec5SDimitry Andric #endif 16730b57cec5SDimitry Andric std::sort(Start, End, Comp); 16740b57cec5SDimitry Andric } 16750b57cec5SDimitry Andric 16760b57cec5SDimitry Andric template <typename Container, typename Compare> 16770b57cec5SDimitry Andric inline void sort(Container &&C, Compare Comp) { 16780b57cec5SDimitry Andric llvm::sort(adl_begin(C), adl_end(C), Comp); 16790b57cec5SDimitry Andric } 16800b57cec5SDimitry Andric 16810b57cec5SDimitry Andric /// Get the size of a range. This is a wrapper function around std::distance 16820b57cec5SDimitry Andric /// which is only enabled when the operation is O(1). 16830b57cec5SDimitry Andric template <typename R> 16845ffd83dbSDimitry Andric auto size(R &&Range, 1685e8d8bef9SDimitry Andric std::enable_if_t< 1686e8d8bef9SDimitry Andric std::is_base_of<std::random_access_iterator_tag, 1687e8d8bef9SDimitry Andric typename std::iterator_traits<decltype( 1688e8d8bef9SDimitry Andric Range.begin())>::iterator_category>::value, 16895ffd83dbSDimitry Andric void> * = nullptr) { 16900b57cec5SDimitry Andric return std::distance(Range.begin(), Range.end()); 16910b57cec5SDimitry Andric } 16920b57cec5SDimitry Andric 169306c3fb27SDimitry Andric namespace detail { 169406c3fb27SDimitry Andric template <typename Range> 169506c3fb27SDimitry Andric using check_has_free_function_size = 169606c3fb27SDimitry Andric decltype(adl_size(std::declval<Range &>())); 169706c3fb27SDimitry Andric 169806c3fb27SDimitry Andric template <typename Range> 169906c3fb27SDimitry Andric static constexpr bool HasFreeFunctionSize = 170006c3fb27SDimitry Andric is_detected<check_has_free_function_size, Range>::value; 170106c3fb27SDimitry Andric } // namespace detail 170206c3fb27SDimitry Andric 170306c3fb27SDimitry Andric /// Returns the size of the \p Range, i.e., the number of elements. This 170406c3fb27SDimitry Andric /// implementation takes inspiration from `std::ranges::size` from C++20 and 170506c3fb27SDimitry Andric /// delegates the size check to `adl_size` or `std::distance`, in this order of 170606c3fb27SDimitry Andric /// preference. Unlike `llvm::size`, this function does *not* guarantee O(1) 170706c3fb27SDimitry Andric /// running time, and is intended to be used in generic code that does not know 170806c3fb27SDimitry Andric /// the exact range type. 170906c3fb27SDimitry Andric template <typename R> constexpr size_t range_size(R &&Range) { 171006c3fb27SDimitry Andric if constexpr (detail::HasFreeFunctionSize<R>) 171106c3fb27SDimitry Andric return adl_size(Range); 171206c3fb27SDimitry Andric else 171306c3fb27SDimitry Andric return static_cast<size_t>(std::distance(adl_begin(Range), adl_end(Range))); 171406c3fb27SDimitry Andric } 171506c3fb27SDimitry Andric 17160b57cec5SDimitry Andric /// Provide wrappers to std::for_each which take ranges instead of having to 17170b57cec5SDimitry Andric /// pass begin/end explicitly. 1718e8d8bef9SDimitry Andric template <typename R, typename UnaryFunction> 1719e8d8bef9SDimitry Andric UnaryFunction for_each(R &&Range, UnaryFunction F) { 1720e8d8bef9SDimitry Andric return std::for_each(adl_begin(Range), adl_end(Range), F); 17210b57cec5SDimitry Andric } 17220b57cec5SDimitry Andric 17230b57cec5SDimitry Andric /// Provide wrappers to std::all_of which take ranges instead of having to pass 17240b57cec5SDimitry Andric /// begin/end explicitly. 17250b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 17260b57cec5SDimitry Andric bool all_of(R &&Range, UnaryPredicate P) { 17270b57cec5SDimitry Andric return std::all_of(adl_begin(Range), adl_end(Range), P); 17280b57cec5SDimitry Andric } 17290b57cec5SDimitry Andric 17300b57cec5SDimitry Andric /// Provide wrappers to std::any_of which take ranges instead of having to pass 17310b57cec5SDimitry Andric /// begin/end explicitly. 17320b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 17330b57cec5SDimitry Andric bool any_of(R &&Range, UnaryPredicate P) { 17340b57cec5SDimitry Andric return std::any_of(adl_begin(Range), adl_end(Range), P); 17350b57cec5SDimitry Andric } 17360b57cec5SDimitry Andric 17370b57cec5SDimitry Andric /// Provide wrappers to std::none_of which take ranges instead of having to pass 17380b57cec5SDimitry Andric /// begin/end explicitly. 17390b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 17400b57cec5SDimitry Andric bool none_of(R &&Range, UnaryPredicate P) { 17410b57cec5SDimitry Andric return std::none_of(adl_begin(Range), adl_end(Range), P); 17420b57cec5SDimitry Andric } 17430b57cec5SDimitry Andric 17440b57cec5SDimitry Andric /// Provide wrappers to std::find which take ranges instead of having to pass 17450b57cec5SDimitry Andric /// begin/end explicitly. 17465ffd83dbSDimitry Andric template <typename R, typename T> auto find(R &&Range, const T &Val) { 17470b57cec5SDimitry Andric return std::find(adl_begin(Range), adl_end(Range), Val); 17480b57cec5SDimitry Andric } 17490b57cec5SDimitry Andric 17500b57cec5SDimitry Andric /// Provide wrappers to std::find_if which take ranges instead of having to pass 17510b57cec5SDimitry Andric /// begin/end explicitly. 17520b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 17535ffd83dbSDimitry Andric auto find_if(R &&Range, UnaryPredicate P) { 17540b57cec5SDimitry Andric return std::find_if(adl_begin(Range), adl_end(Range), P); 17550b57cec5SDimitry Andric } 17560b57cec5SDimitry Andric 17570b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 17585ffd83dbSDimitry Andric auto find_if_not(R &&Range, UnaryPredicate P) { 17590b57cec5SDimitry Andric return std::find_if_not(adl_begin(Range), adl_end(Range), P); 17600b57cec5SDimitry Andric } 17610b57cec5SDimitry Andric 17620b57cec5SDimitry Andric /// Provide wrappers to std::remove_if which take ranges instead of having to 17630b57cec5SDimitry Andric /// pass begin/end explicitly. 17640b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 17655ffd83dbSDimitry Andric auto remove_if(R &&Range, UnaryPredicate P) { 17660b57cec5SDimitry Andric return std::remove_if(adl_begin(Range), adl_end(Range), P); 17670b57cec5SDimitry Andric } 17680b57cec5SDimitry Andric 17690b57cec5SDimitry Andric /// Provide wrappers to std::copy_if which take ranges instead of having to 17700b57cec5SDimitry Andric /// pass begin/end explicitly. 17710b57cec5SDimitry Andric template <typename R, typename OutputIt, typename UnaryPredicate> 17720b57cec5SDimitry Andric OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) { 17730b57cec5SDimitry Andric return std::copy_if(adl_begin(Range), adl_end(Range), Out, P); 17740b57cec5SDimitry Andric } 17750b57cec5SDimitry Andric 1776bdd1243dSDimitry Andric /// Return the single value in \p Range that satisfies 1777bdd1243dSDimitry Andric /// \p P(<member of \p Range> *, AllowRepeats)->T * returning nullptr 1778bdd1243dSDimitry Andric /// when no values or multiple values were found. 1779bdd1243dSDimitry Andric /// When \p AllowRepeats is true, multiple values that compare equal 1780bdd1243dSDimitry Andric /// are allowed. 1781bdd1243dSDimitry Andric template <typename T, typename R, typename Predicate> 1782bdd1243dSDimitry Andric T *find_singleton(R &&Range, Predicate P, bool AllowRepeats = false) { 1783bdd1243dSDimitry Andric T *RC = nullptr; 1784*5f757f3fSDimitry Andric for (auto &&A : Range) { 1785bdd1243dSDimitry Andric if (T *PRC = P(A, AllowRepeats)) { 1786bdd1243dSDimitry Andric if (RC) { 1787bdd1243dSDimitry Andric if (!AllowRepeats || PRC != RC) 1788bdd1243dSDimitry Andric return nullptr; 1789bdd1243dSDimitry Andric } else 1790bdd1243dSDimitry Andric RC = PRC; 1791bdd1243dSDimitry Andric } 1792bdd1243dSDimitry Andric } 1793bdd1243dSDimitry Andric return RC; 1794bdd1243dSDimitry Andric } 1795bdd1243dSDimitry Andric 1796bdd1243dSDimitry Andric /// Return a pair consisting of the single value in \p Range that satisfies 1797bdd1243dSDimitry Andric /// \p P(<member of \p Range> *, AllowRepeats)->std::pair<T*, bool> returning 1798bdd1243dSDimitry Andric /// nullptr when no values or multiple values were found, and a bool indicating 1799bdd1243dSDimitry Andric /// whether multiple values were found to cause the nullptr. 1800bdd1243dSDimitry Andric /// When \p AllowRepeats is true, multiple values that compare equal are 1801bdd1243dSDimitry Andric /// allowed. The predicate \p P returns a pair<T *, bool> where T is the 1802bdd1243dSDimitry Andric /// singleton while the bool indicates whether multiples have already been 1803bdd1243dSDimitry Andric /// found. It is expected that first will be nullptr when second is true. 1804bdd1243dSDimitry Andric /// This allows using find_singleton_nested within the predicate \P. 1805bdd1243dSDimitry Andric template <typename T, typename R, typename Predicate> 1806bdd1243dSDimitry Andric std::pair<T *, bool> find_singleton_nested(R &&Range, Predicate P, 1807bdd1243dSDimitry Andric bool AllowRepeats = false) { 1808bdd1243dSDimitry Andric T *RC = nullptr; 1809bdd1243dSDimitry Andric for (auto *A : Range) { 1810bdd1243dSDimitry Andric std::pair<T *, bool> PRC = P(A, AllowRepeats); 1811bdd1243dSDimitry Andric if (PRC.second) { 1812bdd1243dSDimitry Andric assert(PRC.first == nullptr && 1813bdd1243dSDimitry Andric "Inconsistent return values in find_singleton_nested."); 1814bdd1243dSDimitry Andric return PRC; 1815bdd1243dSDimitry Andric } 1816bdd1243dSDimitry Andric if (PRC.first) { 1817bdd1243dSDimitry Andric if (RC) { 1818bdd1243dSDimitry Andric if (!AllowRepeats || PRC.first != RC) 1819bdd1243dSDimitry Andric return {nullptr, true}; 1820bdd1243dSDimitry Andric } else 1821bdd1243dSDimitry Andric RC = PRC.first; 1822bdd1243dSDimitry Andric } 1823bdd1243dSDimitry Andric } 1824bdd1243dSDimitry Andric return {RC, false}; 1825bdd1243dSDimitry Andric } 1826bdd1243dSDimitry Andric 18270b57cec5SDimitry Andric template <typename R, typename OutputIt> 18280b57cec5SDimitry Andric OutputIt copy(R &&Range, OutputIt Out) { 18290b57cec5SDimitry Andric return std::copy(adl_begin(Range), adl_end(Range), Out); 18300b57cec5SDimitry Andric } 18310b57cec5SDimitry Andric 1832bdd1243dSDimitry Andric /// Provide wrappers to std::replace_copy_if which take ranges instead of having 1833bdd1243dSDimitry Andric /// to pass begin/end explicitly. 1834bdd1243dSDimitry Andric template <typename R, typename OutputIt, typename UnaryPredicate, typename T> 1835bdd1243dSDimitry Andric OutputIt replace_copy_if(R &&Range, OutputIt Out, UnaryPredicate P, 1836bdd1243dSDimitry Andric const T &NewValue) { 1837bdd1243dSDimitry Andric return std::replace_copy_if(adl_begin(Range), adl_end(Range), Out, P, 1838bdd1243dSDimitry Andric NewValue); 1839bdd1243dSDimitry Andric } 1840bdd1243dSDimitry Andric 1841bdd1243dSDimitry Andric /// Provide wrappers to std::replace_copy which take ranges instead of having to 1842bdd1243dSDimitry Andric /// pass begin/end explicitly. 1843bdd1243dSDimitry Andric template <typename R, typename OutputIt, typename T> 1844bdd1243dSDimitry Andric OutputIt replace_copy(R &&Range, OutputIt Out, const T &OldValue, 1845bdd1243dSDimitry Andric const T &NewValue) { 1846bdd1243dSDimitry Andric return std::replace_copy(adl_begin(Range), adl_end(Range), Out, OldValue, 1847bdd1243dSDimitry Andric NewValue); 1848bdd1243dSDimitry Andric } 1849bdd1243dSDimitry Andric 1850e8d8bef9SDimitry Andric /// Provide wrappers to std::move which take ranges instead of having to 1851e8d8bef9SDimitry Andric /// pass begin/end explicitly. 1852e8d8bef9SDimitry Andric template <typename R, typename OutputIt> 1853e8d8bef9SDimitry Andric OutputIt move(R &&Range, OutputIt Out) { 1854e8d8bef9SDimitry Andric return std::move(adl_begin(Range), adl_end(Range), Out); 1855e8d8bef9SDimitry Andric } 1856e8d8bef9SDimitry Andric 185706c3fb27SDimitry Andric namespace detail { 185806c3fb27SDimitry Andric template <typename Range, typename Element> 185906c3fb27SDimitry Andric using check_has_member_contains_t = 186006c3fb27SDimitry Andric decltype(std::declval<Range &>().contains(std::declval<const Element &>())); 186106c3fb27SDimitry Andric 186206c3fb27SDimitry Andric template <typename Range, typename Element> 186306c3fb27SDimitry Andric static constexpr bool HasMemberContains = 186406c3fb27SDimitry Andric is_detected<check_has_member_contains_t, Range, Element>::value; 186506c3fb27SDimitry Andric 186606c3fb27SDimitry Andric template <typename Range, typename Element> 186706c3fb27SDimitry Andric using check_has_member_find_t = 186806c3fb27SDimitry Andric decltype(std::declval<Range &>().find(std::declval<const Element &>()) != 186906c3fb27SDimitry Andric std::declval<Range &>().end()); 187006c3fb27SDimitry Andric 187106c3fb27SDimitry Andric template <typename Range, typename Element> 187206c3fb27SDimitry Andric static constexpr bool HasMemberFind = 187306c3fb27SDimitry Andric is_detected<check_has_member_find_t, Range, Element>::value; 187406c3fb27SDimitry Andric 187506c3fb27SDimitry Andric } // namespace detail 187606c3fb27SDimitry Andric 187706c3fb27SDimitry Andric /// Returns true if \p Element is found in \p Range. Delegates the check to 187806c3fb27SDimitry Andric /// either `.contains(Element)`, `.find(Element)`, or `std::find`, in this 187906c3fb27SDimitry Andric /// order of preference. This is intended as the canonical way to check if an 188006c3fb27SDimitry Andric /// element exists in a range in generic code or range type that does not 188106c3fb27SDimitry Andric /// expose a `.contains(Element)` member. 18820b57cec5SDimitry Andric template <typename R, typename E> 18830b57cec5SDimitry Andric bool is_contained(R &&Range, const E &Element) { 188406c3fb27SDimitry Andric if constexpr (detail::HasMemberContains<R, E>) 188506c3fb27SDimitry Andric return Range.contains(Element); 188606c3fb27SDimitry Andric else if constexpr (detail::HasMemberFind<R, E>) 188706c3fb27SDimitry Andric return Range.find(Element) != Range.end(); 188806c3fb27SDimitry Andric else 188906c3fb27SDimitry Andric return std::find(adl_begin(Range), adl_end(Range), Element) != 189006c3fb27SDimitry Andric adl_end(Range); 18910b57cec5SDimitry Andric } 18920b57cec5SDimitry Andric 189306c3fb27SDimitry Andric /// Returns true iff \p Element exists in \p Set. This overload takes \p Set as 189406c3fb27SDimitry Andric /// an initializer list and is `constexpr`-friendly. 189506c3fb27SDimitry Andric template <typename T, typename E> 189606c3fb27SDimitry Andric constexpr bool is_contained(std::initializer_list<T> Set, const E &Element) { 189781ad6265SDimitry Andric // TODO: Use std::find when we switch to C++20. 189806c3fb27SDimitry Andric for (const T &V : Set) 189906c3fb27SDimitry Andric if (V == Element) 190081ad6265SDimitry Andric return true; 190181ad6265SDimitry Andric return false; 190281ad6265SDimitry Andric } 190381ad6265SDimitry Andric 19045ffd83dbSDimitry Andric /// Wrapper function around std::is_sorted to check if elements in a range \p R 19055ffd83dbSDimitry Andric /// are sorted with respect to a comparator \p C. 19065ffd83dbSDimitry Andric template <typename R, typename Compare> bool is_sorted(R &&Range, Compare C) { 19075ffd83dbSDimitry Andric return std::is_sorted(adl_begin(Range), adl_end(Range), C); 19085ffd83dbSDimitry Andric } 19095ffd83dbSDimitry Andric 19105ffd83dbSDimitry Andric /// Wrapper function around std::is_sorted to check if elements in a range \p R 19115ffd83dbSDimitry Andric /// are sorted in non-descending order. 19125ffd83dbSDimitry Andric template <typename R> bool is_sorted(R &&Range) { 19135ffd83dbSDimitry Andric return std::is_sorted(adl_begin(Range), adl_end(Range)); 19145ffd83dbSDimitry Andric } 19155ffd83dbSDimitry Andric 19160b57cec5SDimitry Andric /// Wrapper function around std::count to count the number of times an element 19170b57cec5SDimitry Andric /// \p Element occurs in the given range \p Range. 19185ffd83dbSDimitry Andric template <typename R, typename E> auto count(R &&Range, const E &Element) { 19190b57cec5SDimitry Andric return std::count(adl_begin(Range), adl_end(Range), Element); 19200b57cec5SDimitry Andric } 19210b57cec5SDimitry Andric 19220b57cec5SDimitry Andric /// Wrapper function around std::count_if to count the number of times an 19230b57cec5SDimitry Andric /// element satisfying a given predicate occurs in a range. 19240b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 19255ffd83dbSDimitry Andric auto count_if(R &&Range, UnaryPredicate P) { 19260b57cec5SDimitry Andric return std::count_if(adl_begin(Range), adl_end(Range), P); 19270b57cec5SDimitry Andric } 19280b57cec5SDimitry Andric 19290b57cec5SDimitry Andric /// Wrapper function around std::transform to apply a function to a range and 19300b57cec5SDimitry Andric /// store the result elsewhere. 1931e8d8bef9SDimitry Andric template <typename R, typename OutputIt, typename UnaryFunction> 1932e8d8bef9SDimitry Andric OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F) { 1933e8d8bef9SDimitry Andric return std::transform(adl_begin(Range), adl_end(Range), d_first, F); 19340b57cec5SDimitry Andric } 19350b57cec5SDimitry Andric 19360b57cec5SDimitry Andric /// Provide wrappers to std::partition which take ranges instead of having to 19370b57cec5SDimitry Andric /// pass begin/end explicitly. 19380b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 19395ffd83dbSDimitry Andric auto partition(R &&Range, UnaryPredicate P) { 19400b57cec5SDimitry Andric return std::partition(adl_begin(Range), adl_end(Range), P); 19410b57cec5SDimitry Andric } 19420b57cec5SDimitry Andric 19430b57cec5SDimitry Andric /// Provide wrappers to std::lower_bound which take ranges instead of having to 19440b57cec5SDimitry Andric /// pass begin/end explicitly. 19455ffd83dbSDimitry Andric template <typename R, typename T> auto lower_bound(R &&Range, T &&Value) { 19460b57cec5SDimitry Andric return std::lower_bound(adl_begin(Range), adl_end(Range), 19470b57cec5SDimitry Andric std::forward<T>(Value)); 19480b57cec5SDimitry Andric } 19490b57cec5SDimitry Andric 19500b57cec5SDimitry Andric template <typename R, typename T, typename Compare> 19515ffd83dbSDimitry Andric auto lower_bound(R &&Range, T &&Value, Compare C) { 19520b57cec5SDimitry Andric return std::lower_bound(adl_begin(Range), adl_end(Range), 19530b57cec5SDimitry Andric std::forward<T>(Value), C); 19540b57cec5SDimitry Andric } 19550b57cec5SDimitry Andric 19560b57cec5SDimitry Andric /// Provide wrappers to std::upper_bound which take ranges instead of having to 19570b57cec5SDimitry Andric /// pass begin/end explicitly. 19585ffd83dbSDimitry Andric template <typename R, typename T> auto upper_bound(R &&Range, T &&Value) { 19590b57cec5SDimitry Andric return std::upper_bound(adl_begin(Range), adl_end(Range), 19600b57cec5SDimitry Andric std::forward<T>(Value)); 19610b57cec5SDimitry Andric } 19620b57cec5SDimitry Andric 19630b57cec5SDimitry Andric template <typename R, typename T, typename Compare> 19645ffd83dbSDimitry Andric auto upper_bound(R &&Range, T &&Value, Compare C) { 19650b57cec5SDimitry Andric return std::upper_bound(adl_begin(Range), adl_end(Range), 19660b57cec5SDimitry Andric std::forward<T>(Value), C); 19670b57cec5SDimitry Andric } 19680b57cec5SDimitry Andric 19690b57cec5SDimitry Andric template <typename R> 19700b57cec5SDimitry Andric void stable_sort(R &&Range) { 19710b57cec5SDimitry Andric std::stable_sort(adl_begin(Range), adl_end(Range)); 19720b57cec5SDimitry Andric } 19730b57cec5SDimitry Andric 19740b57cec5SDimitry Andric template <typename R, typename Compare> 19750b57cec5SDimitry Andric void stable_sort(R &&Range, Compare C) { 19760b57cec5SDimitry Andric std::stable_sort(adl_begin(Range), adl_end(Range), C); 19770b57cec5SDimitry Andric } 19780b57cec5SDimitry Andric 19790b57cec5SDimitry Andric /// Binary search for the first iterator in a range where a predicate is false. 19800b57cec5SDimitry Andric /// Requires that C is always true below some limit, and always false above it. 19810b57cec5SDimitry Andric template <typename R, typename Predicate, 19820b57cec5SDimitry Andric typename Val = decltype(*adl_begin(std::declval<R>()))> 19835ffd83dbSDimitry Andric auto partition_point(R &&Range, Predicate P) { 19840b57cec5SDimitry Andric return std::partition_point(adl_begin(Range), adl_end(Range), P); 19850b57cec5SDimitry Andric } 19860b57cec5SDimitry Andric 1987fe6060f1SDimitry Andric template<typename Range, typename Predicate> 1988fe6060f1SDimitry Andric auto unique(Range &&R, Predicate P) { 1989fe6060f1SDimitry Andric return std::unique(adl_begin(R), adl_end(R), P); 1990fe6060f1SDimitry Andric } 1991fe6060f1SDimitry Andric 1992fe6060f1SDimitry Andric /// Wrapper function around std::equal to detect if pair-wise elements between 1993fe6060f1SDimitry Andric /// two ranges are the same. 1994fe6060f1SDimitry Andric template <typename L, typename R> bool equal(L &&LRange, R &&RRange) { 1995fe6060f1SDimitry Andric return std::equal(adl_begin(LRange), adl_end(LRange), adl_begin(RRange), 1996fe6060f1SDimitry Andric adl_end(RRange)); 1997fe6060f1SDimitry Andric } 1998fe6060f1SDimitry Andric 1999bdd1243dSDimitry Andric /// Returns true if all elements in Range are equal or when the Range is empty. 2000bdd1243dSDimitry Andric template <typename R> bool all_equal(R &&Range) { 2001bdd1243dSDimitry Andric auto Begin = adl_begin(Range); 2002bdd1243dSDimitry Andric auto End = adl_end(Range); 2003bdd1243dSDimitry Andric return Begin == End || std::equal(Begin + 1, End, Begin); 2004bdd1243dSDimitry Andric } 2005bdd1243dSDimitry Andric 2006bdd1243dSDimitry Andric /// Returns true if all Values in the initializer lists are equal or the list 2007bdd1243dSDimitry Andric // is empty. 2008bdd1243dSDimitry Andric template <typename T> bool all_equal(std::initializer_list<T> Values) { 2009bdd1243dSDimitry Andric return all_equal<std::initializer_list<T>>(std::move(Values)); 20100b57cec5SDimitry Andric } 20110b57cec5SDimitry Andric 20120b57cec5SDimitry Andric /// Provide a container algorithm similar to C++ Library Fundamentals v2's 20130b57cec5SDimitry Andric /// `erase_if` which is equivalent to: 20140b57cec5SDimitry Andric /// 20150b57cec5SDimitry Andric /// C.erase(remove_if(C, pred), C.end()); 20160b57cec5SDimitry Andric /// 20170b57cec5SDimitry Andric /// This version works for any container with an erase method call accepting 20180b57cec5SDimitry Andric /// two iterators. 20190b57cec5SDimitry Andric template <typename Container, typename UnaryPredicate> 20200b57cec5SDimitry Andric void erase_if(Container &C, UnaryPredicate P) { 20210b57cec5SDimitry Andric C.erase(remove_if(C, P), C.end()); 20220b57cec5SDimitry Andric } 20230b57cec5SDimitry Andric 2024e8d8bef9SDimitry Andric /// Wrapper function to remove a value from a container: 2025e8d8bef9SDimitry Andric /// 2026e8d8bef9SDimitry Andric /// C.erase(remove(C.begin(), C.end(), V), C.end()); 2027e8d8bef9SDimitry Andric template <typename Container, typename ValueType> 2028*5f757f3fSDimitry Andric void erase(Container &C, ValueType V) { 2029e8d8bef9SDimitry Andric C.erase(std::remove(C.begin(), C.end(), V), C.end()); 2030e8d8bef9SDimitry Andric } 2031e8d8bef9SDimitry Andric 2032*5f757f3fSDimitry Andric template <typename Container, typename ValueType> 2033*5f757f3fSDimitry Andric LLVM_DEPRECATED("Use erase instead", "erase") 2034*5f757f3fSDimitry Andric void erase_value(Container &C, ValueType V) { 2035*5f757f3fSDimitry Andric erase(C, V); 2036*5f757f3fSDimitry Andric } 2037*5f757f3fSDimitry Andric 2038*5f757f3fSDimitry Andric /// Wrapper function to append range `R` to container `C`. 2039e8d8bef9SDimitry Andric /// 2040e8d8bef9SDimitry Andric /// C.insert(C.end(), R.begin(), R.end()); 2041e8d8bef9SDimitry Andric template <typename Container, typename Range> 2042*5f757f3fSDimitry Andric void append_range(Container &C, Range &&R) { 204306c3fb27SDimitry Andric C.insert(C.end(), adl_begin(R), adl_end(R)); 2044e8d8bef9SDimitry Andric } 2045e8d8bef9SDimitry Andric 2046*5f757f3fSDimitry Andric /// Appends all `Values` to container `C`. 2047*5f757f3fSDimitry Andric template <typename Container, typename... Args> 2048*5f757f3fSDimitry Andric void append_values(Container &C, Args &&...Values) { 2049*5f757f3fSDimitry Andric C.reserve(range_size(C) + sizeof...(Args)); 2050*5f757f3fSDimitry Andric // Append all values one by one. 2051*5f757f3fSDimitry Andric ((void)C.insert(C.end(), std::forward<Args>(Values)), ...); 2052*5f757f3fSDimitry Andric } 2053*5f757f3fSDimitry Andric 20540b57cec5SDimitry Andric /// Given a sequence container Cont, replace the range [ContIt, ContEnd) with 20550b57cec5SDimitry Andric /// the range [ValIt, ValEnd) (which is not from the same container). 20560b57cec5SDimitry Andric template<typename Container, typename RandomAccessIterator> 20570b57cec5SDimitry Andric void replace(Container &Cont, typename Container::iterator ContIt, 20580b57cec5SDimitry Andric typename Container::iterator ContEnd, RandomAccessIterator ValIt, 20590b57cec5SDimitry Andric RandomAccessIterator ValEnd) { 20600b57cec5SDimitry Andric while (true) { 20610b57cec5SDimitry Andric if (ValIt == ValEnd) { 20620b57cec5SDimitry Andric Cont.erase(ContIt, ContEnd); 20630b57cec5SDimitry Andric return; 20640b57cec5SDimitry Andric } else if (ContIt == ContEnd) { 20650b57cec5SDimitry Andric Cont.insert(ContIt, ValIt, ValEnd); 20660b57cec5SDimitry Andric return; 20670b57cec5SDimitry Andric } 20680b57cec5SDimitry Andric *ContIt++ = *ValIt++; 20690b57cec5SDimitry Andric } 20700b57cec5SDimitry Andric } 20710b57cec5SDimitry Andric 20720b57cec5SDimitry Andric /// Given a sequence container Cont, replace the range [ContIt, ContEnd) with 20730b57cec5SDimitry Andric /// the range R. 20740b57cec5SDimitry Andric template<typename Container, typename Range = std::initializer_list< 20750b57cec5SDimitry Andric typename Container::value_type>> 20760b57cec5SDimitry Andric void replace(Container &Cont, typename Container::iterator ContIt, 20770b57cec5SDimitry Andric typename Container::iterator ContEnd, Range R) { 20780b57cec5SDimitry Andric replace(Cont, ContIt, ContEnd, R.begin(), R.end()); 20790b57cec5SDimitry Andric } 20800b57cec5SDimitry Andric 20815ffd83dbSDimitry Andric /// An STL-style algorithm similar to std::for_each that applies a second 20825ffd83dbSDimitry Andric /// functor between every pair of elements. 20835ffd83dbSDimitry Andric /// 20845ffd83dbSDimitry Andric /// This provides the control flow logic to, for example, print a 20855ffd83dbSDimitry Andric /// comma-separated list: 20865ffd83dbSDimitry Andric /// \code 20875ffd83dbSDimitry Andric /// interleave(names.begin(), names.end(), 20885ffd83dbSDimitry Andric /// [&](StringRef name) { os << name; }, 20895ffd83dbSDimitry Andric /// [&] { os << ", "; }); 20905ffd83dbSDimitry Andric /// \endcode 20915ffd83dbSDimitry Andric template <typename ForwardIterator, typename UnaryFunctor, 20925ffd83dbSDimitry Andric typename NullaryFunctor, 2093bdd1243dSDimitry Andric typename = std::enable_if_t< 20945ffd83dbSDimitry Andric !std::is_constructible<StringRef, UnaryFunctor>::value && 2095bdd1243dSDimitry Andric !std::is_constructible<StringRef, NullaryFunctor>::value>> 20965ffd83dbSDimitry Andric inline void interleave(ForwardIterator begin, ForwardIterator end, 20975ffd83dbSDimitry Andric UnaryFunctor each_fn, NullaryFunctor between_fn) { 20985ffd83dbSDimitry Andric if (begin == end) 20995ffd83dbSDimitry Andric return; 21005ffd83dbSDimitry Andric each_fn(*begin); 21015ffd83dbSDimitry Andric ++begin; 21025ffd83dbSDimitry Andric for (; begin != end; ++begin) { 21035ffd83dbSDimitry Andric between_fn(); 21045ffd83dbSDimitry Andric each_fn(*begin); 21055ffd83dbSDimitry Andric } 21065ffd83dbSDimitry Andric } 21075ffd83dbSDimitry Andric 21085ffd83dbSDimitry Andric template <typename Container, typename UnaryFunctor, typename NullaryFunctor, 2109bdd1243dSDimitry Andric typename = std::enable_if_t< 21105ffd83dbSDimitry Andric !std::is_constructible<StringRef, UnaryFunctor>::value && 2111bdd1243dSDimitry Andric !std::is_constructible<StringRef, NullaryFunctor>::value>> 21125ffd83dbSDimitry Andric inline void interleave(const Container &c, UnaryFunctor each_fn, 21135ffd83dbSDimitry Andric NullaryFunctor between_fn) { 21145ffd83dbSDimitry Andric interleave(c.begin(), c.end(), each_fn, between_fn); 21155ffd83dbSDimitry Andric } 21165ffd83dbSDimitry Andric 21175ffd83dbSDimitry Andric /// Overload of interleave for the common case of string separator. 21185ffd83dbSDimitry Andric template <typename Container, typename UnaryFunctor, typename StreamT, 21195ffd83dbSDimitry Andric typename T = detail::ValueOfRange<Container>> 21205ffd83dbSDimitry Andric inline void interleave(const Container &c, StreamT &os, UnaryFunctor each_fn, 21215ffd83dbSDimitry Andric const StringRef &separator) { 21225ffd83dbSDimitry Andric interleave(c.begin(), c.end(), each_fn, [&] { os << separator; }); 21235ffd83dbSDimitry Andric } 21245ffd83dbSDimitry Andric template <typename Container, typename StreamT, 21255ffd83dbSDimitry Andric typename T = detail::ValueOfRange<Container>> 21265ffd83dbSDimitry Andric inline void interleave(const Container &c, StreamT &os, 21275ffd83dbSDimitry Andric const StringRef &separator) { 21285ffd83dbSDimitry Andric interleave( 21295ffd83dbSDimitry Andric c, os, [&](const T &a) { os << a; }, separator); 21305ffd83dbSDimitry Andric } 21315ffd83dbSDimitry Andric 21325ffd83dbSDimitry Andric template <typename Container, typename UnaryFunctor, typename StreamT, 21335ffd83dbSDimitry Andric typename T = detail::ValueOfRange<Container>> 21345ffd83dbSDimitry Andric inline void interleaveComma(const Container &c, StreamT &os, 21355ffd83dbSDimitry Andric UnaryFunctor each_fn) { 21365ffd83dbSDimitry Andric interleave(c, os, each_fn, ", "); 21375ffd83dbSDimitry Andric } 21385ffd83dbSDimitry Andric template <typename Container, typename StreamT, 21395ffd83dbSDimitry Andric typename T = detail::ValueOfRange<Container>> 21405ffd83dbSDimitry Andric inline void interleaveComma(const Container &c, StreamT &os) { 21415ffd83dbSDimitry Andric interleaveComma(c, os, [&](const T &a) { os << a; }); 21425ffd83dbSDimitry Andric } 21435ffd83dbSDimitry Andric 21440b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 21450b57cec5SDimitry Andric // Extra additions to <memory> 21460b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 21470b57cec5SDimitry Andric 21480b57cec5SDimitry Andric struct FreeDeleter { 21490b57cec5SDimitry Andric void operator()(void* v) { 21500b57cec5SDimitry Andric ::free(v); 21510b57cec5SDimitry Andric } 21520b57cec5SDimitry Andric }; 21530b57cec5SDimitry Andric 21540b57cec5SDimitry Andric template<typename First, typename Second> 21550b57cec5SDimitry Andric struct pair_hash { 21560b57cec5SDimitry Andric size_t operator()(const std::pair<First, Second> &P) const { 21570b57cec5SDimitry Andric return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second); 21580b57cec5SDimitry Andric } 21590b57cec5SDimitry Andric }; 21600b57cec5SDimitry Andric 21610b57cec5SDimitry Andric /// Binary functor that adapts to any other binary functor after dereferencing 21620b57cec5SDimitry Andric /// operands. 21630b57cec5SDimitry Andric template <typename T> struct deref { 21640b57cec5SDimitry Andric T func; 21650b57cec5SDimitry Andric 21660b57cec5SDimitry Andric // Could be further improved to cope with non-derivable functors and 21670b57cec5SDimitry Andric // non-binary functors (should be a variadic template member function 21680b57cec5SDimitry Andric // operator()). 21695ffd83dbSDimitry Andric template <typename A, typename B> auto operator()(A &lhs, B &rhs) const { 21700b57cec5SDimitry Andric assert(lhs); 21710b57cec5SDimitry Andric assert(rhs); 21720b57cec5SDimitry Andric return func(*lhs, *rhs); 21730b57cec5SDimitry Andric } 21740b57cec5SDimitry Andric }; 21750b57cec5SDimitry Andric 21760b57cec5SDimitry Andric namespace detail { 21770b57cec5SDimitry Andric 217806c3fb27SDimitry Andric /// Tuple-like type for `zip_enumerator` dereference. 217906c3fb27SDimitry Andric template <typename... Refs> struct enumerator_result; 21800b57cec5SDimitry Andric 218106c3fb27SDimitry Andric template <typename... Iters> 218206c3fb27SDimitry Andric using EnumeratorTupleType = enumerator_result<decltype(*declval<Iters>())...>; 21830b57cec5SDimitry Andric 218406c3fb27SDimitry Andric /// Zippy iterator that uses the second iterator for comparisons. For the 218506c3fb27SDimitry Andric /// increment to be safe, the second range has to be the shortest. 218606c3fb27SDimitry Andric /// Returns `enumerator_result` on dereference to provide `.index()` and 218706c3fb27SDimitry Andric /// `.value()` member functions. 218806c3fb27SDimitry Andric /// Note: Because the dereference operator returns `enumerator_result` as a 218906c3fb27SDimitry Andric /// value instead of a reference and does not strictly conform to the C++17's 219006c3fb27SDimitry Andric /// definition of forward iterator. However, it satisfies all the 219106c3fb27SDimitry Andric /// forward_iterator requirements that the `zip_common` and `zippy` depend on 219206c3fb27SDimitry Andric /// and fully conforms to the C++20 definition of forward iterator. 219306c3fb27SDimitry Andric /// This is similar to `std::vector<bool>::iterator` that returns bit reference 219406c3fb27SDimitry Andric /// wrappers on dereference. 219506c3fb27SDimitry Andric template <typename... Iters> 219606c3fb27SDimitry Andric struct zip_enumerator : zip_common<zip_enumerator<Iters...>, 219706c3fb27SDimitry Andric EnumeratorTupleType<Iters...>, Iters...> { 219806c3fb27SDimitry Andric static_assert(sizeof...(Iters) >= 2, "Expected at least two iteratees"); 219906c3fb27SDimitry Andric using zip_common<zip_enumerator<Iters...>, EnumeratorTupleType<Iters...>, 220006c3fb27SDimitry Andric Iters...>::zip_common; 22010b57cec5SDimitry Andric 220206c3fb27SDimitry Andric bool operator==(const zip_enumerator &Other) const { 220306c3fb27SDimitry Andric return std::get<1>(this->iterators) == std::get<1>(Other.iterators); 22040b57cec5SDimitry Andric } 22050b57cec5SDimitry Andric }; 22060b57cec5SDimitry Andric 220706c3fb27SDimitry Andric template <typename... Refs> struct enumerator_result<std::size_t, Refs...> { 220806c3fb27SDimitry Andric static constexpr std::size_t NumRefs = sizeof...(Refs); 220906c3fb27SDimitry Andric static_assert(NumRefs != 0); 221006c3fb27SDimitry Andric // `NumValues` includes the index. 221106c3fb27SDimitry Andric static constexpr std::size_t NumValues = NumRefs + 1; 221206c3fb27SDimitry Andric 221306c3fb27SDimitry Andric // Tuple type whose element types are references for each `Ref`. 221406c3fb27SDimitry Andric using range_reference_tuple = std::tuple<Refs...>; 221506c3fb27SDimitry Andric // Tuple type who elements are references to all values, including both 221606c3fb27SDimitry Andric // the index and `Refs` reference types. 221706c3fb27SDimitry Andric using value_reference_tuple = std::tuple<std::size_t, Refs...>; 221806c3fb27SDimitry Andric 221906c3fb27SDimitry Andric enumerator_result(std::size_t Index, Refs &&...Rs) 222006c3fb27SDimitry Andric : Idx(Index), Storage(std::forward<Refs>(Rs)...) {} 222106c3fb27SDimitry Andric 222206c3fb27SDimitry Andric /// Returns the 0-based index of the current position within the original 222306c3fb27SDimitry Andric /// input range(s). 222406c3fb27SDimitry Andric std::size_t index() const { return Idx; } 222506c3fb27SDimitry Andric 222606c3fb27SDimitry Andric /// Returns the value(s) for the current iterator. This does not include the 222706c3fb27SDimitry Andric /// index. 222806c3fb27SDimitry Andric decltype(auto) value() const { 222906c3fb27SDimitry Andric if constexpr (NumRefs == 1) 223006c3fb27SDimitry Andric return std::get<0>(Storage); 223106c3fb27SDimitry Andric else 223206c3fb27SDimitry Andric return Storage; 2233bdd1243dSDimitry Andric } 2234bdd1243dSDimitry Andric 223506c3fb27SDimitry Andric /// Returns the value at index `I`. This case covers the index. 223606c3fb27SDimitry Andric template <std::size_t I, typename = std::enable_if_t<I == 0>> 223706c3fb27SDimitry Andric friend std::size_t get(const enumerator_result &Result) { 223806c3fb27SDimitry Andric return Result.Idx; 22390b57cec5SDimitry Andric } 22400b57cec5SDimitry Andric 224106c3fb27SDimitry Andric /// Returns the value at index `I`. This case covers references to the 224206c3fb27SDimitry Andric /// iteratees. 224306c3fb27SDimitry Andric template <std::size_t I, typename = std::enable_if_t<I != 0>> 224406c3fb27SDimitry Andric friend decltype(auto) get(const enumerator_result &Result) { 224506c3fb27SDimitry Andric // Note: This is a separate function from the other `get`, instead of an 224606c3fb27SDimitry Andric // `if constexpr` case, to work around an MSVC 19.31.31XXX compiler 224706c3fb27SDimitry Andric // (Visual Studio 2022 17.1) return type deduction bug. 224806c3fb27SDimitry Andric return std::get<I - 1>(Result.Storage); 22490b57cec5SDimitry Andric } 22500b57cec5SDimitry Andric 225106c3fb27SDimitry Andric template <typename... Ts> 225206c3fb27SDimitry Andric friend bool operator==(const enumerator_result &Result, 225306c3fb27SDimitry Andric const std::tuple<std::size_t, Ts...> &Other) { 225406c3fb27SDimitry Andric static_assert(NumRefs == sizeof...(Ts), "Size mismatch"); 225506c3fb27SDimitry Andric if (Result.Idx != std::get<0>(Other)) 225606c3fb27SDimitry Andric return false; 225706c3fb27SDimitry Andric return Result.is_value_equal(Other, std::make_index_sequence<NumRefs>{}); 22580b57cec5SDimitry Andric } 22590b57cec5SDimitry Andric 22600b57cec5SDimitry Andric private: 226106c3fb27SDimitry Andric template <typename Tuple, std::size_t... Idx> 226206c3fb27SDimitry Andric bool is_value_equal(const Tuple &Other, std::index_sequence<Idx...>) const { 226306c3fb27SDimitry Andric return ((std::get<Idx>(Storage) == std::get<Idx + 1>(Other)) && ...); 226406c3fb27SDimitry Andric } 226506c3fb27SDimitry Andric 226606c3fb27SDimitry Andric std::size_t Idx; 226706c3fb27SDimitry Andric // Make this tuple mutable to avoid casts that obfuscate const-correctness 226806c3fb27SDimitry Andric // issues. Const-correctness of references is taken care of by `zippy` that 226906c3fb27SDimitry Andric // defines const-non and const iterator types that will propagate down to 227006c3fb27SDimitry Andric // `enumerator_result`'s `Refs`. 227106c3fb27SDimitry Andric // Note that unlike the results of `zip*` functions, `enumerate`'s result are 227206c3fb27SDimitry Andric // supposed to be modifiable even when defined as 227306c3fb27SDimitry Andric // `const`. 227406c3fb27SDimitry Andric mutable range_reference_tuple Storage; 22750b57cec5SDimitry Andric }; 22760b57cec5SDimitry Andric 2277*5f757f3fSDimitry Andric struct index_iterator 2278*5f757f3fSDimitry Andric : llvm::iterator_facade_base<index_iterator, 2279*5f757f3fSDimitry Andric std::random_access_iterator_tag, std::size_t> { 2280*5f757f3fSDimitry Andric index_iterator(std::size_t Index) : Index(Index) {} 2281*5f757f3fSDimitry Andric 2282*5f757f3fSDimitry Andric index_iterator &operator+=(std::ptrdiff_t N) { 2283*5f757f3fSDimitry Andric Index += N; 228406c3fb27SDimitry Andric return *this; 22854824e7fdSDimitry Andric } 22860b57cec5SDimitry Andric 2287*5f757f3fSDimitry Andric index_iterator &operator-=(std::ptrdiff_t N) { 2288*5f757f3fSDimitry Andric Index -= N; 2289*5f757f3fSDimitry Andric return *this; 2290*5f757f3fSDimitry Andric } 2291*5f757f3fSDimitry Andric 2292*5f757f3fSDimitry Andric std::ptrdiff_t operator-(const index_iterator &R) const { 2293*5f757f3fSDimitry Andric return Index - R.Index; 2294*5f757f3fSDimitry Andric } 2295*5f757f3fSDimitry Andric 229606c3fb27SDimitry Andric // Note: This dereference operator returns a value instead of a reference 229706c3fb27SDimitry Andric // and does not strictly conform to the C++17's definition of forward 229806c3fb27SDimitry Andric // iterator. However, it satisfies all the forward_iterator requirements 229906c3fb27SDimitry Andric // that the `zip_common` depends on and fully conforms to the C++20 230006c3fb27SDimitry Andric // definition of forward iterator. 230106c3fb27SDimitry Andric std::size_t operator*() const { return Index; } 230206c3fb27SDimitry Andric 2303*5f757f3fSDimitry Andric friend bool operator==(const index_iterator &Lhs, const index_iterator &Rhs) { 230406c3fb27SDimitry Andric return Lhs.Index == Rhs.Index; 23054824e7fdSDimitry Andric } 23060b57cec5SDimitry Andric 2307*5f757f3fSDimitry Andric friend bool operator<(const index_iterator &Lhs, const index_iterator &Rhs) { 2308*5f757f3fSDimitry Andric return Lhs.Index < Rhs.Index; 2309*5f757f3fSDimitry Andric } 2310*5f757f3fSDimitry Andric 2311*5f757f3fSDimitry Andric private: 2312*5f757f3fSDimitry Andric std::size_t Index; 231306c3fb27SDimitry Andric }; 231406c3fb27SDimitry Andric 2315*5f757f3fSDimitry Andric /// Infinite stream of increasing 0-based `size_t` indices. 2316*5f757f3fSDimitry Andric struct index_stream { 2317*5f757f3fSDimitry Andric index_iterator begin() const { return {0}; } 2318*5f757f3fSDimitry Andric index_iterator end() const { 231906c3fb27SDimitry Andric // We approximate 'infinity' with the max size_t value, which should be good 232006c3fb27SDimitry Andric // enough to index over any container. 2321*5f757f3fSDimitry Andric return index_iterator{std::numeric_limits<std::size_t>::max()}; 232206c3fb27SDimitry Andric } 23230b57cec5SDimitry Andric }; 23240b57cec5SDimitry Andric 23250b57cec5SDimitry Andric } // end namespace detail 23260b57cec5SDimitry Andric 2327*5f757f3fSDimitry Andric /// Increasing range of `size_t` indices. 2328*5f757f3fSDimitry Andric class index_range { 2329*5f757f3fSDimitry Andric std::size_t Begin; 2330*5f757f3fSDimitry Andric std::size_t End; 2331*5f757f3fSDimitry Andric 2332*5f757f3fSDimitry Andric public: 2333*5f757f3fSDimitry Andric index_range(std::size_t Begin, std::size_t End) : Begin(Begin), End(End) {} 2334*5f757f3fSDimitry Andric detail::index_iterator begin() const { return {Begin}; } 2335*5f757f3fSDimitry Andric detail::index_iterator end() const { return {End}; } 2336*5f757f3fSDimitry Andric }; 2337*5f757f3fSDimitry Andric 233806c3fb27SDimitry Andric /// Given two or more input ranges, returns a new range whose values are are 233906c3fb27SDimitry Andric /// tuples (A, B, C, ...), such that A is the 0-based index of the item in the 234006c3fb27SDimitry Andric /// sequence, and B, C, ..., are the values from the original input ranges. All 234106c3fb27SDimitry Andric /// input ranges are required to have equal lengths. Note that the returned 234206c3fb27SDimitry Andric /// iterator allows for the values (B, C, ...) to be modified. Example: 23430b57cec5SDimitry Andric /// 234406c3fb27SDimitry Andric /// ```c++ 234506c3fb27SDimitry Andric /// std::vector<char> Letters = {'A', 'B', 'C', 'D'}; 234606c3fb27SDimitry Andric /// std::vector<int> Vals = {10, 11, 12, 13}; 234706c3fb27SDimitry Andric /// 234806c3fb27SDimitry Andric /// for (auto [Index, Letter, Value] : enumerate(Letters, Vals)) { 234906c3fb27SDimitry Andric /// printf("Item %zu - %c: %d\n", Index, Letter, Value); 235006c3fb27SDimitry Andric /// Value -= 10; 23510b57cec5SDimitry Andric /// } 235206c3fb27SDimitry Andric /// ``` 2353bdd1243dSDimitry Andric /// 23540b57cec5SDimitry Andric /// Output: 235506c3fb27SDimitry Andric /// Item 0 - A: 10 235606c3fb27SDimitry Andric /// Item 1 - B: 11 235706c3fb27SDimitry Andric /// Item 2 - C: 12 235806c3fb27SDimitry Andric /// Item 3 - D: 13 23590b57cec5SDimitry Andric /// 236006c3fb27SDimitry Andric /// or using an iterator: 236106c3fb27SDimitry Andric /// ```c++ 236206c3fb27SDimitry Andric /// for (auto it : enumerate(Vals)) { 236306c3fb27SDimitry Andric /// it.value() += 10; 236406c3fb27SDimitry Andric /// printf("Item %zu: %d\n", it.index(), it.value()); 236506c3fb27SDimitry Andric /// } 236606c3fb27SDimitry Andric /// ``` 236706c3fb27SDimitry Andric /// 236806c3fb27SDimitry Andric /// Output: 236906c3fb27SDimitry Andric /// Item 0: 20 237006c3fb27SDimitry Andric /// Item 1: 21 237106c3fb27SDimitry Andric /// Item 2: 22 237206c3fb27SDimitry Andric /// Item 3: 23 237306c3fb27SDimitry Andric /// 237406c3fb27SDimitry Andric template <typename FirstRange, typename... RestRanges> 237506c3fb27SDimitry Andric auto enumerate(FirstRange &&First, RestRanges &&...Rest) { 237606c3fb27SDimitry Andric if constexpr (sizeof...(Rest) != 0) { 237706c3fb27SDimitry Andric #ifndef NDEBUG 237806c3fb27SDimitry Andric // Note: Create an array instead of an initializer list to work around an 237906c3fb27SDimitry Andric // Apple clang 14 compiler bug. 238006c3fb27SDimitry Andric size_t sizes[] = {range_size(First), range_size(Rest)...}; 238106c3fb27SDimitry Andric assert(all_equal(sizes) && "Ranges have different length"); 238206c3fb27SDimitry Andric #endif 238306c3fb27SDimitry Andric } 238406c3fb27SDimitry Andric using enumerator = detail::zippy<detail::zip_enumerator, detail::index_stream, 238506c3fb27SDimitry Andric FirstRange, RestRanges...>; 238606c3fb27SDimitry Andric return enumerator(detail::index_stream{}, std::forward<FirstRange>(First), 238706c3fb27SDimitry Andric std::forward<RestRanges>(Rest)...); 23880b57cec5SDimitry Andric } 23890b57cec5SDimitry Andric 23900b57cec5SDimitry Andric namespace detail { 23910b57cec5SDimitry Andric 2392349cc55cSDimitry Andric template <typename Predicate, typename... Args> 2393349cc55cSDimitry Andric bool all_of_zip_predicate_first(Predicate &&P, Args &&...args) { 2394349cc55cSDimitry Andric auto z = zip(args...); 2395349cc55cSDimitry Andric auto it = z.begin(); 2396349cc55cSDimitry Andric auto end = z.end(); 2397349cc55cSDimitry Andric while (it != end) { 2398bdd1243dSDimitry Andric if (!std::apply([&](auto &&...args) { return P(args...); }, *it)) 2399349cc55cSDimitry Andric return false; 2400349cc55cSDimitry Andric ++it; 2401349cc55cSDimitry Andric } 2402349cc55cSDimitry Andric return it.all_equals(end); 2403349cc55cSDimitry Andric } 2404349cc55cSDimitry Andric 2405349cc55cSDimitry Andric // Just an adaptor to switch the order of argument and have the predicate before 2406349cc55cSDimitry Andric // the zipped inputs. 2407349cc55cSDimitry Andric template <typename... ArgsThenPredicate, size_t... InputIndexes> 2408349cc55cSDimitry Andric bool all_of_zip_predicate_last( 2409349cc55cSDimitry Andric std::tuple<ArgsThenPredicate...> argsThenPredicate, 2410349cc55cSDimitry Andric std::index_sequence<InputIndexes...>) { 2411349cc55cSDimitry Andric auto constexpr OutputIndex = 2412349cc55cSDimitry Andric std::tuple_size<decltype(argsThenPredicate)>::value - 1; 2413349cc55cSDimitry Andric return all_of_zip_predicate_first(std::get<OutputIndex>(argsThenPredicate), 2414349cc55cSDimitry Andric std::get<InputIndexes>(argsThenPredicate)...); 2415349cc55cSDimitry Andric } 2416349cc55cSDimitry Andric 2417349cc55cSDimitry Andric } // end namespace detail 2418349cc55cSDimitry Andric 2419349cc55cSDimitry Andric /// Compare two zipped ranges using the provided predicate (as last argument). 2420349cc55cSDimitry Andric /// Return true if all elements satisfy the predicate and false otherwise. 2421349cc55cSDimitry Andric // Return false if the zipped iterator aren't all at end (size mismatch). 2422349cc55cSDimitry Andric template <typename... ArgsAndPredicate> 2423349cc55cSDimitry Andric bool all_of_zip(ArgsAndPredicate &&...argsAndPredicate) { 2424349cc55cSDimitry Andric return detail::all_of_zip_predicate_last( 2425349cc55cSDimitry Andric std::forward_as_tuple(argsAndPredicate...), 2426349cc55cSDimitry Andric std::make_index_sequence<sizeof...(argsAndPredicate) - 1>{}); 2427349cc55cSDimitry Andric } 2428349cc55cSDimitry Andric 24290b57cec5SDimitry Andric /// Return true if the sequence [Begin, End) has exactly N items. Runs in O(N) 24300b57cec5SDimitry Andric /// time. Not meant for use with random-access iterators. 24315ffd83dbSDimitry Andric /// Can optionally take a predicate to filter lazily some items. 24325ffd83dbSDimitry Andric template <typename IterTy, 24335ffd83dbSDimitry Andric typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)> 24340b57cec5SDimitry Andric bool hasNItems( 24350b57cec5SDimitry Andric IterTy &&Begin, IterTy &&End, unsigned N, 24365ffd83dbSDimitry Andric Pred &&ShouldBeCounted = 24375ffd83dbSDimitry Andric [](const decltype(*std::declval<IterTy>()) &) { return true; }, 24385ffd83dbSDimitry Andric std::enable_if_t< 2439e8d8bef9SDimitry Andric !std::is_base_of<std::random_access_iterator_tag, 2440e8d8bef9SDimitry Andric typename std::iterator_traits<std::remove_reference_t< 2441e8d8bef9SDimitry Andric decltype(Begin)>>::iterator_category>::value, 24425ffd83dbSDimitry Andric void> * = nullptr) { 24435ffd83dbSDimitry Andric for (; N; ++Begin) { 24440b57cec5SDimitry Andric if (Begin == End) 24450b57cec5SDimitry Andric return false; // Too few. 24465ffd83dbSDimitry Andric N -= ShouldBeCounted(*Begin); 24475ffd83dbSDimitry Andric } 24485ffd83dbSDimitry Andric for (; Begin != End; ++Begin) 24495ffd83dbSDimitry Andric if (ShouldBeCounted(*Begin)) 24505ffd83dbSDimitry Andric return false; // Too many. 24515ffd83dbSDimitry Andric return true; 24520b57cec5SDimitry Andric } 24530b57cec5SDimitry Andric 24540b57cec5SDimitry Andric /// Return true if the sequence [Begin, End) has N or more items. Runs in O(N) 24550b57cec5SDimitry Andric /// time. Not meant for use with random-access iterators. 24565ffd83dbSDimitry Andric /// Can optionally take a predicate to lazily filter some items. 24575ffd83dbSDimitry Andric template <typename IterTy, 24585ffd83dbSDimitry Andric typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)> 24590b57cec5SDimitry Andric bool hasNItemsOrMore( 24600b57cec5SDimitry Andric IterTy &&Begin, IterTy &&End, unsigned N, 24615ffd83dbSDimitry Andric Pred &&ShouldBeCounted = 24625ffd83dbSDimitry Andric [](const decltype(*std::declval<IterTy>()) &) { return true; }, 24635ffd83dbSDimitry Andric std::enable_if_t< 2464e8d8bef9SDimitry Andric !std::is_base_of<std::random_access_iterator_tag, 2465e8d8bef9SDimitry Andric typename std::iterator_traits<std::remove_reference_t< 2466e8d8bef9SDimitry Andric decltype(Begin)>>::iterator_category>::value, 24675ffd83dbSDimitry Andric void> * = nullptr) { 24685ffd83dbSDimitry Andric for (; N; ++Begin) { 24690b57cec5SDimitry Andric if (Begin == End) 24700b57cec5SDimitry Andric return false; // Too few. 24715ffd83dbSDimitry Andric N -= ShouldBeCounted(*Begin); 24725ffd83dbSDimitry Andric } 24730b57cec5SDimitry Andric return true; 24740b57cec5SDimitry Andric } 24750b57cec5SDimitry Andric 24765ffd83dbSDimitry Andric /// Returns true if the sequence [Begin, End) has N or less items. Can 24775ffd83dbSDimitry Andric /// optionally take a predicate to lazily filter some items. 24785ffd83dbSDimitry Andric template <typename IterTy, 24795ffd83dbSDimitry Andric typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)> 24805ffd83dbSDimitry Andric bool hasNItemsOrLess( 24815ffd83dbSDimitry Andric IterTy &&Begin, IterTy &&End, unsigned N, 24825ffd83dbSDimitry Andric Pred &&ShouldBeCounted = [](const decltype(*std::declval<IterTy>()) &) { 24835ffd83dbSDimitry Andric return true; 24845ffd83dbSDimitry Andric }) { 24855ffd83dbSDimitry Andric assert(N != std::numeric_limits<unsigned>::max()); 24865ffd83dbSDimitry Andric return !hasNItemsOrMore(Begin, End, N + 1, ShouldBeCounted); 24875ffd83dbSDimitry Andric } 24885ffd83dbSDimitry Andric 24895ffd83dbSDimitry Andric /// Returns true if the given container has exactly N items 24905ffd83dbSDimitry Andric template <typename ContainerTy> bool hasNItems(ContainerTy &&C, unsigned N) { 24915ffd83dbSDimitry Andric return hasNItems(std::begin(C), std::end(C), N); 24925ffd83dbSDimitry Andric } 24935ffd83dbSDimitry Andric 24945ffd83dbSDimitry Andric /// Returns true if the given container has N or more items 24955ffd83dbSDimitry Andric template <typename ContainerTy> 24965ffd83dbSDimitry Andric bool hasNItemsOrMore(ContainerTy &&C, unsigned N) { 24975ffd83dbSDimitry Andric return hasNItemsOrMore(std::begin(C), std::end(C), N); 24985ffd83dbSDimitry Andric } 24995ffd83dbSDimitry Andric 25005ffd83dbSDimitry Andric /// Returns true if the given container has N or less items 25015ffd83dbSDimitry Andric template <typename ContainerTy> 25025ffd83dbSDimitry Andric bool hasNItemsOrLess(ContainerTy &&C, unsigned N) { 25035ffd83dbSDimitry Andric return hasNItemsOrLess(std::begin(C), std::end(C), N); 25045ffd83dbSDimitry Andric } 25055ffd83dbSDimitry Andric 25060b57cec5SDimitry Andric /// Returns a raw pointer that represents the same address as the argument. 25070b57cec5SDimitry Andric /// 25085ffd83dbSDimitry Andric /// This implementation can be removed once we move to C++20 where it's defined 25095ffd83dbSDimitry Andric /// as std::to_address(). 25100b57cec5SDimitry Andric /// 25110b57cec5SDimitry Andric /// The std::pointer_traits<>::to_address(p) variations of these overloads has 25120b57cec5SDimitry Andric /// not been implemented. 25135ffd83dbSDimitry Andric template <class Ptr> auto to_address(const Ptr &P) { return P.operator->(); } 25140b57cec5SDimitry Andric template <class T> constexpr T *to_address(T *P) { return P; } 25150b57cec5SDimitry Andric 2516*5f757f3fSDimitry Andric // Detect incomplete types, relying on the fact that their size is unknown. 2517*5f757f3fSDimitry Andric namespace detail { 2518*5f757f3fSDimitry Andric template <typename T> using has_sizeof = decltype(sizeof(T)); 2519*5f757f3fSDimitry Andric } // namespace detail 2520*5f757f3fSDimitry Andric 2521*5f757f3fSDimitry Andric /// Detects when type `T` is incomplete. This is true for forward declarations 2522*5f757f3fSDimitry Andric /// and false for types with a full definition. 2523*5f757f3fSDimitry Andric template <typename T> 2524*5f757f3fSDimitry Andric constexpr bool is_incomplete_v = !is_detected<detail::has_sizeof, T>::value; 2525*5f757f3fSDimitry Andric 25260b57cec5SDimitry Andric } // end namespace llvm 25270b57cec5SDimitry Andric 2528bdd1243dSDimitry Andric namespace std { 252906c3fb27SDimitry Andric template <typename... Refs> 253006c3fb27SDimitry Andric struct tuple_size<llvm::detail::enumerator_result<Refs...>> 253106c3fb27SDimitry Andric : std::integral_constant<std::size_t, sizeof...(Refs)> {}; 2532bdd1243dSDimitry Andric 253306c3fb27SDimitry Andric template <std::size_t I, typename... Refs> 253406c3fb27SDimitry Andric struct tuple_element<I, llvm::detail::enumerator_result<Refs...>> 253506c3fb27SDimitry Andric : std::tuple_element<I, std::tuple<Refs...>> {}; 253606c3fb27SDimitry Andric 253706c3fb27SDimitry Andric template <std::size_t I, typename... Refs> 253806c3fb27SDimitry Andric struct tuple_element<I, const llvm::detail::enumerator_result<Refs...>> 253906c3fb27SDimitry Andric : std::tuple_element<I, std::tuple<Refs...>> {}; 2540bdd1243dSDimitry Andric 2541bdd1243dSDimitry Andric } // namespace std 2542bdd1243dSDimitry Andric 25430b57cec5SDimitry Andric #endif // LLVM_ADT_STLEXTRAS_H 2544