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