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