okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

main
36.1 KiB990 linesraw
1//==---- vector.h ---------------------------------*- C++ -*----------------==//
2//
3// Copyright (C) Intel Corporation
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5// See https://llvm.org/LICENSE.txt for license information.
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef __DPCT_VECTOR_H__
10#define __DPCT_VECTOR_H__
11
12#include <oneapi/dpl/algorithm>
13#include <oneapi/dpl/execution>
14#include <oneapi/dpl/memory>
15
16#include "memory.h"
17
18#include <algorithm>
19#include <iterator>
20#include <vector>
21
22namespace dpct {
23
24namespace internal {
25template <typename Iter, typename Void = void> // for non-iterators
26struct is_iterator : std::false_type {};
27
28template <typename Iter> // For iterators
29struct is_iterator<
30    Iter,
31    typename std::enable_if<
32        !std::is_void<typename Iter::iterator_category>::value, void>::type>
33    : std::true_type {};
34
35template <typename T> // For pointers
36struct is_iterator<T *> : std::true_type {};
37} // end namespace internal
38
39#ifndef DPCT_USM_LEVEL_NONE
40
41// device_allocator_traits is a helper struct which makes use of custom
42//  allocator constructor routines when they are specified serially on the host,
43//  while enabling oneDPL pstl accelleration when such custom constructors are
44//  not provided.
45template <typename _Allocator> struct device_allocator_traits {
46
47  // taken from libc++
48  template <class, class _Alloc, class... _Args>
49  struct __has_construct_impl : ::std::false_type {};
50
51  template <class _Alloc, class... _Args>
52  struct __has_construct_impl<decltype((void)std::declval<_Alloc>().construct(
53                                  std::declval<_Args>()...)),
54                              _Alloc, _Args...> : ::std::true_type {};
55
56  template <class _Alloc, class... _Args>
57  struct __has_construct : __has_construct_impl<void, _Alloc, _Args...> {};
58
59  template <class _Alloc, class _Pointer, class = void>
60  struct __has_destroy : ::std::false_type {};
61
62  template <class _Alloc, class _Pointer>
63  struct __has_destroy<_Alloc, _Pointer,
64                       decltype((void)std::declval<_Alloc>().destroy(
65                           std::declval<_Pointer>()))> : ::std::true_type {};
66  // end of taken from libc++
67
68  template <typename T, typename Size>
69  static void uninitialized_value_construct_n(_Allocator alloc, T *p, Size n) {
70    assert(p != nullptr && "value constructing null data");
71    if constexpr (__has_construct<_Allocator, T *>::value) {
72      for (Size i = 0; i < n; i++) {
73        ::std::allocator_traits<_Allocator>::construct(alloc, p + i);
74      }
75    } else {
76      ::std::uninitialized_value_construct_n(
77          oneapi::dpl::execution::make_device_policy(
78              ::dpct::cs::get_default_queue()),
79          p, n);
80    }
81  }
82
83  template <typename T, typename Size, typename Value>
84  static void uninitialized_fill_n(_Allocator alloc, T *first, Size n,
85                                   const Value &value) {
86    assert(first != nullptr && "filling null data");
87    if constexpr (__has_construct<_Allocator, T *, const Value &>::value) {
88      for (Size i = 0; i < n; i++) {
89        ::std::allocator_traits<_Allocator>::construct(alloc, first + i, value);
90      }
91    } else {
92      ::std::uninitialized_fill_n(oneapi::dpl::execution::make_device_policy(
93                                      ::dpct::cs::get_default_queue()),
94                                  first, n, value);
95    }
96  }
97
98  template <typename Iter1, typename Size, typename T>
99  static void __uninitialized_custom_copy_n(_Allocator alloc, Iter1 first,
100                                            Size n, T *d_first) {
101    for (Size i = 0; i < n; i++) {
102      ::std::allocator_traits<_Allocator>::construct(alloc, d_first + i,
103                                                     *(first + i));
104    }
105  }
106
107  template <typename Iter1, typename Size, typename T>
108  static void uninitialized_device_copy_n(_Allocator alloc, Iter1 first, Size n,
109                                          T *d_first) {
110    assert(d_first != nullptr && "copying into null data");
111    if constexpr (__has_construct<_Allocator, T *,
112                                  typename ::std::iterator_traits<
113                                      Iter1>::value_type>::value) {
114      __uninitialized_custom_copy_n(alloc, first, n, d_first);
115    } else {
116      ::std::uninitialized_copy_n(oneapi::dpl::execution::make_device_policy(
117                                      ::dpct::cs::get_default_queue()),
118                                  first, n, d_first);
119    }
120  }
121
122  template <typename Iter1, typename Size, typename T>
123  static void uninitialized_host_copy_n(_Allocator alloc, Iter1 first, Size n,
124                                        T *d_first) {
125    assert(d_first != nullptr && "copying into null data");
126    if constexpr (__has_construct<_Allocator, T *,
127                                  typename ::std::iterator_traits<
128                                      Iter1>::value_type>::value) {
129      __uninitialized_custom_copy_n(alloc, first, n, d_first);
130    } else {
131      ::std::uninitialized_copy_n(first, n, d_first);
132    }
133  }
134
135  template <typename T, typename Size>
136  static void destroy_n(_Allocator alloc, T *p, Size n) {
137    assert(p != nullptr && "destroying null data");
138    if constexpr (__has_destroy<_Allocator, T *>::value) {
139      for (Size i = 0; i < n; i++) {
140        ::std::allocator_traits<_Allocator>::destroy(alloc, p + i);
141      }
142    } else {
143      ::std::destroy_n(oneapi::dpl::execution::make_device_policy(
144                           ::dpct::cs::get_default_queue()),
145                       p, n);
146    }
147  }
148};
149
150template <typename T,
151          typename Allocator = sycl::usm_allocator<T, sycl::usm::alloc::shared>>
152class device_vector {
153public:
154  using iterator = device_iterator<T>;
155  using const_iterator = const iterator;
156  using reference = device_reference<T>;
157  using const_reference = const reference;
158  using value_type = T;
159  using pointer = device_pointer<T>;
160  using const_pointer = device_pointer<const T>;
161  using difference_type =
162      typename ::std::iterator_traits<iterator>::difference_type;
163  using size_type = ::std::size_t;
164  using allocator_type = Allocator;
165  using alloc_traits = ::std::allocator_traits<Allocator>;
166
167private:
168  Allocator _alloc;
169  size_type _size;
170  size_type _capacity;
171  T *_storage;
172
173  size_type _min_capacity() const { return size_type(1); }
174
175  void _set_capacity_and_alloc() {
176    _capacity = (::std::max)(_size * 2, _min_capacity());
177    _storage = alloc_traits::allocate(_alloc, _capacity);
178  }
179
180  void _construct(size_type n, size_type start_idx = 0) {
181    if (n > 0) {
182      device_allocator_traits<Allocator>::uninitialized_value_construct_n(
183          _alloc, _storage + start_idx, n);
184    }
185  }
186
187  void _construct(size_type n, const T &value, size_type start_idx = 0) {
188    if (n > 0) {
189      device_allocator_traits<Allocator>::uninitialized_fill_n(
190          _alloc, _storage + start_idx, n, value);
191    }
192  }
193
194  template <typename Iter>
195  void _construct_iter(Iter first, size_type n, size_type start_idx = 0) {
196    if (n > 0) {
197      device_allocator_traits<Allocator>::uninitialized_device_copy_n(
198          _alloc, first, n, _storage + start_idx);
199    }
200  }
201
202  template <typename Iter>
203  void _construct_iter_host(Iter first, size_type n, size_type start_idx = 0) {
204    if (n > 0) {
205      device_allocator_traits<Allocator>::uninitialized_host_copy_n(
206          _alloc, first, n, _storage + start_idx);
207    }
208  }
209
210  void _destroy(size_type n, size_type start_idx = 0) {
211    if (n > 0) {
212      device_allocator_traits<Allocator>::destroy_n(_alloc,
213                                                    _storage + start_idx, n);
214    }
215  }
216
217  void _assign_elements(const device_vector &other) {
218    if (other.size() <= _size) {
219      // if incoming elements fit within existing elements, copy then destroy
220      // excess
221      ::std::copy(oneapi::dpl::execution::make_device_policy(
222                      ::dpct::cs::get_default_queue()),
223                  other.begin(), other.end(), begin());
224      resize(other.size());
225    } else if (other.size() < _capacity) {
226      // if incoming elements don't fit within existing elements but do fit
227      // within total capacity
228      // copy elements that fit, then use uninitialized copy to ge the rest
229      // and adjust size
230      std::copy_n(oneapi::dpl::execution::make_device_policy(
231                      ::dpct::cs::get_default_queue()),
232                  other.begin(), _size, begin());
233      device_allocator_traits<Allocator>::uninitialized_device_copy_n(
234          _alloc, other.begin() + _size, other.size() - _size,
235          _storage + _size);
236      _size = other.size();
237    } else {
238      // If incoming elements exceed current capacity, destroy all existing
239      // elements, then allocate incoming vectors capacity, then use
240      // uninitialized copy
241      clear();
242      reserve(other.capacity());
243      device_allocator_traits<Allocator>::uninitialized_device_copy_n(
244          _alloc, other.begin(), other.size(), _storage);
245      _size = other.size();
246    }
247  }
248
249public:
250  template <typename OtherA> operator ::std::vector<T, OtherA>() const {
251    auto __tmp = ::std::vector<T, OtherA>(this->size());
252    ::std::copy(oneapi::dpl::execution::make_device_policy(
253                    ::dpct::cs::get_default_queue()),
254                this->begin(), this->end(), __tmp.begin());
255    return __tmp;
256  }
257
258  device_vector(
259      const Allocator &alloc = Allocator(::dpct::cs::get_default_queue()))
260      : _alloc(alloc), _size(0), _capacity(_min_capacity()) {
261    _set_capacity_and_alloc();
262  }
263
264  ~device_vector() /*= default*/ {
265    clear();
266    alloc_traits::deallocate(_alloc, _storage, _capacity);
267  }
268
269  explicit device_vector(size_type n, const Allocator &alloc = Allocator(
270                                          ::dpct::cs::get_default_queue()))
271      : _alloc(alloc), _size(n) {
272    _set_capacity_and_alloc();
273    _construct(n);
274  }
275
276  explicit device_vector(
277      size_type n, const T &value,
278      const Allocator &alloc = Allocator(::dpct::cs::get_default_queue()))
279      : _alloc(alloc), _size(n) {
280    _set_capacity_and_alloc();
281    _construct(n, value);
282  }
283
284  device_vector(device_vector &&other)
285      : _alloc(std::move(other._alloc)), _size(other.size()),
286        _capacity(other.capacity()), _storage(other._storage) {
287    other._size = 0;
288    other._capacity = 0;
289    other._storage = nullptr;
290  }
291
292  device_vector(device_vector &&other, const Allocator &alloc)
293      : _alloc(alloc), _size(other.size()), _capacity(other.capacity()) {
294    _storage = alloc_traits::allocate(_alloc, _capacity);
295    _construct_iter(other.begin(), _size); // ok to parallelize
296    other._size = 0;
297    other._capacity = 0;
298    other._storage = nullptr;
299  }
300
301  template <typename InputIterator>
302  device_vector(
303      InputIterator first,
304      typename ::std::enable_if_t<
305          dpct::internal::is_iterator<InputIterator>::value, InputIterator>
306          last,
307      const Allocator &alloc = Allocator(::dpct::cs::get_default_queue()))
308      : _alloc(alloc) {
309    _size = ::std::distance(first, last);
310    _set_capacity_and_alloc();
311    // unsafe to parallelize on device as we dont know if InputIterator is
312    // valid oneDPL input type
313    _construct_iter_host(first, _size);
314  }
315
316  device_vector(const device_vector &other, const Allocator &alloc)
317      : _alloc(alloc) {
318    _size = other.size();
319    _capacity = other.capacity();
320    _storage = alloc_traits::allocate(_alloc, _capacity);
321    _construct_iter(other.begin(), _size);
322  }
323
324  device_vector(const device_vector &other)
325      : device_vector(
326            other,
327            alloc_traits::select_on_container_copy_construction(other._alloc)) {
328  }
329
330  template <typename OtherAllocator>
331  device_vector(
332      const device_vector<T, OtherAllocator> &other,
333      const Allocator &alloc = Allocator(::dpct::cs::get_default_queue()))
334      : _alloc(alloc) {
335    _size = other.size();
336    _capacity = other.capacity();
337    _storage = alloc_traits::allocate(_alloc, _capacity);
338    _construct_iter(other.begin(), _size);
339  }
340
341  template <typename OtherAllocator>
342  device_vector(const ::std::vector<T, OtherAllocator> &v)
343      : device_vector(v.begin(), v.end()) {}
344
345  template <typename OtherAllocator>
346  device_vector(const ::std::vector<T, OtherAllocator> &v,
347                const Allocator &alloc)
348      : device_vector(v.begin(), v.end(), alloc) {}
349
350  template <typename OtherAllocator>
351  device_vector &operator=(const ::std::vector<T, OtherAllocator> &v) {
352    resize(v.size());
353    ::std::copy(oneapi::dpl::execution::make_device_policy(
354                    ::dpct::cs::get_default_queue()),
355                v.begin(), v.end(), begin());
356    return *this;
357  }
358
359  device_vector &operator=(const device_vector &other) {
360    // Copy assignment operator:
361    if constexpr (alloc_traits::propagate_on_container_copy_assignment::value) {
362      clear();
363      alloc_traits::deallocate(_alloc, _storage, _capacity);
364      _capacity = 0;
365      _alloc = other._alloc;
366    }
367    _assign_elements(other);
368    return *this;
369  }
370  device_vector &operator=(device_vector &&other) {
371    // Move assignment operator:
372    if constexpr (alloc_traits::propagate_on_container_move_assignment::value) {
373      clear();
374      alloc_traits::deallocate(_alloc, _storage, _capacity);
375      _alloc = ::std::move(other._alloc);
376      _storage = ::std::move(other._storage);
377      _capacity = ::std::move(other._capacity);
378      _size = ::std::move(other._size);
379    } else {
380      _assign_elements(other);
381      // destroy and deallocate other vector
382      other.clear();
383      alloc_traits::deallocate(other._alloc, other._storage, other._capacity);
384    }
385    other._size = 0;
386    other._capacity = 0;
387    other._storage = nullptr;
388    return *this;
389  }
390  size_type size() const { return _size; }
391  iterator begin() noexcept { return device_iterator<T>(_storage, 0); }
392  iterator end() { return device_iterator<T>(_storage, size()); }
393  const_iterator begin() const noexcept {
394    return device_iterator<T>(_storage, 0);
395  }
396  const_iterator cbegin() const noexcept { return begin(); }
397  const_iterator end() const { return device_iterator<T>(_storage, size()); }
398  const_iterator cend() const { return end(); }
399  T *real_begin() { return _storage; }
400  const T *real_begin() const { return _storage; }
401  void swap(device_vector &v) {
402    if constexpr (::std::allocator_traits<
403                      Allocator>::propagate_on_container_swap::value) {
404      ::std::swap(_alloc, v._alloc);
405      ::std::swap(_size, v._size);
406      ::std::swap(_capacity, v._capacity);
407      ::std::swap(_storage, v._storage);
408    } else {
409      // swap all elements up to the minimum size between the two vectors
410      size_type min_size = (::std::min)(size(), v.size());
411      auto zip = oneapi::dpl::make_zip_iterator(begin(), v.begin());
412      ::std::for_each(oneapi::dpl::execution::make_device_policy(
413                          ::dpct::cs::get_default_queue()),
414                      zip, zip + min_size, [](auto zip_ele) {
415                        std::swap(::std::get<0>(zip_ele),
416                                  ::std::get<1>(zip_ele));
417                      });
418      // then copy the elements beyond the end of the smaller list, and resize
419      if (size() > v.size()) {
420        v.reserve(capacity());
421        device_allocator_traits<Allocator>::uninitialized_device_copy_n(
422            _alloc, begin() + min_size, size() - min_size,
423            v._storage + min_size);
424        v._size = size();
425        _destroy(size() - min_size, min_size);
426        _size = min_size;
427      } else if (size() < v.size()) {
428        reserve(v.capacity());
429        device_allocator_traits<Allocator>::uninitialized_device_copy_n(
430            _alloc, v.begin() + min_size, v.size() - min_size,
431            _storage + min_size);
432        _size = v.size();
433        v._destroy(v.size() - min_size, min_size);
434        v._size = min_size;
435      }
436    }
437  }
438  reference operator[](size_type n) { return _storage[n]; }
439  const_reference operator[](size_type n) const { return _storage[n]; }
440  void reserve(size_type n) {
441    if (n > capacity()) {
442      // allocate buffer for new size
443      auto tmp = alloc_traits::allocate(_alloc, n);
444      // copy content (old buffer to new buffer)
445      if (capacity() > 0) {
446        device_allocator_traits<Allocator>::uninitialized_device_copy_n(
447            _alloc, begin(), _size, tmp);
448        alloc_traits::deallocate(_alloc, _storage, _capacity);
449      }
450      _storage = tmp;
451      _capacity = n;
452    }
453  }
454  void resize(size_type new_size, const T &x = T()) {
455    reserve(new_size);
456    if (new_size > size()) {
457      _construct(new_size - size(), x, size());
458    } else {
459      _destroy(_size - new_size, new_size);
460    }
461    _size = new_size;
462  }
463  size_type max_size(void) const {
464    return ::std::numeric_limits<size_type>::max() / sizeof(T);
465  }
466  size_type capacity() const { return _capacity; }
467  const_reference front() const { return *begin(); }
468  reference front() { return *begin(); }
469  const_reference back(void) const { return *(end() - 1); }
470  reference back(void) { return *(end() - 1); }
471  pointer data(void) { return pointer(_storage); }
472  const_pointer data(void) const { return const_pointer(_storage); }
473  void shrink_to_fit(void) {
474    if (_size != capacity() && capacity() > _min_capacity()) {
475      size_type tmp_capacity = (::std::max)(_size, _min_capacity());
476      auto tmp = alloc_traits::allocate(_alloc, tmp_capacity);
477      if (_size > 0) {
478        ::std::copy(oneapi::dpl::execution::make_device_policy(
479                        ::dpct::cs::get_default_queue()),
480                    begin(), end(), tmp);
481      }
482      alloc_traits::deallocate(_alloc, _storage, _capacity);
483      _storage = tmp;
484      _capacity = tmp_capacity;
485    }
486  }
487  void assign(size_type n, const T &x) {
488    resize(n);
489    if (_size > 0) {
490      ::std::fill(oneapi::dpl::execution::make_device_policy(
491                      ::dpct::cs::get_default_queue()),
492                  begin(), begin() + n, x);
493    }
494  }
495  template <typename InputIterator>
496  void
497  assign(InputIterator first,
498         typename ::std::enable_if<internal::is_iterator<InputIterator>::value,
499                                   InputIterator>::type last) {
500    auto n = ::std::distance(first, last);
501    resize(n);
502    if (_size > 0) {
503      // unsafe to call on device as we don't know the InputIterator type
504      ::std::copy(first, last, begin());
505    }
506  }
507  void clear(void) {
508    _destroy(_size);
509    _size = 0;
510  }
511  bool empty(void) const { return (size() == 0); }
512  void push_back(const T &x) { insert(end(), size_type(1), x); }
513  void pop_back(void) {
514    if (_size > 0) {
515      _destroy(1, _size - 1);
516      --_size;
517    }
518  }
519  iterator erase(iterator first, iterator last) {
520    auto n = ::std::distance(first, last);
521    if (last == end()) {
522      _destroy(n, _size - n);
523      _size = _size - n;
524      return end();
525    }
526    auto m = ::std::distance(last, end());
527    if (m <= 0) {
528      return end();
529    } else if (n >= m) {
530      ::std::copy(oneapi::dpl::execution::make_device_policy(
531                      ::dpct::cs::get_default_queue()),
532                  last, last + m, first);
533    } else {
534      auto tmp = alloc_traits::allocate(_alloc, m);
535
536      device_allocator_traits<Allocator>::uninitialized_device_copy_n(
537          _alloc, last, m, tmp);
538
539      std::copy(oneapi::dpl::execution::make_device_policy(
540                    ::dpct::cs::get_default_queue()),
541                tmp, tmp + m, first);
542      device_allocator_traits<Allocator>::destroy_n(_alloc, tmp, m);
543      alloc_traits::deallocate(_alloc, tmp, m);
544    }
545    // now destroy the remaining elements
546    _destroy(n, size() - n);
547    _size -= n;
548    return begin() + first.get_idx() + n;
549  }
550  iterator erase(iterator pos) { return erase(pos, pos + 1); }
551  iterator insert(iterator position, const T &x) {
552    auto n = ::std::distance(begin(), position);
553    insert(position, size_type(1), x);
554    return begin() + n;
555  }
556  void insert(iterator position, size_type n, const T &x) {
557    if (position == end()) {
558      reserve(size() + n);
559      device_allocator_traits<Allocator>::uninitialized_fill_n(
560          _alloc, _storage + size(), n, x);
561      _size += n;
562    } else {
563      auto i_n = ::std::distance(begin(), position);
564      // allocate temporary storage
565      auto m = ::std::distance(position, end());
566      // will throw if position is not inside active vector
567      auto tmp = alloc_traits::allocate(_alloc, m);
568      // copy remainder
569      device_allocator_traits<Allocator>::uninitialized_device_copy_n(
570          _alloc, position, m, tmp);
571      resize(size() + n);
572      // resizing might invalidate position
573      position = begin() + position.get_idx();
574      ::std::fill(oneapi::dpl::execution::make_device_policy(
575                      ::dpct::cs::get_default_queue()),
576                  position, position + n, x);
577      ::std::copy(oneapi::dpl::execution::make_device_policy(
578                      ::dpct::cs::get_default_queue()),
579                  tmp, tmp + m, position + n);
580      device_allocator_traits<Allocator>::destroy_n(_alloc, tmp, m);
581      alloc_traits::deallocate(_alloc, tmp, m);
582    }
583  }
584  template <typename InputIterator>
585  void
586  insert(iterator position, InputIterator first,
587         typename ::std::enable_if<internal::is_iterator<InputIterator>::value,
588                                   InputIterator>::type last) {
589    auto n = ::std::distance(first, last);
590    if (position == end()) {
591      reserve(size() + n);
592      // unsafe to call on device as we dont know the InputIterator type
593      ::std::uninitialized_copy(first, last, end());
594      _size += n;
595    } else {
596      auto m = ::std::distance(position, end());
597      // will throw if position is not inside active vector
598      auto tmp = alloc_traits::allocate(_alloc, m);
599
600      device_allocator_traits<Allocator>::uninitialized_device_copy_n(
601          _alloc, position, m, tmp);
602
603      resize(size() + n);
604      // resizing might invalidate position
605      position = begin() + position.get_idx();
606      // unsafe to call on device as we dont know the InputIterator type
607      ::std::copy(first, last, position);
608      ::std::copy(oneapi::dpl::execution::make_device_policy(
609                      ::dpct::cs::get_default_queue()),
610                  tmp, tmp + m, position + n);
611      device_allocator_traits<Allocator>::destroy_n(_alloc, tmp, m);
612      alloc_traits::deallocate(_alloc, tmp, m);
613    }
614  }
615  Allocator get_allocator() const { return _alloc; }
616};
617
618#else
619
620template <typename T, typename Allocator = detail::__buffer_allocator<T>>
621class device_vector {
622  static_assert(
623      std::is_same<Allocator, detail::__buffer_allocator<T>>::value,
624      "device_vector doesn't support custom allocator when USM is not used.");
625
626public:
627  using iterator = device_iterator<T>;
628  using const_iterator = const iterator;
629  using reference = device_reference<T>;
630  using const_reference = const reference;
631  using value_type = T;
632  using pointer = device_pointer<T>;
633  using const_pointer = device_pointer<const T>;
634  using difference_type =
635      typename std::iterator_traits<iterator>::difference_type;
636  using size_type = std::size_t;
637
638private:
639  using Buffer = sycl::buffer<T, 1>;
640  using Range = sycl::range<1>;
641  // Using mem_mgr to handle memory allocation
642  void *_storage;
643  size_type _size;
644
645  size_type _min_capacity() const { return size_type(1); }
646
647  void *alloc_store(size_type num_bytes) {
648    return detail::mem_mgr::instance().mem_alloc(num_bytes);
649  }
650
651public:
652  template <typename OtherA> operator std::vector<T, OtherA>() const {
653    auto __tmp = std::vector<T, OtherA>(this->size());
654    std::copy(oneapi::dpl::execution::dpcpp_default, this->begin(), this->end(),
655              __tmp.begin());
656    return __tmp;
657  }
658  device_vector()
659      : _storage(alloc_store(_min_capacity() * sizeof(T))), _size(0) {}
660  ~device_vector() = default;
661  explicit device_vector(size_type n) : device_vector(n, T()) {}
662  explicit device_vector(size_type n, const T &value)
663      : _storage(alloc_store((std::max)(n, _min_capacity()) * sizeof(T))),
664        _size(n) {
665    auto buf = get_buffer();
666    std::fill(oneapi::dpl::execution::dpcpp_default, oneapi::dpl::begin(buf),
667              oneapi::dpl::begin(buf) + n, T(value));
668  }
669  device_vector(const device_vector &other)
670      : _storage(other._storage), _size(other.size()) {}
671  device_vector(device_vector &&other)
672      : _storage(std::move(other._storage)), _size(other.size()) {}
673
674  template <typename InputIterator>
675  device_vector(InputIterator first,
676                typename std::enable_if<
677                    internal::is_iterator<InputIterator>::value &&
678                        !std::is_pointer<InputIterator>::value &&
679                        std::is_same<typename std::iterator_traits<
680                                         InputIterator>::iterator_category,
681                                     std::random_access_iterator_tag>::value,
682                    InputIterator>::type last)
683      : _storage(alloc_store(std::distance(first, last) * sizeof(T))),
684        _size(std::distance(first, last)) {
685    auto buf = get_buffer();
686    auto dst = oneapi::dpl::begin(buf);
687    std::copy(oneapi::dpl::execution::make_device_policy(
688                  ::dpct::cs::get_default_queue()),
689              first, last, dst);
690  }
691
692  template <typename InputIterator>
693  device_vector(InputIterator first,
694                typename std::enable_if<std::is_pointer<InputIterator>::value,
695                                        InputIterator>::type last)
696      : _storage(alloc_store(std::distance(first, last) * sizeof(T))),
697        _size(std::distance(first, last)) {
698    auto buf = get_buffer();
699    Buffer tmp_buf(first, last);
700    auto start = oneapi::dpl::begin(tmp_buf);
701    auto end = oneapi::dpl::end(tmp_buf);
702    auto dst = oneapi::dpl::begin(buf);
703    std::copy(oneapi::dpl::execution::make_device_policy(
704                  ::dpct::cs::get_default_queue()),
705              start, end, dst);
706  }
707
708  template <typename InputIterator>
709  device_vector(InputIterator first,
710                typename std::enable_if<
711                    internal::is_iterator<InputIterator>::value &&
712                        !std::is_same<typename std::iterator_traits<
713                                          InputIterator>::iterator_category,
714                                      std::random_access_iterator_tag>::value,
715                    InputIterator>::type last)
716      : _storage(alloc_store(std::distance(first, last) * sizeof(T))),
717        _size(std::distance(first, last)) {
718    auto buf = get_buffer();
719    std::vector<T> tmp(first, last);
720    Buffer tmp_buf(tmp);
721    auto start = oneapi::dpl::begin(tmp_buf);
722    auto end = oneapi::dpl::end(tmp_buf);
723    auto dst = oneapi::dpl::begin(buf);
724    std::copy(oneapi::dpl::execution::make_device_policy(
725                  ::dpct::cs::get_default_queue()),
726              start, end, dst);
727  }
728
729  template <typename OtherAllocator>
730  device_vector(const device_vector<T, OtherAllocator> &v)
731      : _storage(alloc_store(v.size() * sizeof(T))), _size(v.size()) {
732    auto buf = get_buffer();
733    auto dst = oneapi::dpl::begin(buf);
734    std::copy(oneapi::dpl::execution::make_device_policy(
735                  ::dpct::cs::get_default_queue()),
736              v.real_begin(), v.real_begin() + v.size(), dst);
737  }
738
739  template <typename OtherAllocator>
740  device_vector(std::vector<T, OtherAllocator> &v)
741      : _storage(alloc_store(v.size() * sizeof(T))), _size(v.size()) {
742    std::copy(oneapi::dpl::execution::dpcpp_default, v.begin(), v.end(),
743              oneapi::dpl::begin(get_buffer()));
744  }
745
746  device_vector &operator=(const device_vector &other) {
747    // Copy assignment operator:
748    _size = other.size();
749    void *tmp = alloc_store(_size * sizeof(T));
750    auto tmp_buf =
751        detail::mem_mgr::instance()
752            .translate_ptr(tmp)
753            .buffer.template reinterpret<T, 1>(sycl::range<1>(_size));
754    std::copy(oneapi::dpl::execution::dpcpp_default,
755              oneapi::dpl::begin(other.get_buffer()),
756              oneapi::dpl::end(other.get_buffer()),
757              oneapi::dpl::begin(tmp_buf));
758    detail::mem_mgr::instance().mem_free(_storage);
759    _storage = tmp;
760    return *this;
761  }
762  device_vector &operator=(device_vector &&other) {
763    // Move assignment operator:
764    _size = other.size();
765    this->_storage = std::move(other._storage);
766    return *this;
767  }
768  template <typename OtherAllocator>
769  device_vector &operator=(const std::vector<T, OtherAllocator> &v) {
770    Buffer data(v.begin(), v.end());
771    _size = v.size();
772    void *tmp = alloc_store(_size * sizeof(T));
773    auto tmp_buf =
774        detail::mem_mgr::instance()
775            .translate_ptr(tmp)
776            .buffer.template reinterpret<T, 1>(sycl::range<1>(_size));
777    std::copy(oneapi::dpl::execution::dpcpp_default, oneapi::dpl::begin(data),
778              oneapi::dpl::end(data), oneapi::dpl::begin(tmp_buf));
779    detail::mem_mgr::instance().mem_free(_storage);
780    _storage = tmp;
781
782    return *this;
783  }
784  Buffer get_buffer() const {
785    return detail::mem_mgr::instance()
786        .translate_ptr(_storage)
787        .buffer.template reinterpret<T, 1>(sycl::range<1>(capacity()));
788  }
789  size_type size() const { return _size; }
790  iterator begin() noexcept { return device_iterator<T>(get_buffer(), 0); }
791  iterator end() { return device_iterator<T>(get_buffer(), _size); }
792  const_iterator begin() const noexcept {
793    return device_iterator<T>(get_buffer(), 0);
794  }
795  const_iterator cbegin() const noexcept { return begin(); }
796  const_iterator end() const { return device_iterator<T>(get_buffer(), _size); }
797  const_iterator cend() const { return end(); }
798  T *real_begin() {
799    // This code returns a pointer to a data within sycl buffer accessor which
800    // is leaving scope. This relies on undefined
801    // behavior and may not provide a valid pointer to data inside that buffer.
802    return (detail::mem_mgr::instance()
803                .translate_ptr(_storage)
804                .buffer.get_host_access())
805        .get_pointer();
806  }
807  const T *real_begin() const {
808    // This code returns a pointer to a data within sycl buffer accessor which
809    // is leaving scope. This relies on undefined
810    // behavior and may not provide a valid pointer to data inside that buffer.
811    return const_cast<device_vector *>(this)->real_begin();
812  }
813  void swap(device_vector &v) {
814    void *temp = v._storage;
815    v._storage = this->_storage;
816    this->_storage = temp;
817    std::swap(_size, v._size);
818  }
819  reference operator[](size_type n) { return *(begin() + n); }
820  const_reference operator[](size_type n) const { return *(begin() + n); }
821  void reserve(size_type n) {
822    if (n > capacity()) {
823      // create new buffer (allocate for new size)
824      void *a = alloc_store(n * sizeof(T));
825
826      // copy content (old buffer to new buffer)
827      if (_storage != nullptr) {
828        auto tmp = detail::mem_mgr::instance()
829                       .translate_ptr(a)
830                       .buffer.template reinterpret<T, 1>(sycl::range<1>(n));
831        auto src_buf = get_buffer();
832        std::copy(oneapi::dpl::execution::dpcpp_default,
833                  oneapi::dpl::begin(src_buf), oneapi::dpl::end(src_buf),
834                  oneapi::dpl::begin(tmp));
835
836        // deallocate old memory
837        detail::mem_mgr::instance().mem_free(_storage);
838      }
839      _storage = a;
840    }
841  }
842  void resize(size_type new_size, const T &x = T()) {
843    reserve(new_size);
844    if (_size < new_size) {
845      auto src_buf = get_buffer();
846      std::fill(oneapi::dpl::execution::dpcpp_default,
847                oneapi::dpl::begin(src_buf) + _size,
848                oneapi::dpl::begin(src_buf) + new_size, x);
849    }
850    _size = new_size;
851  }
852  size_type max_size(void) const {
853    return std::numeric_limits<size_type>::max() / sizeof(T);
854  }
855  size_type capacity() const {
856    return _storage != nullptr ? detail::mem_mgr::instance()
857                                         .translate_ptr(_storage)
858                                         .buffer.size() /
859                                     sizeof(T)
860                               : 0;
861  }
862  const_reference front() const { return *begin(); }
863  reference front() { return *begin(); }
864  const_reference back(void) const { return *(end() - 1); }
865  reference back(void) { return *(end() - 1); }
866  pointer data(void) { return pointer(reinterpret_cast<T *>(_storage)); }
867  const_pointer data(void) const {
868    return const_pointer(reinterpret_cast<const T *>(_storage));
869  }
870  void shrink_to_fit(void) {
871    if (_size != capacity()) {
872      void *a = alloc_store(_size * sizeof(T));
873      auto tmp = detail::mem_mgr::instance()
874                     .translate_ptr(a)
875                     .buffer.template reinterpret<T, 1>(sycl::range<1>(_size));
876      std::copy(oneapi::dpl::execution::dpcpp_default,
877                oneapi::dpl::begin(get_buffer()),
878                oneapi::dpl::begin(get_buffer()) + _size,
879                oneapi::dpl::begin(tmp));
880      detail::mem_mgr::instance().mem_free(_storage);
881      _storage = a;
882    }
883  }
884  void assign(size_type n, const T &x) {
885    resize(n);
886    std::fill(oneapi::dpl::execution::dpcpp_default, begin(), begin() + n, x);
887  }
888  template <typename InputIterator>
889  void
890  assign(InputIterator first,
891         typename std::enable_if<internal::is_iterator<InputIterator>::value,
892                                 InputIterator>::type last) {
893    auto n = std::distance(first, last);
894    resize(n);
895    if (internal::is_iterator<InputIterator>::value &&
896        !std::is_pointer<InputIterator>::value)
897      std::copy(oneapi::dpl::execution::dpcpp_default, first, last, begin());
898    else {
899      Buffer tmp(first, last);
900      std::copy(oneapi::dpl::execution::dpcpp_default, oneapi::dpl::begin(tmp),
901                oneapi::dpl::end(tmp), begin());
902    }
903  }
904  void clear(void) {
905    _size = 0;
906    detail::mem_mgr::instance().mem_free(_storage);
907    _storage = nullptr;
908  }
909  bool empty(void) const { return (size() == 0); }
910  void push_back(const T &x) { insert(end(), size_type(1), x); }
911  void pop_back(void) {
912    if (_size > 0)
913      --_size;
914  }
915  iterator erase(iterator first, iterator last) {
916    auto n = std::distance(first, last);
917    if (last == end()) {
918      _size = _size - n;
919      return end();
920    }
921    Buffer tmp{Range(std::distance(last, end()))};
922    // copy remainder to temporary buffer.
923    std::copy(oneapi::dpl::execution::dpcpp_default, last, end(),
924              oneapi::dpl::begin(tmp));
925    // override (erase) subsequence in storage.
926    std::copy(oneapi::dpl::execution::dpcpp_default, oneapi::dpl::begin(tmp),
927              oneapi::dpl::end(tmp), first);
928    resize(_size - n);
929    return begin() + first.get_idx() + n;
930  }
931  iterator erase(iterator pos) { return erase(pos, pos + 1); }
932  iterator insert(iterator position, const T &x) {
933    auto n = std::distance(begin(), position);
934    insert(position, size_type(1), x);
935    return begin() + n;
936  }
937  void insert(iterator position, size_type n, const T &x) {
938    if (position == end()) {
939      resize(size() + n);
940      std::fill(oneapi::dpl::execution::dpcpp_default, end() - n, end(), x);
941    } else {
942      auto i_n = std::distance(begin(), position);
943      // allocate temporary storage
944      Buffer tmp{Range(std::distance(position, end()))};
945      // copy remainder
946      std::copy(oneapi::dpl::execution::dpcpp_default, position, end(),
947                oneapi::dpl::begin(tmp));
948
949      resize(size() + n);
950      // resizing might invalidate position
951      position = begin() + position.get_idx();
952
953      std::fill(oneapi::dpl::execution::dpcpp_default, position, position + n,
954                x);
955
956      std::copy(oneapi::dpl::execution::dpcpp_default, oneapi::dpl::begin(tmp),
957                oneapi::dpl::end(tmp), position + n);
958    }
959  }
960  template <typename InputIterator>
961  void
962  insert(iterator position, InputIterator first,
963         typename std::enable_if<internal::is_iterator<InputIterator>::value,
964                                 InputIterator>::type last) {
965    auto n = std::distance(first, last);
966    if (position == end()) {
967      resize(size() + n);
968      std::copy(oneapi::dpl::execution::dpcpp_default, first, last, end());
969    } else {
970      Buffer tmp{Range(std::distance(position, end()))};
971
972      std::copy(oneapi::dpl::execution::dpcpp_default, position, end(),
973                oneapi::dpl::begin(tmp));
974
975      resize(size() + n);
976      // resizing might invalidate position
977      position = begin() + position.get_idx();
978
979      std::copy(oneapi::dpl::execution::dpcpp_default, first, last, position);
980      std::copy(oneapi::dpl::execution::dpcpp_default, oneapi::dpl::begin(tmp),
981                oneapi::dpl::end(tmp), position + n);
982    }
983  }
984};
985
986#endif
987
988} // end namespace dpct
989
990#endif