parallel_backend_tbb.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. // -*- C++ -*-
  2. //===-- parallel_backend_tbb.h --------------------------------------------===//
  3. //
  4. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. // See https://llvm.org/LICENSE.txt for license information.
  6. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #ifndef _PSTL_PARALLEL_BACKEND_TBB_H
  10. #define _PSTL_PARALLEL_BACKEND_TBB_H
  11. #include <algorithm>
  12. #include <type_traits>
  13. #include "parallel_backend_utils.h"
  14. // Bring in minimal required subset of Intel TBB
  15. #include <tbb/blocked_range.h>
  16. #include <tbb/parallel_for.h>
  17. #include <tbb/parallel_reduce.h>
  18. #include <tbb/parallel_scan.h>
  19. #include <tbb/parallel_invoke.h>
  20. #include <tbb/task_arena.h>
  21. #include <tbb/tbb_allocator.h>
  22. #if TBB_INTERFACE_VERSION < 10000
  23. # error Intel(R) Threading Building Blocks 2018 is required; older versions are not supported.
  24. #endif
  25. namespace __pstl
  26. {
  27. namespace __par_backend
  28. {
  29. //! Raw memory buffer with automatic freeing and no exceptions.
  30. /** Some of our algorithms need to start with raw memory buffer,
  31. not an initialize array, because initialization/destruction
  32. would make the span be at least O(N). */
  33. // tbb::allocator can improve performance in some cases.
  34. template <typename _Tp>
  35. class __buffer
  36. {
  37. tbb::tbb_allocator<_Tp> _M_allocator;
  38. _Tp* _M_ptr;
  39. const std::size_t _M_buf_size;
  40. __buffer(const __buffer&) = delete;
  41. void
  42. operator=(const __buffer&) = delete;
  43. public:
  44. //! Try to obtain buffer of given size to store objects of _Tp type
  45. __buffer(std::size_t n) : _M_allocator(), _M_ptr(_M_allocator.allocate(n)), _M_buf_size(n) {}
  46. //! True if buffer was successfully obtained, zero otherwise.
  47. operator bool() const { return _M_ptr != NULL; }
  48. //! Return pointer to buffer, or NULL if buffer could not be obtained.
  49. _Tp*
  50. get() const
  51. {
  52. return _M_ptr;
  53. }
  54. //! Destroy buffer
  55. ~__buffer() { _M_allocator.deallocate(_M_ptr, _M_buf_size); }
  56. };
  57. // Wrapper for tbb::task
  58. inline void
  59. __cancel_execution()
  60. {
  61. tbb::task::self().group()->cancel_group_execution();
  62. }
  63. //------------------------------------------------------------------------
  64. // parallel_for
  65. //------------------------------------------------------------------------
  66. template <class _Index, class _RealBody>
  67. class __parallel_for_body
  68. {
  69. public:
  70. __parallel_for_body(const _RealBody& __body) : _M_body(__body) {}
  71. __parallel_for_body(const __parallel_for_body& __body) : _M_body(__body._M_body) {}
  72. void
  73. operator()(const tbb::blocked_range<_Index>& __range) const
  74. {
  75. _M_body(__range.begin(), __range.end());
  76. }
  77. private:
  78. _RealBody _M_body;
  79. };
  80. //! Evaluation of brick f[i,j) for each subrange [i,j) of [first,last)
  81. // wrapper over tbb::parallel_for
  82. template <class _ExecutionPolicy, class _Index, class _Fp>
  83. void
  84. __parallel_for(_ExecutionPolicy&&, _Index __first, _Index __last, _Fp __f)
  85. {
  86. tbb::this_task_arena::isolate([=]() {
  87. tbb::parallel_for(tbb::blocked_range<_Index>(__first, __last), __parallel_for_body<_Index, _Fp>(__f));
  88. });
  89. }
  90. //! Evaluation of brick f[i,j) for each subrange [i,j) of [first,last)
  91. // wrapper over tbb::parallel_reduce
  92. template <class _ExecutionPolicy, class _Value, class _Index, typename _RealBody, typename _Reduction>
  93. _Value
  94. __parallel_reduce(_ExecutionPolicy&&, _Index __first, _Index __last, const _Value& __identity,
  95. const _RealBody& __real_body, const _Reduction& __reduction)
  96. {
  97. return tbb::this_task_arena::isolate([__first, __last, &__identity, &__real_body, &__reduction]() -> _Value {
  98. return tbb::parallel_reduce(
  99. tbb::blocked_range<_Index>(__first, __last), __identity,
  100. [__real_body](const tbb::blocked_range<_Index>& __r, const _Value& __value) -> _Value {
  101. return __real_body(__r.begin(), __r.end(), __value);
  102. },
  103. __reduction);
  104. });
  105. }
  106. //------------------------------------------------------------------------
  107. // parallel_transform_reduce
  108. //
  109. // Notation:
  110. // r(i,j,init) returns reduction of init with reduction over [i,j)
  111. // u(i) returns f(i,i+1,identity) for a hypothetical left identity element of r
  112. // c(x,y) combines values x and y that were the result of r or u
  113. //------------------------------------------------------------------------
  114. template <class _Index, class _Up, class _Tp, class _Cp, class _Rp>
  115. struct __par_trans_red_body
  116. {
  117. alignas(_Tp) char _M_sum_storage[sizeof(_Tp)]; // Holds generalized non-commutative sum when has_sum==true
  118. _Rp _M_brick_reduce; // Most likely to have non-empty layout
  119. _Up _M_u;
  120. _Cp _M_combine;
  121. bool _M_has_sum; // Put last to minimize size of class
  122. _Tp&
  123. sum()
  124. {
  125. _PSTL_ASSERT_MSG(_M_has_sum, "sum expected");
  126. return *(_Tp*)_M_sum_storage;
  127. }
  128. __par_trans_red_body(_Up __u, _Tp __init, _Cp __c, _Rp __r)
  129. : _M_brick_reduce(__r), _M_u(__u), _M_combine(__c), _M_has_sum(true)
  130. {
  131. new (_M_sum_storage) _Tp(__init);
  132. }
  133. __par_trans_red_body(__par_trans_red_body& __left, tbb::split)
  134. : _M_brick_reduce(__left._M_brick_reduce), _M_u(__left._M_u), _M_combine(__left._M_combine), _M_has_sum(false)
  135. {
  136. }
  137. ~__par_trans_red_body()
  138. {
  139. // 17.6.5.12 tells us to not worry about catching exceptions from destructors.
  140. if (_M_has_sum)
  141. sum().~_Tp();
  142. }
  143. void
  144. join(__par_trans_red_body& __rhs)
  145. {
  146. sum() = _M_combine(sum(), __rhs.sum());
  147. }
  148. void
  149. operator()(const tbb::blocked_range<_Index>& __range)
  150. {
  151. _Index __i = __range.begin();
  152. _Index __j = __range.end();
  153. if (!_M_has_sum)
  154. {
  155. _PSTL_ASSERT_MSG(__range.size() > 1, "there should be at least 2 elements");
  156. new (&_M_sum_storage)
  157. _Tp(_M_combine(_M_u(__i), _M_u(__i + 1))); // The condition i+1 < j is provided by the grain size of 3
  158. _M_has_sum = true;
  159. std::advance(__i, 2);
  160. if (__i == __j)
  161. return;
  162. }
  163. sum() = _M_brick_reduce(__i, __j, sum());
  164. }
  165. };
  166. template <class _ExecutionPolicy, class _Index, class _Up, class _Tp, class _Cp, class _Rp>
  167. _Tp
  168. __parallel_transform_reduce(_ExecutionPolicy&&, _Index __first, _Index __last, _Up __u, _Tp __init, _Cp __combine,
  169. _Rp __brick_reduce)
  170. {
  171. __par_backend::__par_trans_red_body<_Index, _Up, _Tp, _Cp, _Rp> __body(__u, __init, __combine, __brick_reduce);
  172. // The grain size of 3 is used in order to provide mininum 2 elements for each body
  173. tbb::this_task_arena::isolate(
  174. [__first, __last, &__body]() { tbb::parallel_reduce(tbb::blocked_range<_Index>(__first, __last, 3), __body); });
  175. return __body.sum();
  176. }
  177. //------------------------------------------------------------------------
  178. // parallel_scan
  179. //------------------------------------------------------------------------
  180. template <class _Index, class _Up, class _Tp, class _Cp, class _Rp, class _Sp>
  181. class __trans_scan_body
  182. {
  183. alignas(_Tp) char _M_sum_storage[sizeof(_Tp)]; // Holds generalized non-commutative sum when has_sum==true
  184. _Rp _M_brick_reduce; // Most likely to have non-empty layout
  185. _Up _M_u;
  186. _Cp _M_combine;
  187. _Sp _M_scan;
  188. bool _M_has_sum; // Put last to minimize size of class
  189. public:
  190. __trans_scan_body(_Up __u, _Tp __init, _Cp __combine, _Rp __reduce, _Sp __scan)
  191. : _M_brick_reduce(__reduce), _M_u(__u), _M_combine(__combine), _M_scan(__scan), _M_has_sum(true)
  192. {
  193. new (_M_sum_storage) _Tp(__init);
  194. }
  195. __trans_scan_body(__trans_scan_body& __b, tbb::split)
  196. : _M_brick_reduce(__b._M_brick_reduce), _M_u(__b._M_u), _M_combine(__b._M_combine), _M_scan(__b._M_scan),
  197. _M_has_sum(false)
  198. {
  199. }
  200. ~__trans_scan_body()
  201. {
  202. // 17.6.5.12 tells us to not worry about catching exceptions from destructors.
  203. if (_M_has_sum)
  204. sum().~_Tp();
  205. }
  206. _Tp&
  207. sum() const
  208. {
  209. _PSTL_ASSERT_MSG(_M_has_sum, "sum expected");
  210. return *const_cast<_Tp*>(reinterpret_cast<_Tp const*>(_M_sum_storage));
  211. }
  212. void
  213. operator()(const tbb::blocked_range<_Index>& __range, tbb::pre_scan_tag)
  214. {
  215. _Index __i = __range.begin();
  216. _Index __j = __range.end();
  217. if (!_M_has_sum)
  218. {
  219. new (&_M_sum_storage) _Tp(_M_u(__i));
  220. _M_has_sum = true;
  221. ++__i;
  222. if (__i == __j)
  223. return;
  224. }
  225. sum() = _M_brick_reduce(__i, __j, sum());
  226. }
  227. void
  228. operator()(const tbb::blocked_range<_Index>& __range, tbb::final_scan_tag)
  229. {
  230. sum() = _M_scan(__range.begin(), __range.end(), sum());
  231. }
  232. void
  233. reverse_join(__trans_scan_body& __a)
  234. {
  235. if (_M_has_sum)
  236. {
  237. sum() = _M_combine(__a.sum(), sum());
  238. }
  239. else
  240. {
  241. new (&_M_sum_storage) _Tp(__a.sum());
  242. _M_has_sum = true;
  243. }
  244. }
  245. void
  246. assign(__trans_scan_body& __b)
  247. {
  248. sum() = __b.sum();
  249. }
  250. };
  251. template <typename _Index>
  252. _Index
  253. __split(_Index __m)
  254. {
  255. _Index __k = 1;
  256. while (2 * __k < __m)
  257. __k *= 2;
  258. return __k;
  259. }
  260. //------------------------------------------------------------------------
  261. // __parallel_strict_scan
  262. //------------------------------------------------------------------------
  263. template <typename _Index, typename _Tp, typename _Rp, typename _Cp>
  264. void
  265. __upsweep(_Index __i, _Index __m, _Index __tilesize, _Tp* __r, _Index __lastsize, _Rp __reduce, _Cp __combine)
  266. {
  267. if (__m == 1)
  268. __r[0] = __reduce(__i * __tilesize, __lastsize);
  269. else
  270. {
  271. _Index __k = __split(__m);
  272. tbb::parallel_invoke(
  273. [=] { __par_backend::__upsweep(__i, __k, __tilesize, __r, __tilesize, __reduce, __combine); },
  274. [=] {
  275. __par_backend::__upsweep(__i + __k, __m - __k, __tilesize, __r + __k, __lastsize, __reduce, __combine);
  276. });
  277. if (__m == 2 * __k)
  278. __r[__m - 1] = __combine(__r[__k - 1], __r[__m - 1]);
  279. }
  280. }
  281. template <typename _Index, typename _Tp, typename _Cp, typename _Sp>
  282. void
  283. __downsweep(_Index __i, _Index __m, _Index __tilesize, _Tp* __r, _Index __lastsize, _Tp __initial, _Cp __combine,
  284. _Sp __scan)
  285. {
  286. if (__m == 1)
  287. __scan(__i * __tilesize, __lastsize, __initial);
  288. else
  289. {
  290. const _Index __k = __split(__m);
  291. tbb::parallel_invoke(
  292. [=] { __par_backend::__downsweep(__i, __k, __tilesize, __r, __tilesize, __initial, __combine, __scan); },
  293. // Assumes that __combine never throws.
  294. //TODO: Consider adding a requirement for user functors to be constant.
  295. [=, &__combine] {
  296. __par_backend::__downsweep(__i + __k, __m - __k, __tilesize, __r + __k, __lastsize,
  297. __combine(__initial, __r[__k - 1]), __combine, __scan);
  298. });
  299. }
  300. }
  301. // Adapted from Intel(R) Cilk(TM) version from cilkpub.
  302. // Let i:len denote a counted interval of length n starting at i. s denotes a generalized-sum value.
  303. // Expected actions of the functors are:
  304. // reduce(i,len) -> s -- return reduction value of i:len.
  305. // combine(s1,s2) -> s -- return merged sum
  306. // apex(s) -- do any processing necessary between reduce and scan.
  307. // scan(i,len,initial) -- perform scan over i:len starting with initial.
  308. // The initial range 0:n is partitioned into consecutive subranges.
  309. // reduce and scan are each called exactly once per subrange.
  310. // Thus callers can rely upon side effects in reduce.
  311. // combine must not throw an exception.
  312. // apex is called exactly once, after all calls to reduce and before all calls to scan.
  313. // For example, it's useful for allocating a __buffer used by scan but whose size is the sum of all reduction values.
  314. // T must have a trivial constructor and destructor.
  315. template <class _ExecutionPolicy, typename _Index, typename _Tp, typename _Rp, typename _Cp, typename _Sp, typename _Ap>
  316. void
  317. __parallel_strict_scan(_ExecutionPolicy&&, _Index __n, _Tp __initial, _Rp __reduce, _Cp __combine, _Sp __scan,
  318. _Ap __apex)
  319. {
  320. tbb::this_task_arena::isolate([=, &__combine]() {
  321. if (__n > 1)
  322. {
  323. _Index __p = tbb::this_task_arena::max_concurrency();
  324. const _Index __slack = 4;
  325. _Index __tilesize = (__n - 1) / (__slack * __p) + 1;
  326. _Index __m = (__n - 1) / __tilesize;
  327. __buffer<_Tp> __buf(__m + 1);
  328. _Tp* __r = __buf.get();
  329. __par_backend::__upsweep(_Index(0), _Index(__m + 1), __tilesize, __r, __n - __m * __tilesize, __reduce,
  330. __combine);
  331. // When __apex is a no-op and __combine has no side effects, a good optimizer
  332. // should be able to eliminate all code between here and __apex.
  333. // Alternatively, provide a default value for __apex that can be
  334. // recognized by metaprogramming that conditionlly executes the following.
  335. size_t __k = __m + 1;
  336. _Tp __t = __r[__k - 1];
  337. while ((__k &= __k - 1))
  338. __t = __combine(__r[__k - 1], __t);
  339. __apex(__combine(__initial, __t));
  340. __par_backend::__downsweep(_Index(0), _Index(__m + 1), __tilesize, __r, __n - __m * __tilesize, __initial,
  341. __combine, __scan);
  342. return;
  343. }
  344. // Fewer than 2 elements in sequence, or out of memory. Handle has single block.
  345. _Tp __sum = __initial;
  346. if (__n)
  347. __sum = __combine(__sum, __reduce(_Index(0), __n));
  348. __apex(__sum);
  349. if (__n)
  350. __scan(_Index(0), __n, __initial);
  351. });
  352. }
  353. template <class _ExecutionPolicy, class _Index, class _Up, class _Tp, class _Cp, class _Rp, class _Sp>
  354. _Tp
  355. __parallel_transform_scan(_ExecutionPolicy&&, _Index __n, _Up __u, _Tp __init, _Cp __combine, _Rp __brick_reduce,
  356. _Sp __scan)
  357. {
  358. __trans_scan_body<_Index, _Up, _Tp, _Cp, _Rp, _Sp> __body(__u, __init, __combine, __brick_reduce, __scan);
  359. auto __range = tbb::blocked_range<_Index>(0, __n);
  360. tbb::this_task_arena::isolate([__range, &__body]() { tbb::parallel_scan(__range, __body); });
  361. return __body.sum();
  362. }
  363. //------------------------------------------------------------------------
  364. // parallel_stable_sort
  365. //------------------------------------------------------------------------
  366. //------------------------------------------------------------------------
  367. // stable_sort utilities
  368. //
  369. // These are used by parallel implementations but do not depend on them.
  370. //------------------------------------------------------------------------
  371. template <typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename _RandomAccessIterator3,
  372. typename _Compare, typename _Cleanup, typename _LeafMerge>
  373. class __merge_task : public tbb::task
  374. {
  375. /*override*/ tbb::task*
  376. execute();
  377. _RandomAccessIterator1 _M_xs, _M_xe;
  378. _RandomAccessIterator2 _M_ys, _M_ye;
  379. _RandomAccessIterator3 _M_zs;
  380. _Compare _M_comp;
  381. _Cleanup _M_cleanup;
  382. _LeafMerge _M_leaf_merge;
  383. public:
  384. __merge_task(_RandomAccessIterator1 __xs, _RandomAccessIterator1 __xe, _RandomAccessIterator2 __ys,
  385. _RandomAccessIterator2 __ye, _RandomAccessIterator3 __zs, _Compare __comp, _Cleanup __cleanup,
  386. _LeafMerge __leaf_merge)
  387. : _M_xs(__xs), _M_xe(__xe), _M_ys(__ys), _M_ye(__ye), _M_zs(__zs), _M_comp(__comp), _M_cleanup(__cleanup),
  388. _M_leaf_merge(__leaf_merge)
  389. {
  390. }
  391. };
  392. #define _PSTL_MERGE_CUT_OFF 2000
  393. template <typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename _RandomAccessIterator3,
  394. typename __M_Compare, typename _Cleanup, typename _LeafMerge>
  395. tbb::task*
  396. __merge_task<_RandomAccessIterator1, _RandomAccessIterator2, _RandomAccessIterator3, __M_Compare, _Cleanup,
  397. _LeafMerge>::execute()
  398. {
  399. typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type _DifferenceType1;
  400. typedef typename std::iterator_traits<_RandomAccessIterator2>::difference_type _DifferenceType2;
  401. typedef typename std::common_type<_DifferenceType1, _DifferenceType2>::type _SizeType;
  402. const _SizeType __n = (_M_xe - _M_xs) + (_M_ye - _M_ys);
  403. const _SizeType __merge_cut_off = _PSTL_MERGE_CUT_OFF;
  404. if (__n <= __merge_cut_off)
  405. {
  406. _M_leaf_merge(_M_xs, _M_xe, _M_ys, _M_ye, _M_zs, _M_comp);
  407. //we clean the buffer one time on last step of the sort
  408. _M_cleanup(_M_xs, _M_xe);
  409. _M_cleanup(_M_ys, _M_ye);
  410. return nullptr;
  411. }
  412. else
  413. {
  414. _RandomAccessIterator1 __xm;
  415. _RandomAccessIterator2 __ym;
  416. if (_M_xe - _M_xs < _M_ye - _M_ys)
  417. {
  418. __ym = _M_ys + (_M_ye - _M_ys) / 2;
  419. __xm = std::upper_bound(_M_xs, _M_xe, *__ym, _M_comp);
  420. }
  421. else
  422. {
  423. __xm = _M_xs + (_M_xe - _M_xs) / 2;
  424. __ym = std::lower_bound(_M_ys, _M_ye, *__xm, _M_comp);
  425. }
  426. const _RandomAccessIterator3 __zm = _M_zs + ((__xm - _M_xs) + (__ym - _M_ys));
  427. tbb::task* __right = new (tbb::task::allocate_additional_child_of(*parent()))
  428. __merge_task(__xm, _M_xe, __ym, _M_ye, __zm, _M_comp, _M_cleanup, _M_leaf_merge);
  429. tbb::task::spawn(*__right);
  430. tbb::task::recycle_as_continuation();
  431. _M_xe = __xm;
  432. _M_ye = __ym;
  433. }
  434. return this;
  435. }
  436. template <typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename _Compare, typename _LeafSort>
  437. class __stable_sort_task : public tbb::task
  438. {
  439. public:
  440. typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type _DifferenceType1;
  441. typedef typename std::iterator_traits<_RandomAccessIterator2>::difference_type _DifferenceType2;
  442. typedef typename std::common_type<_DifferenceType1, _DifferenceType2>::type _SizeType;
  443. private:
  444. /*override*/ tbb::task*
  445. execute();
  446. _RandomAccessIterator1 _M_xs, _M_xe;
  447. _RandomAccessIterator2 _M_zs;
  448. _Compare _M_comp;
  449. _LeafSort _M_leaf_sort;
  450. int32_t _M_inplace;
  451. _SizeType _M_nsort;
  452. public:
  453. __stable_sort_task(_RandomAccessIterator1 __xs, _RandomAccessIterator1 __xe, _RandomAccessIterator2 __zs,
  454. int32_t __inplace, _Compare __comp, _LeafSort __leaf_sort, _SizeType __n)
  455. : _M_xs(__xs), _M_xe(__xe), _M_zs(__zs), _M_comp(__comp), _M_leaf_sort(__leaf_sort), _M_inplace(__inplace),
  456. _M_nsort(__n)
  457. {
  458. }
  459. };
  460. //! Binary operator that does nothing
  461. struct __binary_no_op
  462. {
  463. template <typename _Tp>
  464. void operator()(_Tp, _Tp)
  465. {
  466. }
  467. };
  468. #define _PSTL_STABLE_SORT_CUT_OFF 500
  469. template <typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename _Compare, typename _LeafSort>
  470. tbb::task*
  471. __stable_sort_task<_RandomAccessIterator1, _RandomAccessIterator2, _Compare, _LeafSort>::execute()
  472. {
  473. const _SizeType __n = _M_xe - _M_xs;
  474. const _SizeType __nmerge = _M_nsort > 0 ? _M_nsort : __n;
  475. const _SizeType __sort_cut_off = _PSTL_STABLE_SORT_CUT_OFF;
  476. if (__n <= __sort_cut_off)
  477. {
  478. _M_leaf_sort(_M_xs, _M_xe, _M_comp);
  479. if (_M_inplace != 2)
  480. __par_backend::__init_buf(_M_xs, _M_xe, _M_zs, _M_inplace == 0);
  481. return NULL;
  482. }
  483. else
  484. {
  485. const _RandomAccessIterator1 __xm = _M_xs + __n / 2;
  486. const _RandomAccessIterator2 __zm = _M_zs + (__xm - _M_xs);
  487. const _RandomAccessIterator2 __ze = _M_zs + __n;
  488. task* __m;
  489. auto __move_values = [](_RandomAccessIterator2 __x, _RandomAccessIterator1 __z) { *__z = std::move(*__x); };
  490. auto __move_sequences = [](_RandomAccessIterator2 __first1, _RandomAccessIterator2 __last1,
  491. _RandomAccessIterator1 __first2) { return std::move(__first1, __last1, __first2); };
  492. if (_M_inplace == 2)
  493. __m = new (tbb::task::allocate_continuation())
  494. __merge_task<_RandomAccessIterator2, _RandomAccessIterator2, _RandomAccessIterator1, _Compare,
  495. __serial_destroy,
  496. __par_backend::__serial_move_merge<decltype(__move_values), decltype(__move_sequences)>>(
  497. _M_zs, __zm, __zm, __ze, _M_xs, _M_comp, __serial_destroy(),
  498. __par_backend::__serial_move_merge<decltype(__move_values), decltype(__move_sequences)>(
  499. __nmerge, __move_values, __move_sequences));
  500. else if (_M_inplace)
  501. __m = new (tbb::task::allocate_continuation())
  502. __merge_task<_RandomAccessIterator2, _RandomAccessIterator2, _RandomAccessIterator1, _Compare,
  503. __par_backend::__binary_no_op,
  504. __par_backend::__serial_move_merge<decltype(__move_values), decltype(__move_sequences)>>(
  505. _M_zs, __zm, __zm, __ze, _M_xs, _M_comp, __par_backend::__binary_no_op(),
  506. __par_backend::__serial_move_merge<decltype(__move_values), decltype(__move_sequences)>(
  507. __nmerge, __move_values, __move_sequences));
  508. else
  509. {
  510. auto __move_values = [](_RandomAccessIterator1 __x, _RandomAccessIterator2 __z) { *__z = std::move(*__x); };
  511. auto __move_sequences = [](_RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1,
  512. _RandomAccessIterator2 __first2) {
  513. return std::move(__first1, __last1, __first2);
  514. };
  515. __m = new (tbb::task::allocate_continuation())
  516. __merge_task<_RandomAccessIterator1, _RandomAccessIterator1, _RandomAccessIterator2, _Compare,
  517. __par_backend::__binary_no_op,
  518. __par_backend::__serial_move_merge<decltype(__move_values), decltype(__move_sequences)>>(
  519. _M_xs, __xm, __xm, _M_xe, _M_zs, _M_comp, __par_backend::__binary_no_op(),
  520. __par_backend::__serial_move_merge<decltype(__move_values), decltype(__move_sequences)>(
  521. __nmerge, __move_values, __move_sequences));
  522. }
  523. __m->set_ref_count(2);
  524. task* __right = new (__m->allocate_child())
  525. __stable_sort_task(__xm, _M_xe, __zm, !_M_inplace, _M_comp, _M_leaf_sort, __nmerge);
  526. tbb::task::spawn(*__right);
  527. tbb::task::recycle_as_child_of(*__m);
  528. _M_xe = __xm;
  529. _M_inplace = !_M_inplace;
  530. }
  531. return this;
  532. }
  533. template <class _ExecutionPolicy, typename _RandomAccessIterator, typename _Compare, typename _LeafSort>
  534. void
  535. __parallel_stable_sort(_ExecutionPolicy&&, _RandomAccessIterator __xs, _RandomAccessIterator __xe, _Compare __comp,
  536. _LeafSort __leaf_sort, std::size_t __nsort = 0)
  537. {
  538. tbb::this_task_arena::isolate([=, &__nsort]() {
  539. //sorting based on task tree and parallel merge
  540. typedef typename std::iterator_traits<_RandomAccessIterator>::value_type _ValueType;
  541. typedef typename std::iterator_traits<_RandomAccessIterator>::difference_type _DifferenceType;
  542. const _DifferenceType __n = __xe - __xs;
  543. if (__nsort == 0)
  544. __nsort = __n;
  545. const _DifferenceType __sort_cut_off = _PSTL_STABLE_SORT_CUT_OFF;
  546. if (__n > __sort_cut_off)
  547. {
  548. _PSTL_ASSERT(__nsort > 0 && __nsort <= __n);
  549. __buffer<_ValueType> __buf(__n);
  550. using tbb::task;
  551. task::spawn_root_and_wait(*new (task::allocate_root())
  552. __stable_sort_task<_RandomAccessIterator, _ValueType*, _Compare, _LeafSort>(
  553. __xs, __xe, (_ValueType*)__buf.get(), 2, __comp, __leaf_sort, __nsort));
  554. return;
  555. }
  556. //serial sort
  557. __leaf_sort(__xs, __xe, __comp);
  558. });
  559. }
  560. //------------------------------------------------------------------------
  561. // parallel_merge
  562. //------------------------------------------------------------------------
  563. template <class _ExecutionPolicy, typename _RandomAccessIterator1, typename _RandomAccessIterator2,
  564. typename _RandomAccessIterator3, typename _Compare, typename _LeafMerge>
  565. void
  566. __parallel_merge(_ExecutionPolicy&&, _RandomAccessIterator1 __xs, _RandomAccessIterator1 __xe,
  567. _RandomAccessIterator2 __ys, _RandomAccessIterator2 __ye, _RandomAccessIterator3 __zs, _Compare __comp,
  568. _LeafMerge __leaf_merge)
  569. {
  570. typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type _DifferenceType1;
  571. typedef typename std::iterator_traits<_RandomAccessIterator2>::difference_type _DifferenceType2;
  572. typedef typename std::common_type<_DifferenceType1, _DifferenceType2>::type _SizeType;
  573. const _SizeType __n = (__xe - __xs) + (__ye - __ys);
  574. const _SizeType __merge_cut_off = _PSTL_MERGE_CUT_OFF;
  575. if (__n <= __merge_cut_off)
  576. {
  577. // Fall back on serial merge
  578. __leaf_merge(__xs, __xe, __ys, __ye, __zs, __comp);
  579. }
  580. else
  581. {
  582. tbb::this_task_arena::isolate([=]() {
  583. typedef __merge_task<_RandomAccessIterator1, _RandomAccessIterator2, _RandomAccessIterator3, _Compare,
  584. __par_backend::__binary_no_op, _LeafMerge>
  585. _TaskType;
  586. tbb::task::spawn_root_and_wait(*new (tbb::task::allocate_root()) _TaskType(
  587. __xs, __xe, __ys, __ye, __zs, __comp, __par_backend::__binary_no_op(), __leaf_merge));
  588. });
  589. }
  590. }
  591. //------------------------------------------------------------------------
  592. // parallel_invoke
  593. //------------------------------------------------------------------------
  594. template <class _ExecutionPolicy, typename _F1, typename _F2>
  595. void
  596. __parallel_invoke(_ExecutionPolicy&&, _F1&& __f1, _F2&& __f2)
  597. {
  598. //TODO: a version of tbb::this_task_arena::isolate with variadic arguments pack should be added in the future
  599. tbb::this_task_arena::isolate([&]() { tbb::parallel_invoke(std::forward<_F1>(__f1), std::forward<_F2>(__f2)); });
  600. }
  601. } // namespace __par_backend
  602. } // namespace __pstl
  603. #endif /* _PSTL_PARALLEL_BACKEND_TBB_H */