STLExtras.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains some templates that are useful if you are working with the
  11. // STL at all.
  12. //
  13. // No library is required when using these functions.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #ifndef LLVM_ADT_STLEXTRAS_H
  17. #define LLVM_ADT_STLEXTRAS_H
  18. #include "llvm/Support/Compiler.h"
  19. #include <algorithm> // for std::all_of
  20. #include <cassert>
  21. #include <cstddef> // for std::size_t
  22. #include <cstdlib> // for qsort
  23. #include <functional>
  24. #include <iterator>
  25. #include <memory>
  26. #include <utility> // for std::pair
  27. namespace llvm {
  28. //===----------------------------------------------------------------------===//
  29. // Extra additions to <functional>
  30. //===----------------------------------------------------------------------===//
  31. template<class Ty>
  32. struct identity : public std::unary_function<Ty, Ty> {
  33. Ty &operator()(Ty &self) const {
  34. return self;
  35. }
  36. const Ty &operator()(const Ty &self) const {
  37. return self;
  38. }
  39. };
  40. template<class Ty>
  41. struct less_ptr : public std::binary_function<Ty, Ty, bool> {
  42. bool operator()(const Ty* left, const Ty* right) const {
  43. return *left < *right;
  44. }
  45. };
  46. template<class Ty>
  47. struct greater_ptr : public std::binary_function<Ty, Ty, bool> {
  48. bool operator()(const Ty* left, const Ty* right) const {
  49. return *right < *left;
  50. }
  51. };
  52. /// An efficient, type-erasing, non-owning reference to a callable. This is
  53. /// intended for use as the type of a function parameter that is not used
  54. /// after the function in question returns.
  55. ///
  56. /// This class does not own the callable, so it is not in general safe to store
  57. /// a function_ref.
  58. template<typename Fn> class function_ref;
  59. template<typename Ret, typename ...Params>
  60. class function_ref<Ret(Params...)> {
  61. Ret (*callback)(intptr_t callable, Params ...params);
  62. intptr_t callable;
  63. template<typename Callable>
  64. static Ret callback_fn(intptr_t callable, Params ...params) {
  65. return (*reinterpret_cast<Callable*>(callable))(
  66. std::forward<Params>(params)...);
  67. }
  68. public:
  69. template <typename Callable>
  70. function_ref(Callable &&callable,
  71. typename std::enable_if<
  72. !std::is_same<typename std::remove_reference<Callable>::type,
  73. function_ref>::value>::type * = nullptr)
  74. : callback(callback_fn<typename std::remove_reference<Callable>::type>),
  75. callable(reinterpret_cast<intptr_t>(&callable)) {}
  76. Ret operator()(Params ...params) const {
  77. return callback(callable, std::forward<Params>(params)...);
  78. }
  79. };
  80. // deleter - Very very very simple method that is used to invoke operator
  81. // delete on something. It is used like this:
  82. //
  83. // for_each(V.begin(), B.end(), deleter<Interval>);
  84. //
  85. template <class T>
  86. inline void deleter(T *Ptr) {
  87. delete Ptr;
  88. }
  89. //===----------------------------------------------------------------------===//
  90. // Extra additions to <iterator>
  91. //===----------------------------------------------------------------------===//
  92. // mapped_iterator - This is a simple iterator adapter that causes a function to
  93. // be dereferenced whenever operator* is invoked on the iterator.
  94. //
  95. template <class RootIt, class UnaryFunc>
  96. class mapped_iterator {
  97. RootIt current;
  98. UnaryFunc Fn;
  99. public:
  100. typedef typename std::iterator_traits<RootIt>::iterator_category
  101. iterator_category;
  102. typedef typename std::iterator_traits<RootIt>::difference_type
  103. difference_type;
  104. typedef typename UnaryFunc::result_type value_type;
  105. typedef void pointer;
  106. //typedef typename UnaryFunc::result_type *pointer;
  107. typedef void reference; // Can't modify value returned by fn
  108. typedef RootIt iterator_type;
  109. inline const RootIt &getCurrent() const { return current; }
  110. inline const UnaryFunc &getFunc() const { return Fn; }
  111. inline explicit mapped_iterator(const RootIt &I, UnaryFunc F)
  112. : current(I), Fn(F) {}
  113. inline value_type operator*() const { // All this work to do this
  114. return Fn(*current); // little change
  115. }
  116. mapped_iterator &operator++() {
  117. ++current;
  118. return *this;
  119. }
  120. mapped_iterator &operator--() {
  121. --current;
  122. return *this;
  123. }
  124. mapped_iterator operator++(int) {
  125. mapped_iterator __tmp = *this;
  126. ++current;
  127. return __tmp;
  128. }
  129. mapped_iterator operator--(int) {
  130. mapped_iterator __tmp = *this;
  131. --current;
  132. return __tmp;
  133. }
  134. mapped_iterator operator+(difference_type n) const {
  135. return mapped_iterator(current + n, Fn);
  136. }
  137. mapped_iterator &operator+=(difference_type n) {
  138. current += n;
  139. return *this;
  140. }
  141. mapped_iterator operator-(difference_type n) const {
  142. return mapped_iterator(current - n, Fn);
  143. }
  144. mapped_iterator &operator-=(difference_type n) {
  145. current -= n;
  146. return *this;
  147. }
  148. reference operator[](difference_type n) const { return *(*this + n); }
  149. bool operator!=(const mapped_iterator &X) const { return !operator==(X); }
  150. bool operator==(const mapped_iterator &X) const {
  151. return current == X.current;
  152. }
  153. bool operator<(const mapped_iterator &X) const { return current < X.current; }
  154. difference_type operator-(const mapped_iterator &X) const {
  155. return current - X.current;
  156. }
  157. };
  158. template <class Iterator, class Func>
  159. inline mapped_iterator<Iterator, Func>
  160. operator+(typename mapped_iterator<Iterator, Func>::difference_type N,
  161. const mapped_iterator<Iterator, Func> &X) {
  162. return mapped_iterator<Iterator, Func>(X.getCurrent() - N, X.getFunc());
  163. }
  164. // map_iterator - Provide a convenient way to create mapped_iterators, just like
  165. // make_pair is useful for creating pairs...
  166. //
  167. template <class ItTy, class FuncTy>
  168. inline mapped_iterator<ItTy, FuncTy> map_iterator(const ItTy &I, FuncTy F) {
  169. return mapped_iterator<ItTy, FuncTy>(I, F);
  170. }
  171. //===----------------------------------------------------------------------===//
  172. // Extra additions to <utility>
  173. //===----------------------------------------------------------------------===//
  174. /// \brief Function object to check whether the first component of a std::pair
  175. /// compares less than the first component of another std::pair.
  176. struct less_first {
  177. template <typename T> bool operator()(const T &lhs, const T &rhs) const {
  178. return lhs.first < rhs.first;
  179. }
  180. };
  181. /// \brief Function object to check whether the second component of a std::pair
  182. /// compares less than the second component of another std::pair.
  183. struct less_second {
  184. template <typename T> bool operator()(const T &lhs, const T &rhs) const {
  185. return lhs.second < rhs.second;
  186. }
  187. };
  188. // A subset of N3658. More stuff can be added as-needed.
  189. /// \brief Represents a compile-time sequence of integers.
  190. template <class T, T... I> struct integer_sequence {
  191. typedef T value_type;
  192. static LLVM_CONSTEXPR size_t size() { return sizeof...(I); }
  193. };
  194. /// \brief Alias for the common case of a sequence of size_ts.
  195. template <size_t... I>
  196. struct index_sequence : integer_sequence<std::size_t, I...> {};
  197. template <std::size_t N, std::size_t... I>
  198. struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
  199. template <std::size_t... I>
  200. struct build_index_impl<0, I...> : index_sequence<I...> {};
  201. /// \brief Creates a compile-time integer sequence for a parameter pack.
  202. template <class... Ts>
  203. struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
  204. //===----------------------------------------------------------------------===//
  205. // Extra additions for arrays
  206. //===----------------------------------------------------------------------===//
  207. /// Find the length of an array.
  208. template <class T, std::size_t N>
  209. LLVM_CONSTEXPR inline size_t array_lengthof(T (&)[N]) {
  210. return N;
  211. }
  212. /// Adapt std::less<T> for array_pod_sort.
  213. // HLSL Change: changed calling convention to __cdecl
  214. template<typename T>
  215. inline int __cdecl array_pod_sort_comparator(const void *P1, const void *P2) {
  216. if (std::less<T>()(*reinterpret_cast<const T*>(P1),
  217. *reinterpret_cast<const T*>(P2)))
  218. return -1;
  219. if (std::less<T>()(*reinterpret_cast<const T*>(P2),
  220. *reinterpret_cast<const T*>(P1)))
  221. return 1;
  222. return 0;
  223. }
  224. /// get_array_pod_sort_comparator - This is an internal helper function used to
  225. /// get type deduction of T right.
  226. //
  227. // HLSL Change: changed calling convention to __cdecl
  228. // HLSL Change: pulled this out into a typdef to make it easier to make change
  229. typedef int(__cdecl *llvm_cmp_func)(const void *, const void *);
  230. template<typename T>
  231. inline llvm_cmp_func get_array_pod_sort_comparator(const T &) {
  232. return array_pod_sort_comparator<T>;
  233. }
  234. /// array_pod_sort - This sorts an array with the specified start and end
  235. /// extent. This is just like std::sort, except that it calls qsort instead of
  236. /// using an inlined template. qsort is slightly slower than std::sort, but
  237. /// most sorts are not performance critical in LLVM and std::sort has to be
  238. /// template instantiated for each type, leading to significant measured code
  239. /// bloat. This function should generally be used instead of std::sort where
  240. /// possible.
  241. ///
  242. /// This function assumes that you have simple POD-like types that can be
  243. /// compared with std::less and can be moved with memcpy. If this isn't true,
  244. /// you should use std::sort.
  245. ///
  246. /// NOTE: If qsort_r were portable, we could allow a custom comparator and
  247. /// default to std::less.
  248. template<class IteratorTy>
  249. inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
  250. // Don't inefficiently call qsort with one element or trigger undefined
  251. // behavior with an empty sequence.
  252. auto NElts = End - Start;
  253. if (NElts <= 1) return;
  254. qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
  255. }
  256. // HLSL Change: changed calling convention of Compare to __cdecl
  257. template <class IteratorTy>
  258. inline void array_pod_sort(
  259. IteratorTy Start, IteratorTy End,
  260. int (__cdecl *Compare)(
  261. const typename std::iterator_traits<IteratorTy>::value_type *,
  262. const typename std::iterator_traits<IteratorTy>::value_type *)) {
  263. // Don't inefficiently call qsort with one element or trigger undefined
  264. // behavior with an empty sequence.
  265. auto NElts = End - Start;
  266. if (NElts <= 1) return;
  267. qsort(&*Start, NElts, sizeof(*Start),
  268. reinterpret_cast<int (__cdecl *)(const void *, const void *)>(Compare)); // HLSL Change - __cdecl
  269. }
  270. //===----------------------------------------------------------------------===//
  271. // Extra additions to <algorithm>
  272. //===----------------------------------------------------------------------===//
  273. /// For a container of pointers, deletes the pointers and then clears the
  274. /// container.
  275. template<typename Container>
  276. void DeleteContainerPointers(Container &C) {
  277. for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
  278. delete *I;
  279. C.clear();
  280. }
  281. /// In a container of pairs (usually a map) whose second element is a pointer,
  282. /// deletes the second elements and then clears the container.
  283. template<typename Container>
  284. void DeleteContainerSeconds(Container &C) {
  285. for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
  286. delete I->second;
  287. C.clear();
  288. }
  289. /// Provide wrappers to std::all_of which take ranges instead of having to pass
  290. /// being/end explicitly.
  291. template<typename R, class UnaryPredicate>
  292. bool all_of(R &&Range, UnaryPredicate &&P) {
  293. return std::all_of(Range.begin(), Range.end(),
  294. std::forward<UnaryPredicate>(P));
  295. }
  296. //===----------------------------------------------------------------------===//
  297. // Extra additions to <memory>
  298. // //
  299. ///////////////////////////////////////////////////////////////////////////////
  300. // Implement make_unique according to N3656.
  301. /// \brief Constructs a `new T()` with the given args and returns a
  302. /// `unique_ptr<T>` which owns the object.
  303. ///
  304. /// Example:
  305. ///
  306. /// auto p = make_unique<int>();
  307. /// auto p = make_unique<std::tuple<int, int>>(0, 1);
  308. template <class T, class... Args>
  309. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  310. make_unique(Args &&... args) {
  311. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  312. }
  313. /// \brief Constructs a `new T[n]` with the given args and returns a
  314. /// `unique_ptr<T[]>` which owns the object.
  315. ///
  316. /// \param n size of the new array.
  317. ///
  318. /// Example:
  319. ///
  320. /// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
  321. template <class T>
  322. typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
  323. std::unique_ptr<T>>::type
  324. make_unique(size_t n) {
  325. return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
  326. }
  327. /// This function isn't used and is only here to provide better compile errors.
  328. template <class T, class... Args>
  329. typename std::enable_if<std::extent<T>::value != 0>::type
  330. make_unique(Args &&...) = delete;
  331. struct FreeDeleter {
  332. void operator()(void* v) {
  333. ::free(v);
  334. }
  335. };
  336. template<typename First, typename Second>
  337. struct pair_hash {
  338. size_t operator()(const std::pair<First, Second> &P) const {
  339. return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
  340. }
  341. };
  342. /// A functor like C++14's std::less<void> in its absence.
  343. struct less {
  344. template <typename A, typename B> bool operator()(A &&a, B &&b) const {
  345. return std::forward<A>(a) < std::forward<B>(b);
  346. }
  347. };
  348. /// A functor like C++14's std::equal<void> in its absence.
  349. struct equal {
  350. template <typename A, typename B> bool operator()(A &&a, B &&b) const {
  351. return std::forward<A>(a) == std::forward<B>(b);
  352. }
  353. };
  354. /// Binary functor that adapts to any other binary functor after dereferencing
  355. /// operands.
  356. template <typename T> struct deref {
  357. T func;
  358. // Could be further improved to cope with non-derivable functors and
  359. // non-binary functors (should be a variadic template member function
  360. // operator()).
  361. template <typename A, typename B>
  362. auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
  363. assert(lhs);
  364. assert(rhs);
  365. return func(*lhs, *rhs);
  366. }
  367. };
  368. } // End llvm namespace
  369. #endif