IsContiguous.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #pragma once
  2. namespace at { namespace native { inline namespace CPU_CAPABILITY {
  3. // n: number of function arguments (arity)
  4. // traits: function_traits (see FunctionTraits.h)
  5. // s: index of scalar argument or -1
  6. template <int n, int stride_index, typename traits, int s=-1>
  7. struct IsContiguous {
  8. static bool eval(const int64_t* strides) {
  9. using type = typename traits::template arg<n - 1>::type;
  10. return strides[stride_index] == (s == n ? 0 : sizeof(type)) &&
  11. IsContiguous<n - 1, stride_index - 1, traits, s>::eval(strides);
  12. }
  13. };
  14. // will be called when there is an output exists
  15. template <typename traits, int s>
  16. struct IsContiguous<0, 0, traits, s> {
  17. static bool eval(const int64_t* strides) {
  18. return strides[0] == sizeof(typename traits::result_type);
  19. }
  20. };
  21. // will be called when there is no output
  22. template <typename traits, int s>
  23. struct IsContiguous<0, -1, traits, s> {
  24. static bool eval(const int64_t* /*strides*/) {
  25. return true;
  26. }
  27. };
  28. // output and all inputs are contiguous
  29. template <typename traits,
  30. typename std::enable_if<std::is_void<typename traits::result_type>::value>::type* = nullptr>
  31. static inline bool is_contiguous(const int64_t* strides) {
  32. return IsContiguous<traits::arity, traits::arity - 1, traits>::eval(strides);
  33. }
  34. template <typename traits,
  35. typename std::enable_if<!std::is_void<typename traits::result_type>::value>::type* = nullptr>
  36. static inline bool is_contiguous(const int64_t* strides) {
  37. return IsContiguous<traits::arity, traits::arity, traits>::eval(strides);
  38. }
  39. // input at `s` is scalar (stride 0); output and other inputs are contiguous
  40. // NB: output is typically at strides[0] so first input corresponds to s=1
  41. template <typename traits, int s,
  42. typename std::enable_if<std::is_void<typename traits::result_type>::value>::type* = nullptr>
  43. static inline bool is_contiguous_scalar(const int64_t* strides) {
  44. static_assert(s > 0 && s <= traits::arity, "scalar argument index out of bounds");
  45. return IsContiguous<traits::arity, traits::arity - 1, traits, s>::eval(strides);
  46. }
  47. template <typename traits, int s,
  48. typename std::enable_if<!std::is_void<typename traits::result_type>::value>::type* = nullptr>
  49. static inline bool is_contiguous_scalar(const int64_t* strides) {
  50. static_assert(s > 0 && s <= traits::arity, "scalar argument index out of bounds");
  51. return IsContiguous<traits::arity, traits::arity, traits, s>::eval(strides);
  52. }
  53. }}}