okami.mom/strata

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

Niko1221Merge f-037-arc (5eaee81a4)86bed1c92

main
33.5 KiB1019 linesraw
1//==---- device.hpp -------------------------------*- 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_DEVICE_HPP__
10#define __DPCT_DEVICE_HPP__
11
12#include <algorithm>
13#include <array>
14#include <climits>
15#include <cstdlib>
16#include <cstring>
17#include <functional>
18#include <iostream>
19#include <map>
20#include <mutex>
21#include <set>
22#include <sstream>
23#include <stack>
24#include <sycl/sycl.hpp>
25#include <thread>
26#include <vector>
27#if defined(__linux__)
28#include <unistd.h>
29#include <sys/syscall.h>
30#endif
31#if defined(_WIN64)
32#ifndef NOMINMAX
33#define NOMINMAX
34#endif
35#include <windows.h>
36#endif
37
38namespace dpct {
39namespace detail {
40static void get_version(const sycl::device &dev, int &major, int &minor) {
41  // Version string has the following format:
42  // a. OpenCL<space><major.minor><space><vendor-specific-information>
43  // b. <major.minor>
44  std::string ver;
45  ver = dev.get_info<sycl::info::device::version>();
46  std::string::size_type i = 0;
47  while (i < ver.size()) {
48    if (isdigit(ver[i]))
49      break;
50    i++;
51  }
52  if (i < ver.size())
53    major = std::stoi(&(ver[i]));
54  else
55    major = 0;
56  while (i < ver.size()) {
57    if (ver[i] == '.')
58      break;
59    i++;
60  }
61  i++;
62  if (i < ver.size())
63    minor = std::stoi(&(ver[i]));
64  else
65    minor = 0;
66}
67} // namespace detail
68
69/// SYCL default exception handler
70inline auto exception_handler = [](sycl::exception_list exceptions) {
71  for (std::exception_ptr const &e : exceptions) {
72    try {
73      std::rethrow_exception(e);
74    } catch (sycl::exception const &e) {
75      std::cerr << "Caught asynchronous SYCL exception:" << std::endl
76                << e.what() << std::endl
77                << "Exception caught at file:" << __FILE__
78                << ", line:" << __LINE__ << std::endl;
79    }
80  }
81};
82
83typedef sycl::event *event_ptr;
84
85typedef sycl::queue *queue_ptr;
86
87typedef char *device_ptr;
88
89using queue_callback = std::function<void (queue_ptr, int, void*)>;
90
91/// Destroy \p event pointed memory.
92///
93/// \param event Pointer to the sycl::event address.
94static void destroy_event(event_ptr event) {
95    delete event;
96}
97
98class device_info {
99public:
100  // get interface
101  const char *get_name() const { return _name; }
102  char *get_name() { return _name; }
103  template <typename WorkItemSizesTy = sycl::range<3>,
104            std::enable_if_t<std::is_same_v<WorkItemSizesTy, sycl::range<3>> ||
105                                 std::is_same_v<WorkItemSizesTy, int *>,
106                             int> = 0>
107  auto get_max_work_item_sizes() const {
108    if constexpr (std::is_same_v<WorkItemSizesTy, sycl::range<3>>)
109      return sycl::range<3>(_max_work_item_sizes_i[0],
110                            _max_work_item_sizes_i[1],
111                            _max_work_item_sizes_i[2]);
112    else {
113      return _max_work_item_sizes_i;
114    }  
115  }
116  template <typename WorkItemSizesTy = sycl::range<3>,
117            std::enable_if_t<std::is_same_v<WorkItemSizesTy, sycl::range<3>> ||
118                                 std::is_same_v<WorkItemSizesTy, int *>,
119                             int> = 0>
120  auto get_max_work_item_sizes() {
121    if constexpr (std::is_same_v<WorkItemSizesTy, sycl::range<3>>)
122      return sycl::range<3>(_max_work_item_sizes_i[0],
123                            _max_work_item_sizes_i[1],
124                            _max_work_item_sizes_i[2]);
125    else {
126      return _max_work_item_sizes_i;
127    }  
128  }
129  bool get_host_unified_memory() const { return _host_unified_memory; }
130  int get_major_version() const { return _major; }
131  int get_minor_version() const { return _minor; }
132  int get_integrated() const { return _integrated; }
133  int get_max_clock_frequency() const { return _frequency; }
134  int get_max_compute_units() const { return _max_compute_units; }
135  int get_max_work_group_size() const { return _max_work_group_size; }
136  int get_max_sub_group_size() const { return _max_sub_group_size; }
137  int get_max_work_items_per_compute_unit() const {
138    return _max_work_items_per_compute_unit;
139  }
140  int get_max_register_size_per_work_group() const {
141    return _max_register_size_per_work_group;
142  }
143  template <typename NDRangeSizeTy = size_t *,
144            std::enable_if_t<std::is_same_v<NDRangeSizeTy, size_t *> ||
145                                 std::is_same_v<NDRangeSizeTy, int *>,
146                             int> = 0>
147  auto get_max_nd_range_size() const {
148    if constexpr (std::is_same_v<NDRangeSizeTy, size_t *>)
149      return _max_nd_range_size;
150    else
151      return _max_nd_range_size_i;
152  }
153  template <typename NDRangeSizeTy = size_t *,
154            std::enable_if_t<std::is_same_v<NDRangeSizeTy, size_t *> ||
155                                 std::is_same_v<NDRangeSizeTy, int *>,
156                             int> = 0>
157  auto get_max_nd_range_size() {
158    if constexpr (std::is_same_v<NDRangeSizeTy, size_t *>)
159      return _max_nd_range_size;
160    else
161      return _max_nd_range_size_i;
162  }
163  size_t get_global_mem_size() const { return _global_mem_size; }
164  size_t get_local_mem_size() const { return _local_mem_size; }
165  /// Returns the maximum clock rate of device's global memory in kHz. If
166  /// compiler does not support this API then returns default value 3200000 kHz.
167  unsigned int get_memory_clock_rate() const { return _memory_clock_rate; }
168  /// Returns the maximum bus width between device and memory in bits. If
169  /// compiler does not support this API then returns default value 64 bits.
170  unsigned int get_memory_bus_width() const { return _memory_bus_width; }
171  uint32_t get_device_id() const { return _device_id; }
172  std::array<unsigned char, 16> get_uuid() const { return _uuid; }
173  /// Returns global memory cache size in bytes.
174  unsigned int get_global_mem_cache_size() const {
175    return _global_mem_cache_size;
176  }
177  int get_image1d_max() const { return _image1d_max; }
178  auto get_image2d_max() const { return _image2d_max; }
179  auto get_image2d_max() { return _image2d_max; }
180  auto get_image3d_max() const { return _image3d_max; }
181  auto get_image3d_max() { return _image3d_max; }
182
183  // set interface
184  void set_name(const char* name) {
185    size_t length = strlen(name);
186    if (length < 256) {
187      std::memcpy(_name, name, length + 1);
188    } else {
189      std::memcpy(_name, name, 255);
190      _name[255] = '\0';
191    }
192  }
193  void set_max_work_item_sizes(const sycl::range<3> max_work_item_sizes) {
194    for (int i = 0; i < 3; ++i)
195      _max_work_item_sizes_i[i] = max_work_item_sizes[i];
196  }
197  void set_host_unified_memory(bool host_unified_memory) {
198    _host_unified_memory = host_unified_memory;
199  }
200  void set_major_version(int major) { _major = major; }
201  void set_minor_version(int minor) { _minor = minor; }
202  void set_integrated(int integrated) { _integrated = integrated; }
203  void set_max_clock_frequency(int frequency) { _frequency = frequency; }
204  void set_max_compute_units(int max_compute_units) {
205    _max_compute_units = max_compute_units;
206  }
207  void set_global_mem_size(size_t global_mem_size) {
208    _global_mem_size = global_mem_size;
209  }
210  void set_local_mem_size(size_t local_mem_size) {
211    _local_mem_size = local_mem_size;
212  }
213  void set_max_work_group_size(int max_work_group_size) {
214    _max_work_group_size = max_work_group_size;
215  }
216  void set_max_sub_group_size(int max_sub_group_size) {
217    _max_sub_group_size = max_sub_group_size;
218  }
219  void
220  set_max_work_items_per_compute_unit(int max_work_items_per_compute_unit) {
221    _max_work_items_per_compute_unit = max_work_items_per_compute_unit;
222  }
223  void set_max_nd_range_size(int max_nd_range_size[]) {
224    for (int i = 0; i < 3; i++) {
225      _max_nd_range_size[i] = max_nd_range_size[i];
226      _max_nd_range_size_i[i] = max_nd_range_size[i];
227    }
228  }
229  void set_max_nd_range_size(sycl::id<3> max_nd_range_size) {
230    for (int i = 0; i < 3; i++) {
231      _max_nd_range_size[i] = max_nd_range_size[i];
232      _max_nd_range_size_i[i] = max_nd_range_size[i];
233    }
234  }
235  void set_memory_clock_rate(unsigned int memory_clock_rate) {
236    _memory_clock_rate = memory_clock_rate;
237  }
238  void set_memory_bus_width(unsigned int memory_bus_width) {
239    _memory_bus_width = memory_bus_width;
240  }
241  void
242  set_max_register_size_per_work_group(int max_register_size_per_work_group) {
243    _max_register_size_per_work_group = max_register_size_per_work_group;
244  }
245  void set_device_id(uint32_t device_id) {
246    _device_id = device_id;
247  }
248  void set_uuid(std::array<unsigned char, 16> uuid) {
249    _uuid = std::move(uuid);
250  }
251  void set_global_mem_cache_size(unsigned int global_mem_cache_size) {
252    _global_mem_cache_size = global_mem_cache_size;
253  }
254  void set_image1d_max(size_t image_max_buffer_size) {
255    _image1d_max = image_max_buffer_size;
256  }
257
258private:
259  char _name[256];
260  int _max_work_item_sizes_i[3];
261  bool _host_unified_memory = false;
262  int _major;
263  int _minor;
264  int _integrated = 0;
265  int _frequency;
266  // Set estimated value 3200000 kHz as default value.
267  unsigned int _memory_clock_rate = 3200000;
268  // Set estimated value 64 bits as default value.
269  unsigned int _memory_bus_width = 64;
270  unsigned int _global_mem_cache_size;
271  int _max_compute_units;
272  int _max_work_group_size;
273  int _max_sub_group_size;
274  int _max_work_items_per_compute_unit;
275  int _max_register_size_per_work_group;
276  size_t _global_mem_size;
277  size_t _local_mem_size;
278  size_t _max_nd_range_size[3];
279  int _max_nd_range_size_i[3];
280  uint32_t _device_id;
281  std::array<unsigned char, 16> _uuid;
282  int _image1d_max;
283  int _image2d_max[2];
284  int _image3d_max[3];
285};
286
287static int get_major_version(const sycl::device &dev) {
288  int major, minor;
289  detail::get_version(dev, major, minor);
290  return major;
291}
292
293static int get_minor_version(const sycl::device &dev) {
294  int major, minor;
295  detail::get_version(dev, major, minor);
296  return minor;
297}
298
299static void get_device_info(device_info &out, const sycl::device &dev) {
300  device_info prop;
301  prop.set_name(dev.get_info<sycl::info::device::name>().c_str());
302
303  int major, minor;
304  detail::get_version(dev, major, minor);
305  prop.set_major_version(major);
306  prop.set_minor_version(minor);
307
308  prop.set_max_work_item_sizes(
309#if (__SYCL_COMPILER_VERSION && __SYCL_COMPILER_VERSION < 20220902)
310      // oneAPI DPC++ compiler older than 2022/09/02, where max_work_item_sizes
311      // is an enum class element
312      dev.get_info<sycl::info::device::max_work_item_sizes>());
313#else
314      // SYCL 2020-conformant code, max_work_item_sizes is a struct templated by
315      // an int
316      dev.get_info<sycl::info::device::max_work_item_sizes<3>>());
317#endif
318  prop.set_host_unified_memory(dev.has(sycl::aspect::usm_host_allocations));
319
320  prop.set_max_clock_frequency(
321      dev.get_info<sycl::info::device::max_clock_frequency>() * 1000);
322
323#ifdef SYCL_EXT_ONEAPI_NUM_COMPUTE_UNITS
324  prop.set_max_compute_units(
325      dev.get_info<sycl::ext::oneapi::info::device::num_compute_units>());
326#else
327  prop.set_max_compute_units(
328      dev.get_info<sycl::info::device::max_compute_units>());
329#endif
330  prop.set_max_work_group_size(
331      dev.get_info<sycl::info::device::max_work_group_size>());
332  prop.set_global_mem_size(dev.get_info<sycl::info::device::global_mem_size>());
333  prop.set_local_mem_size(dev.get_info<sycl::info::device::local_mem_size>());
334
335#if (defined(SYCL_EXT_INTEL_DEVICE_INFO) && SYCL_EXT_INTEL_DEVICE_INFO >= 6)
336  if (dev.has(sycl::aspect::ext_intel_memory_clock_rate)) {
337    unsigned int tmp =
338        dev.get_info<sycl::ext::intel::info::device::memory_clock_rate>();
339    if (tmp != 0)
340      prop.set_memory_clock_rate(1000 * tmp);
341  }
342  if (dev.has(sycl::aspect::ext_intel_memory_bus_width)) {
343    prop.set_memory_bus_width(
344        dev.get_info<sycl::ext::intel::info::device::memory_bus_width>());
345  }
346  if (dev.has(sycl::aspect::ext_intel_device_id)) {
347    prop.set_device_id(
348        dev.get_info<sycl::ext::intel::info::device::device_id>());
349  }
350  if (dev.has(sycl::aspect::ext_intel_device_info_uuid)) {
351    prop.set_uuid(dev.get_info<sycl::ext::intel::info::device::uuid>());
352  }
353#elif defined(_MSC_VER) && !defined(__clang__)
354#pragma message("get_device_info: querying memory_clock_rate and \
355memory_bus_width are not supported by the compiler used. \
356Use 3200000 kHz as memory_clock_rate default value. \
357Use 64 bits as memory_bus_width default value.")
358#else
359#warning "get_device_info: querying memory_clock_rate and \
360memory_bus_width are not supported by the compiler used. \
361Use 3200000 kHz as memory_clock_rate default value. \
362Use 64 bits as memory_bus_width default value."
363#endif
364
365  size_t max_sub_group_size = 1;
366  std::vector<size_t> sub_group_sizes =
367      dev.get_info<sycl::info::device::sub_group_sizes>();
368
369  for (const auto &sub_group_size : sub_group_sizes) {
370    if (max_sub_group_size < sub_group_size)
371      max_sub_group_size = sub_group_size;
372  }
373
374  prop.set_max_sub_group_size(max_sub_group_size);
375
376  prop.set_max_work_items_per_compute_unit(
377      dev.get_info<sycl::info::device::max_work_group_size>());
378#ifdef SYCL_EXT_ONEAPI_MAX_WORK_GROUP_QUERY
379  prop.set_max_nd_range_size(
380      dev.get_info<
381          sycl::ext::oneapi::experimental::info::device::max_work_groups<3>>());
382#else
383#if defined(_MSC_VER) && !defined(__clang__)
384#pragma message("get_device_info: querying the maximum number \
385of work groups is not supported.")
386#else
387#warning "get_device_info: querying the maximum number of \
388work groups is not supported."
389#endif
390  int max_nd_range_size[] = {0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF};
391  prop.set_max_nd_range_size(max_nd_range_size);
392#endif
393
394#ifdef SYCL_EXT_CODEPLAY_MAX_REGISTERS_PER_WORK_GROUP_QUERY
395  if (dev.get_backend() == sycl::backend::ext_oneapi_cuda)
396    prop.set_max_register_size_per_work_group(
397        dev.get_info<sycl::ext::codeplay::experimental::info::device::
398                         max_registers_per_work_group>());
399  else
400#endif
401    // Estimates max register size per work group, feel free to update the value
402    // according to device properties.
403    prop.set_max_register_size_per_work_group(65536);
404
405  prop.set_global_mem_cache_size(
406      dev.get_info<sycl::info::device::global_mem_cache_size>());
407
408  prop.set_image1d_max(
409      dev.get_info<sycl::info::device::image_max_buffer_size>());
410  prop.get_image2d_max()[0] =
411      dev.get_info<sycl::info::device::image2d_max_width>();
412  prop.get_image2d_max()[1] =
413      dev.get_info<sycl::info::device::image2d_max_height>();
414  prop.get_image3d_max()[0] =
415      dev.get_info<sycl::info::device::image3d_max_width>();
416  prop.get_image3d_max()[1] =
417      dev.get_info<sycl::info::device::image3d_max_height>();
418  prop.get_image3d_max()[2] =
419      dev.get_info<sycl::info::device::image3d_max_depth>();
420  out = prop;
421}
422
423/// Util function to check whether a device supports some kinds of sycl::aspect.
424inline void
425has_capability_or_fail(const sycl::device &dev,
426                       const std::initializer_list<sycl::aspect> &props) {
427  for (const auto &it : props) {
428    if (dev.has(it))
429      continue;
430    switch (it) {
431    case sycl::aspect::fp64:
432      throw std::runtime_error("'double' is not supported in '" +
433                               dev.get_info<sycl::info::device::name>() +
434                               "' device");
435      break;
436    case sycl::aspect::fp16:
437      throw std::runtime_error("'half' is not supported in '" +
438                               dev.get_info<sycl::info::device::name>() +
439                               "' device");
440      break;
441    default:
442#define __SYCL_ASPECT(ASPECT, ID)                                              \
443  case sycl::aspect::ASPECT:                                                   \
444    return #ASPECT;
445#define __SYCL_ASPECT_DEPRECATED(ASPECT, ID, MESSAGE) __SYCL_ASPECT(ASPECT, ID)
446#define __SYCL_ASPECT_DEPRECATED_ALIAS(ASPECT, ID, MESSAGE)
447      auto getAspectNameStr = [](sycl::aspect AspectNum) -> std::string {
448        switch (AspectNum) {
449#include <sycl/info/aspects.def>
450#include <sycl/info/aspects_deprecated.def>
451        default:
452          return "unknown aspect";
453        }
454      };
455#undef __SYCL_ASPECT_DEPRECATED_ALIAS
456#undef __SYCL_ASPECT_DEPRECATED
457#undef __SYCL_ASPECT
458      throw std::runtime_error(
459          "'" + getAspectNameStr(it) + "' is not supported in '" +
460          dev.get_info<sycl::info::device::name>() + "' device");
461    }
462    break;
463  }
464}
465
466/// dpct device extension
467class device_ext : public sycl::device {
468  typedef std::mutex mutex_type;
469
470public:
471  device_ext() : sycl::device(), _ctx(*this) {}
472  ~device_ext() {
473    std::lock_guard<mutex_type> lock(m_mutex);
474    clear_queues();
475  }
476  device_ext(const sycl::device &base) : sycl::device(base), _ctx(*this) {
477    std::lock_guard<mutex_type> lock(m_mutex);
478    init_queues();
479  }
480
481  int is_native_atomic_supported() { return 0; }
482  int get_major_version() const {
483    return dpct::get_major_version(*this);
484  }
485
486  int get_minor_version() const {
487    return dpct::get_minor_version(*this);
488  }
489
490  int get_max_compute_units() const {
491    return get_device_info().get_max_compute_units();
492  }
493
494  /// Return the maximum clock frequency of this device in KHz.
495  int get_max_clock_frequency() const {
496    return get_device_info().get_max_clock_frequency();
497  }
498
499  int get_integrated() const { return get_device_info().get_integrated(); }
500
501  int get_max_sub_group_size() const {
502    return get_device_info().get_max_sub_group_size();
503  }
504
505  int get_max_register_size_per_work_group() const {
506    return get_device_info().get_max_register_size_per_work_group();
507  }
508
509  int get_max_work_group_size() const {
510    return get_device_info().get_max_work_group_size();
511  }
512
513  int get_mem_base_addr_align() const {
514    return get_info<sycl::info::device::mem_base_addr_align>();
515  }
516
517  int get_mem_base_addr_align_in_bytes() const {
518    return get_info<sycl::info::device::mem_base_addr_align>() / 8;
519  }
520
521  size_t get_global_mem_size() const {
522    return get_device_info().get_global_mem_size();
523  }
524
525  size_t get_local_mem_size() const {
526    return get_device_info().get_local_mem_size();
527  }
528
529  int get_max_pitch() const { return INT_MAX; }
530
531  /// Get the number of bytes of free and total memory on the SYCL device.
532  /// \param [out] free_memory The number of bytes of free memory on the SYCL device.
533  /// \param [out] total_memory The number of bytes of total memory on the SYCL device.
534  void get_memory_info(size_t &free_memory, size_t &total_memory) {
535#if (defined(__SYCL_COMPILER_VERSION) && __SYCL_COMPILER_VERSION >= 20221105)
536    if (!has(sycl::aspect::ext_intel_free_memory)) {
537      std::cerr << "get_memory_info: ext_intel_free_memory is not supported." << std::endl;
538      free_memory = 0;
539    } else {
540      free_memory = get_info<sycl::ext::intel::info::device::free_memory>();
541    }
542#else
543    std::cerr << "get_memory_info: ext_intel_free_memory is not supported." << std::endl;
544    free_memory = 0;
545#if defined(_MSC_VER) && !defined(__clang__)
546#pragma message("Querying the number of bytes of free memory is not supported")
547#else
548#warning "Querying the number of bytes of free memory is not supported"
549#endif
550#endif
551    total_memory = get_device_info().get_global_mem_size();
552  }
553
554  void get_device_info(device_info &out) const {
555    dpct::get_device_info(out, *this);
556  }
557
558  device_info get_device_info() const {
559    device_info prop;
560    dpct::get_device_info(prop, *this);
561    return prop;
562  }
563
564  void reset() {
565    std::lock_guard<mutex_type> lock(m_mutex);
566    clear_queues();
567    init_queues();
568  }
569
570  sycl::queue &in_order_queue() { return *_q_in_order; }
571
572  sycl::queue &out_of_order_queue() { return *_q_out_of_order; }
573
574  sycl::queue &default_queue() {
575#ifdef DPCT_USM_LEVEL_NONE
576    return out_of_order_queue();
577#else
578    return in_order_queue();
579#endif // DPCT_USM_LEVEL_NONE
580  }
581
582  void queues_wait_and_throw() {
583    std::unique_lock<mutex_type> lock(m_mutex);
584    std::vector<std::shared_ptr<sycl::queue>> current_queues(
585        _queues);
586    lock.unlock();
587    for (const auto &q : current_queues) {
588      q->wait_and_throw();
589    }
590    // Guard the destruct of current_queues to make sure the ref count is safe.
591    lock.lock();
592  }
593
594  std::vector<sycl::event> get_in_order_queues_last_events() {
595    std::unique_lock<mutex_type> lock(m_mutex);
596    std::vector<sycl::event> last_events;
597    std::vector<std::shared_ptr<sycl::queue>> current_queues(_queues);
598    lock.unlock();
599    for (const auto &q : current_queues) {
600      if (q->is_in_order()) {
601        auto last_event = q->ext_oneapi_get_last_event();
602        [&](auto &&_e) {
603          if constexpr (std::is_same_v<
604                            std::remove_reference_t<decltype(last_event)>,
605                            sycl::event>)
606            last_events.push_back(_e);
607          else if (_e.has_value())
608            last_events.push_back(_e.value());
609        }(last_event);
610      }
611    }
612    // Guard the destruct of current_queues to make sure the ref count is safe.
613    lock.lock();
614    return last_events;
615  }
616
617  sycl::queue *create_queue(bool enable_exception_handler = false) {
618#ifdef DPCT_USM_LEVEL_NONE
619    return create_out_of_order_queue(enable_exception_handler);
620#else
621    return create_in_order_queue(enable_exception_handler);
622#endif // DPCT_USM_LEVEL_NONE
623  }
624
625  sycl::queue *create_in_order_queue(bool enable_exception_handler = false) {
626    std::lock_guard<mutex_type> lock(m_mutex);
627    return create_queue_impl(enable_exception_handler,
628                             sycl::property::queue::in_order());
629  }
630
631  sycl::queue *create_out_of_order_queue(bool enable_exception_handler = false) {
632    std::lock_guard<mutex_type> lock(m_mutex);
633    return create_queue_impl(enable_exception_handler);
634  }
635
636  void destroy_queue(sycl::queue *&queue) {
637    std::lock_guard<mutex_type> lock(m_mutex);
638    _queues.erase(std::remove_if(_queues.begin(), _queues.end(),
639                                  [=](const std::shared_ptr<sycl::queue> &q) -> bool {
640                                    return q.get() == queue;
641                                  }),
642                   _queues.end());
643    queue = nullptr;
644  }
645  [[deprecated("set_saved_queue for device_ext is deprecated, please use "
646               "dpct::blas::descriptor::set_saved_queue instead")]] void
647  set_saved_queue(sycl::queue *q) {
648    std::lock_guard<mutex_type> lock(m_mutex);
649    _saved_queue = q;
650  }
651  [[deprecated(
652      "get_saved_queue for device_ext is deprecated, please use "
653      "dpct::blas::descriptor::get_saved_queue instead")]] sycl::queue *
654  get_saved_queue() const {
655    std::lock_guard<mutex_type> lock(m_mutex);
656    return _saved_queue;
657  }
658  sycl::context get_context() const { return _ctx; }
659
660  void
661  has_capability_or_fail(const std::initializer_list<sycl::aspect> &props) {
662    ::dpct::has_capability_or_fail(*this, props);
663  }
664
665private:
666  void clear_queues() {
667    _queues.clear();
668    _q_in_order = _q_out_of_order = _saved_queue = nullptr;
669  }
670
671  void init_queues() {
672    _q_in_order = create_queue_impl(true, sycl::property::queue::in_order());
673    _q_out_of_order = create_queue_impl(true);
674    _saved_queue = &default_queue();
675  }
676
677  /// Caller should acquire resource \p m_mutex before calling this function.
678  template <class... Properties>
679  sycl::queue *create_queue_impl(bool enable_exception_handler,
680                                 Properties... properties) {
681    sycl::async_handler eh = {};
682    if (enable_exception_handler) {
683      eh = exception_handler;
684    }
685    // STRATA_KPROF=1 (include/strata/kprof.hpp): every queue profiles, whatever this translation unit defined
686    static const bool kprof_on = [] { const char* v = std::getenv("STRATA_KPROF"); return v != nullptr && v[0] != '0'; }();
687    if (kprof_on) {
688      _queues.push_back(std::make_shared<sycl::queue>(
689          _ctx, *this, eh,
690          sycl::property_list(sycl::property::queue::enable_profiling(), properties...)));
691      return _queues.back().get();
692    }
693    _queues.push_back(std::make_shared<sycl::queue>(
694        _ctx, *this, eh,
695        sycl::property_list(
696#ifdef DPCT_PROFILING_ENABLED
697            sycl::property::queue::enable_profiling(),
698#endif
699            properties...)));
700
701    return _queues.back().get();
702  }
703
704  void get_version(int &major, int &minor) const {
705    detail::get_version(*this, major, minor);
706  }
707  sycl::queue *_q_in_order, *_q_out_of_order;
708  sycl::queue *_saved_queue;
709  sycl::context _ctx;
710  std::vector<std::shared_ptr<sycl::queue>> _queues;
711  mutable mutex_type m_mutex;
712};
713
714static inline unsigned int get_tid() {
715#if defined(__linux__)
716  return syscall(SYS_gettid);
717#elif defined(_WIN64)
718  return GetCurrentThreadId();
719#else
720#error "Only support Windows and Linux."
721#endif
722}
723
724/// device manager
725class dev_mgr {
726public:
727  device_ext &current_device() { return get_device(current_device_id()); }
728  device_ext &cpu_device() const {
729    std::lock_guard<std::recursive_mutex> lock(m_mutex);
730    if (_cpu_device == -1) {
731      throw std::runtime_error("no valid cpu device");
732    } else {
733      return *_devs[_cpu_device];
734    }
735  }
736  device_ext &get_device(unsigned int id) const {
737    std::lock_guard<std::recursive_mutex> lock(m_mutex);
738    check_id(id);
739    return *_devs[id];
740  }
741
742  unsigned int current_device_id() const {
743    if (_dev_stack.empty())
744      return DEFAULT_DEVICE_ID;
745    return _dev_stack.top();
746  }
747
748  /// Select device with a device ID.
749  /// \param [in] id The id of the device which can
750  /// be obtained through get_device_id(const sycl::device).
751  void select_device(unsigned int id) {
752    /// Replace the top of the stack with the given device id
753    if (_dev_stack.empty()) {
754      push_device(id);
755    } else {
756      check_id(id);
757      _dev_stack.top() = id;
758    }
759  }
760
761  unsigned int device_count() { return _devs.size(); }
762
763  unsigned int get_device_id(const sycl::device &dev) {
764    unsigned int id = 0;
765    for (auto dev_item : _devs) {
766      if (*dev_item == dev) {
767        return id;
768      }
769      id++;
770    }
771    throw std::runtime_error(
772        "The device[" + dev.get_info<sycl::info::device::name>() +
773        "] is filtered out by dpct::dev_mgr::filter/dpct::filter_device in "
774        "current device "
775        "list!");
776  }
777
778  /// List all the devices with its id in dev_mgr.
779  void list_devices() const {
780    for (size_t i = 0; i < _devs.size(); ++i) {
781      std::cout << "" << i << ": "
782                << _devs[i]->get_info<sycl::info::device::name>() << std::endl;
783    }
784  }
785
786  /// Filter out devices; only keep the device whose name contains one of the
787  /// subname in \p dev_subnames.
788  /// May break device id mapping and change current device. It's better to be
789  /// called before other DPCT/SYCL APIs.
790  void filter(const std::vector<std::string> &dev_subnames) {
791    std::lock_guard<std::recursive_mutex> lock(m_mutex);
792    auto iter = _devs.begin();
793    while (iter != _devs.end()) {
794      std::string dev_name = (*iter)->get_info<sycl::info::device::name>();
795      bool matched = false;
796      for (const auto &name : dev_subnames) {
797        if (dev_name.find(name) != std::string::npos) {
798          matched = true;
799          break;
800        }
801      }
802      if (matched)
803        ++iter;
804      else
805        iter = _devs.erase(iter);
806    }
807    _cpu_device = -1;
808    for (unsigned i = 0; i < _devs.size(); ++i) {
809      if (_devs[i]->is_cpu()) {
810        _cpu_device = i;
811        break;
812      }
813    }
814    /// Clear the device stack for all thread here. But we don't have access to
815    /// all threads current implementation.
816#ifdef DPCT_HELPER_VERBOSE
817    list_devices();
818#endif
819  }
820
821  template <class DeviceSelector>
822  std::enable_if_t<
823      std::is_invocable_r_v<int, DeviceSelector, const sycl::device &>>
824  select_device(const DeviceSelector &selector = sycl::gpu_selector_v) {
825    sycl::device selected_device = sycl::device(selector);
826    unsigned int selected_device_id = get_device_id(selected_device);
827    select_device(selected_device_id);
828  }
829
830  /// Update the device stack for the current thread id
831  void push_device(unsigned int id) {
832    check_id(id);
833    _dev_stack.push(id);
834  }
835
836  /// Remove the device from top of the stack if it exist
837  unsigned int pop_device() {
838    if (_dev_stack.empty())
839      throw std::runtime_error("can't pop an empty dpct device stack");
840
841    auto id = _dev_stack.top();
842    _dev_stack.pop();
843    return id;
844  }
845
846  /// Returns the instance of device manager singleton.
847  static dev_mgr &instance() {
848    static dev_mgr d_m;
849    return d_m;
850  }
851  dev_mgr(const dev_mgr &) = delete;
852  dev_mgr &operator=(const dev_mgr &) = delete;
853  dev_mgr(dev_mgr &&) = delete;
854  dev_mgr &operator=(dev_mgr &&) = delete;
855
856private:
857  mutable std::recursive_mutex m_mutex;
858  dev_mgr() {
859    sycl::device default_device =
860        sycl::device(sycl::default_selector_v);
861    _devs.push_back(std::make_shared<device_ext>(default_device));
862
863    std::vector<sycl::device> sycl_all_devs =
864        sycl::device::get_devices(sycl::info::device_type::all);
865    // Collect other devices except for the default device.
866    if (default_device.is_cpu())
867      _cpu_device = 0;
868    for (auto &dev : sycl_all_devs) {
869      if (dev == default_device) {
870        continue;
871      }
872      _devs.push_back(std::make_shared<device_ext>(dev));
873      if (_cpu_device == -1 && dev.is_cpu()) {
874        _cpu_device = _devs.size() - 1;
875      }
876    }
877#ifdef DPCT_HELPER_VERBOSE
878    list_devices();
879#endif
880  }
881  void check_id(unsigned int id) const {
882    std::lock_guard<std::recursive_mutex> lock(m_mutex);
883    if (id >= _devs.size()) {
884      throw std::runtime_error("invalid device id");
885    }
886  }
887  std::vector<std::shared_ptr<device_ext>> _devs;
888  /// stack of devices resulting from CUDA context change;
889  static inline thread_local std::stack<unsigned int> _dev_stack;
890  /// DEFAULT_DEVICE_ID is used, if current_device_id() finds an empty
891  /// _dev_stack, which means the default device should be used for the current
892  /// thread.
893  const unsigned int DEFAULT_DEVICE_ID = 0;
894  int _cpu_device = -1;
895};
896
897/// Util function to get the default queue of current selected device depends on
898/// the USM config. Return the default out-of-ordered queue when USM-none is
899/// enabled, otherwise return the default in-ordered queue.
900static inline sycl::queue &get_default_queue() {
901  return dev_mgr::instance().current_device().default_queue();
902}
903
904/// Util function to get the default in-ordered queue of current device in
905/// dpct device manager.
906static inline sycl::queue &get_in_order_queue() {
907  return dev_mgr::instance().current_device().in_order_queue();
908}
909
910/// Util function to get the default out-of-ordered queue of current device in
911/// dpct device manager.
912static inline sycl::queue &get_out_of_order_queue() {
913  return dev_mgr::instance().current_device().out_of_order_queue();
914}
915
916/// Util function to get the id of current device in
917/// dpct device manager.
918static inline unsigned int get_current_device_id() {
919  return dev_mgr::instance().current_device_id();
920}
921
922/// Util function to get the current device.
923static inline device_ext &get_current_device() {
924  return dev_mgr::instance().current_device();
925}
926
927/// Util function to get a device by id.
928static inline device_ext &get_device(unsigned int id) {
929  return dev_mgr::instance().get_device(id);
930}
931
932/// Util function to get the context of the default queue of current
933/// device in dpct device manager.
934static inline sycl::context get_default_context() {
935  return dpct::get_current_device().get_context();
936}
937
938/// Util function to get a CPU device.
939static inline device_ext &cpu_device() {
940  return dev_mgr::instance().cpu_device();
941}
942
943static inline unsigned int select_device(unsigned int id) {
944  dev_mgr::instance().select_device(id);
945  return id;
946}
947
948template <class DeviceSelector>
949static inline std::enable_if_t<
950    std::is_invocable_r_v<int, DeviceSelector, const sycl::device &>>
951select_device(const DeviceSelector &selector = sycl::gpu_selector_v) {
952  dev_mgr::instance().select_device(selector);
953}
954
955/// Filter out devices; only keep the device whose name contains one of the
956/// subname in \p dev_subnames.
957/// May break device id mapping and change current device. It's better to be
958/// called before other DPCT/SYCL APIs.
959static inline void filter_device(const std::vector<std::string> &dev_subnames) {
960  dev_mgr::instance().filter(dev_subnames);
961}
962
963/// List all the devices with its id in dev_mgr.
964static inline void list_devices() { dev_mgr::instance().list_devices(); }
965
966static inline unsigned int get_device_id(const sycl::device &dev){
967  return dev_mgr::instance().get_device_id(dev);
968}
969
970static inline unsigned int get_cpu_device_id() {
971  return get_device_id(cpu_device());
972}
973
974/// Util function to do implicit sync among queues of the same device then
975/// insert a synchronize barrier in the queue. For USM, If the queue is the
976/// default in-order queue, try to sync with all queues available in the current
977/// device before inserting a barrier. For USM-none, If the queue is the default
978/// out-of-order queue, try to sync with all queues available in the current
979/// device before inserting a barrier, else try to sync in the current queue
980/// before inserting a barrier.
981/// \param [out] event_ptr The memory to store the event.
982/// \param [in] queue The queue specified to do synchronization.
983inline void sync_barrier(sycl::event *event_ptr,
984                         sycl::queue *queue = &get_default_queue()) {
985  if (*queue == get_default_queue()) {
986    // Wait all the kernel tasks in all the queues of current device completed.
987    dpct::get_current_device().queues_wait_and_throw();
988  }
989
990#ifdef DPCT_USM_LEVEL_NONE
991  if (*queue != get_default_queue()) {
992    // For out-of-ordered queue, wait all the kernel tasks in \p queue
993    // completed.
994    queue->wait();
995  }
996#endif
997
998#ifdef DPCT_PROFILING_ENABLED
999  *event_ptr = queue->ext_oneapi_submit_barrier();
1000#else
1001  *event_ptr = queue->single_task([=]() {});
1002#endif
1003}
1004
1005static inline unsigned int push_device_for_curr_thread(unsigned int id) {
1006  dev_mgr::instance().push_device(id);
1007  return id;
1008}
1009
1010static inline unsigned int pop_device_for_curr_thread(void) {
1011  return dev_mgr::instance().pop_device();
1012}
1013
1014static inline unsigned int device_count() {
1015  return dev_mgr::instance().device_count();
1016}
1017} // namespace dpct
1018
1019#endif // __DPCT_DEVICE_HPP__