STLExtras.h 14 KB

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