STLExtras.h 72 KB

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