gokashi commited on
Commit
5e99411
·
verified ·
1 Parent(s): 11ecba2

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. deps/exla/c_src/exla/custom_calls/eigh.h +90 -0
  2. deps/exla/c_src/exla/custom_calls/eigh_f32.cc +19 -0
  3. deps/exla/c_src/exla/custom_calls/eigh_f64.cc +19 -0
  4. deps/exla/c_src/exla/custom_calls/lu.h +87 -0
  5. deps/exla/c_src/exla/custom_calls/lu_bf16.cc +21 -0
  6. deps/exla/c_src/exla/custom_calls/lu_f16.cc +21 -0
  7. deps/exla/c_src/exla/custom_calls/lu_f32.cc +20 -0
  8. deps/exla/c_src/exla/custom_calls/lu_f64.cc +20 -0
  9. deps/exla/c_src/exla/custom_calls/qr.h +88 -0
  10. deps/exla/c_src/exla/custom_calls/qr_bf16.cc +19 -0
  11. deps/exla/c_src/exla/custom_calls/qr_f16.cc +19 -0
  12. deps/exla/c_src/exla/custom_calls/qr_f32.cc +17 -0
  13. deps/exla/c_src/exla/custom_calls/qr_f64.cc +17 -0
  14. deps/exla/c_src/exla/exla.cc +508 -0
  15. deps/exla/c_src/exla/exla_client.h +120 -0
  16. deps/exla/c_src/exla/exla_log_sink.h +64 -0
  17. deps/exla/c_src/exla/exla_mlir.h +70 -0
  18. deps/exla/c_src/exla/exla_nif_util.h +270 -0
  19. deps/exla/cache/0.10.0/objs/exla_mlir.o +0 -0
  20. deps/exla/cache/0.10.0/objs/ipc.o +0 -0
  21. deps/exla/cache/xla_extension/include/_virtual_includes/FXdiv/fxdiv.h +425 -0
  22. deps/exla/cache/xla_extension/include/_virtual_includes/cpuinfo/cpuinfo.h +2331 -0
  23. deps/exla/cache/xla_extension/include/_virtual_includes/fft/ducc/google/threading.h +60 -0
  24. deps/exla/cache/xla_extension/include/_virtual_includes/fft/ducc/src/ducc0/fft/fft.h +1002 -0
  25. deps/exla/cache/xla_extension/include/_virtual_includes/fft/ducc/src/ducc0/fft/fft1d_impl.h +0 -0
  26. deps/exla/cache/xla_extension/include/_virtual_includes/fft/ducc/src/ducc0/fft/fftnd_impl.h +1883 -0
  27. deps/exla/cache/xla_extension/include/_virtual_includes/fft/ducc/src/ducc0/infra/mav.h +1354 -0
  28. deps/exla/cache/xla_extension/include/_virtual_includes/fft/ducc/src/ducc0/infra/threading.h +337 -0
  29. deps/exla/cache/xla_extension/include/_virtual_includes/fft_wrapper/ducc/google/fft.h +77 -0
  30. deps/exla/cache/xla_extension/include/_virtual_includes/pthreadpool/pthreadpool.h +0 -0
  31. deps/exla/cache/xla_extension/include/external/snappy/config.h +44 -0
  32. deps/exla/cache/xla_extension/include/external/snappy/snappy-internal.h +393 -0
  33. deps/exla/cache/xla_extension/include/external/snappy/snappy-sinksource.h +182 -0
  34. deps/exla/cache/xla_extension/include/external/snappy/snappy-stubs-internal.h +492 -0
  35. deps/exla/cache/xla_extension/include/external/snappy/snappy-stubs-public.h +63 -0
  36. deps/exla/cache/xla_extension/include/external/snappy/snappy.h +222 -0
  37. deps/exla/cache/xla_extension/include/external/zlib/crc32.h +0 -0
  38. deps/exla/cache/xla_extension/include/external/zlib/deflate.h +377 -0
  39. deps/exla/cache/xla_extension/include/external/zlib/gzguts.h +214 -0
  40. deps/exla/cache/xla_extension/include/external/zlib/inffast.h +11 -0
  41. deps/exla/cache/xla_extension/include/external/zlib/inffixed.h +94 -0
  42. deps/exla/cache/xla_extension/include/external/zlib/inflate.h +126 -0
  43. deps/exla/cache/xla_extension/include/external/zlib/inftrees.h +62 -0
  44. deps/exla/cache/xla_extension/include/external/zlib/trees.h +128 -0
  45. deps/exla/cache/xla_extension/include/external/zlib/zconf.h +543 -0
  46. deps/exla/cache/xla_extension/include/external/zlib/zlib.h +1938 -0
  47. deps/exla/cache/xla_extension/include/external/zlib/zutil.h +254 -0
  48. deps/exla/cache/xla_extension/include/farmhash.h +328 -0
  49. deps/exla/cache/xla_extension/include/grpc++/alarm.h +28 -0
  50. deps/exla/cache/xla_extension/include/grpc++/channel.h +28 -0
deps/exla/c_src/exla/custom_calls/eigh.h ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <algorithm>
4
+ #include <iostream>
5
+ #include <numeric>
6
+ #include <vector>
7
+
8
+ #include "Eigen/Eigenvalues"
9
+ #include "xla/ffi/api/ffi.h"
10
+ #include "xla/ffi/ffi_api.h"
11
+
12
+ namespace ffi = xla::ffi;
13
+
14
+ template <typename DataType>
15
+ void single_matrix_eigh_cpu_custom_call(DataType *eigenvalues_out,
16
+ DataType *eigenvectors_out,
17
+ DataType *in, uint64_t m, uint64_t n) {
18
+ typedef Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic,
19
+ Eigen::RowMajor>
20
+ RowMajorMatrix;
21
+
22
+ // Map the input matrix
23
+ Eigen::Map<RowMajorMatrix> input(in, m, n);
24
+
25
+ // Compute the Eigenvalue decomposition
26
+ Eigen::SelfAdjointEigenSolver<RowMajorMatrix> eigensolver(input);
27
+
28
+ if (eigensolver.info() != Eigen::Success) {
29
+ std::cerr << "Eigenvalue decomposition failed!" << std::endl;
30
+ return;
31
+ }
32
+
33
+ // Get the eigenvalues and eigenvectors
34
+ Eigen::Matrix<DataType, Eigen::Dynamic, 1> eigenvalues =
35
+ eigensolver.eigenvalues();
36
+ RowMajorMatrix eigenvectors = eigensolver.eigenvectors();
37
+
38
+ // Create a vector of indices and sort it based on eigenvalues in decreasing
39
+ // order
40
+ std::vector<int> indices(m);
41
+ std::iota(indices.begin(), indices.end(), 0);
42
+ std::sort(indices.begin(), indices.end(), [&eigenvalues](int i, int j) {
43
+ return std::abs(eigenvalues(i)) > std::abs(eigenvalues(j));
44
+ });
45
+
46
+ // Sort eigenvalues and rearrange eigenvectors
47
+ Eigen::Matrix<DataType, Eigen::Dynamic, 1> sorted_eigenvalues(m);
48
+ RowMajorMatrix sorted_eigenvectors(m, n);
49
+ for (int i = 0; i < m; ++i) {
50
+ sorted_eigenvalues(i) = eigenvalues(indices[i]);
51
+ sorted_eigenvectors.col(i) = eigenvectors.col(indices[i]);
52
+ }
53
+
54
+ // Copy the sorted eigenvalues to the output
55
+ std::memcpy(eigenvalues_out, sorted_eigenvalues.data(), m * sizeof(DataType));
56
+
57
+ // Copy the sorted eigenvectors to the output
58
+ std::memcpy(eigenvectors_out, sorted_eigenvectors.data(),
59
+ m * n * sizeof(DataType));
60
+ }
61
+
62
+ template <typename DataType, typename BufferType>
63
+ ffi::Error eigh_cpu_custom_call_impl(BufferType operand,
64
+ ffi::Result<BufferType> eigenvalues,
65
+ ffi::Result<BufferType> eigenvectors) {
66
+ auto operand_dims = operand.dimensions();
67
+ auto eigenvalues_dims = eigenvalues->dimensions();
68
+ auto eigenvectors_dims = eigenvectors->dimensions();
69
+
70
+ uint64_t m = eigenvectors_dims[eigenvectors_dims.size() - 2];
71
+ uint64_t n = eigenvectors_dims[eigenvectors_dims.size() - 1];
72
+
73
+ uint64_t batch_items = 1;
74
+ for (auto it = operand_dims.begin(); it != operand_dims.end() - 2; it++) {
75
+ batch_items *= *it;
76
+ }
77
+
78
+ uint64_t eigenvalues_stride = eigenvalues_dims[eigenvalues_dims.size() - 1];
79
+ uint64_t eigenvectors_stride = m * n;
80
+ uint64_t inner_stride = m * n;
81
+
82
+ for (uint64_t i = 0; i < batch_items; i++) {
83
+ single_matrix_eigh_cpu_custom_call<DataType>(
84
+ eigenvalues->typed_data() + i * eigenvalues_stride,
85
+ eigenvectors->typed_data() + i * eigenvectors_stride,
86
+ operand.typed_data() + i * inner_stride, m, n);
87
+ }
88
+
89
+ return ffi::Error::Success();
90
+ }
deps/exla/c_src/exla/custom_calls/eigh_f32.cc ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "eigh.h"
2
+
3
+ ffi::Error
4
+ eigh_cpu_custom_call_f32_impl(ffi::Buffer<ffi::F32> operand,
5
+ ffi::ResultBuffer<ffi::F32> eigenvalues,
6
+ ffi::ResultBuffer<ffi::F32> eigenvectors) {
7
+ return eigh_cpu_custom_call_impl<float, ffi::Buffer<ffi::F32>>(
8
+ operand, eigenvalues, eigenvectors);
9
+ }
10
+
11
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(eigh_cpu_custom_call_f32,
12
+ eigh_cpu_custom_call_f32_impl,
13
+ ffi::Ffi::Bind()
14
+ .Arg<ffi::Buffer<ffi::F32>>()
15
+ .Ret<ffi::Buffer<ffi::F32>>()
16
+ .Ret<ffi::Buffer<ffi::F32>>());
17
+
18
+ XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "eigh_cpu_custom_call_f32",
19
+ "Host", eigh_cpu_custom_call_f32);
deps/exla/c_src/exla/custom_calls/eigh_f64.cc ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "eigh.h"
2
+
3
+ ffi::Error
4
+ eigh_cpu_custom_call_f64_impl(ffi::Buffer<ffi::F64> operand,
5
+ ffi::ResultBuffer<ffi::F64> eigenvalues,
6
+ ffi::ResultBuffer<ffi::F64> eigenvectors) {
7
+ return eigh_cpu_custom_call_impl<double, ffi::Buffer<ffi::F64>>(
8
+ operand, eigenvalues, eigenvectors);
9
+ }
10
+
11
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(eigh_cpu_custom_call_f64,
12
+ eigh_cpu_custom_call_f64_impl,
13
+ ffi::Ffi::Bind()
14
+ .Arg<ffi::Buffer<ffi::F64>>()
15
+ .Ret<ffi::Buffer<ffi::F64>>()
16
+ .Ret<ffi::Buffer<ffi::F64>>());
17
+
18
+ XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "eigh_cpu_custom_call_f64",
19
+ "Host", eigh_cpu_custom_call_f64);
deps/exla/c_src/exla/custom_calls/lu.h ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <algorithm>
4
+ #include <iostream>
5
+ #include <numeric>
6
+ #include <vector>
7
+
8
+ #include "Eigen/LU"
9
+ #include "xla/ffi/api/ffi.h"
10
+ #include "xla/ffi/ffi_api.h"
11
+
12
+ namespace ffi = xla::ffi;
13
+
14
+ template <typename DataType>
15
+ void single_matrix_lu_cpu_custom_call(uint8_t *p_out, DataType *l_out,
16
+ DataType *u_out, DataType *in,
17
+ uint64_t n) {
18
+ typedef Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic,
19
+ Eigen::RowMajor>
20
+ RowMajorMatrix;
21
+
22
+ Eigen::Map<RowMajorMatrix> input(in, n, n);
23
+ Eigen::PartialPivLU<RowMajorMatrix> lu = input.partialPivLu();
24
+
25
+ // Get the permutation matrix P and convert to indices
26
+ Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> P =
27
+ lu.permutationP();
28
+ for (uint64_t i = 0; i < n; i++) {
29
+ for (uint64_t j = 0; j < n; j++) {
30
+ p_out[i * n + j] = static_cast<uint8_t>(P.indices()[i] == j ? 1 : 0);
31
+ }
32
+ }
33
+
34
+ // Get L and U matrices
35
+ RowMajorMatrix L = lu.matrixLU().template triangularView<Eigen::UnitLower>();
36
+ RowMajorMatrix U = lu.matrixLU().template triangularView<Eigen::Upper>();
37
+
38
+ // Copy L matrix
39
+ for (uint64_t i = 0; i < n; i++) {
40
+ for (uint64_t j = 0; j < n; j++) {
41
+ if (j < i) {
42
+ l_out[i * n + j] = static_cast<DataType>(L(i, j));
43
+ } else if (j == i) {
44
+ l_out[i * n + j] = static_cast<DataType>(1.0);
45
+ } else {
46
+ l_out[i * n + j] = static_cast<DataType>(0.0);
47
+ }
48
+ }
49
+ }
50
+
51
+ // Copy U matrix
52
+ for (uint64_t i = 0; i < n; i++) {
53
+ for (uint64_t j = 0; j < n; j++) {
54
+ if (j >= i) {
55
+ u_out[i * n + j] = static_cast<DataType>(U(i, j));
56
+ } else {
57
+ u_out[i * n + j] = static_cast<DataType>(0.0);
58
+ }
59
+ }
60
+ }
61
+ }
62
+
63
+ template <typename DataType, typename BufferType>
64
+ ffi::Error
65
+ lu_cpu_custom_call_impl(BufferType operand, ffi::Result<ffi::Buffer<ffi::U8>> p,
66
+ ffi::Result<BufferType> l, ffi::Result<BufferType> u) {
67
+ auto operand_dims = operand.dimensions();
68
+ auto l_dims = l->dimensions();
69
+ uint64_t n = l_dims[l_dims.size() - 1];
70
+
71
+ uint64_t batch_items = 1;
72
+ for (auto it = operand_dims.begin(); it != operand_dims.end() - 2; it++) {
73
+ batch_items *= *it;
74
+ }
75
+
76
+ uint64_t stride = n * n;
77
+
78
+ for (uint64_t i = 0; i < batch_items; i++) {
79
+ single_matrix_lu_cpu_custom_call<DataType>(
80
+ p->typed_data() + i * stride,
81
+ (DataType *)l->untyped_data() + i * stride,
82
+ (DataType *)u->untyped_data() + i * stride,
83
+ (DataType *)operand.untyped_data() + i * stride, n);
84
+ }
85
+
86
+ return ffi::Error::Success();
87
+ }
deps/exla/c_src/exla/custom_calls/lu_bf16.cc ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "../exla_types.h"
2
+ #include "lu.h"
3
+
4
+ ffi::Error lu_cpu_custom_call_bf16_impl(ffi::Buffer<ffi::BF16> operand,
5
+ ffi::ResultBuffer<ffi::U8> p,
6
+ ffi::ResultBuffer<ffi::BF16> l,
7
+ ffi::ResultBuffer<ffi::BF16> u) {
8
+ return lu_cpu_custom_call_impl<exla::bfloat16, ffi::Buffer<ffi::BF16>>(
9
+ operand, p, l, u);
10
+ }
11
+
12
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(lu_cpu_custom_call_bf16,
13
+ lu_cpu_custom_call_bf16_impl,
14
+ ffi::Ffi::Bind()
15
+ .Arg<ffi::Buffer<ffi::BF16>>()
16
+ .Ret<ffi::Buffer<ffi::U8>>()
17
+ .Ret<ffi::Buffer<ffi::BF16>>()
18
+ .Ret<ffi::Buffer<ffi::BF16>>());
19
+
20
+ XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "lu_cpu_custom_call_bf16", "Host",
21
+ lu_cpu_custom_call_bf16);
deps/exla/c_src/exla/custom_calls/lu_f16.cc ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "../exla_types.h"
2
+ #include "lu.h"
3
+
4
+ ffi::Error lu_cpu_custom_call_f16_impl(ffi::Buffer<ffi::F16> operand,
5
+ ffi::ResultBuffer<ffi::U8> p,
6
+ ffi::ResultBuffer<ffi::F16> l,
7
+ ffi::ResultBuffer<ffi::F16> u) {
8
+ return lu_cpu_custom_call_impl<exla::float16, ffi::Buffer<ffi::F16>>(operand,
9
+ p, l, u);
10
+ }
11
+
12
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(lu_cpu_custom_call_f16,
13
+ lu_cpu_custom_call_f16_impl,
14
+ ffi::Ffi::Bind()
15
+ .Arg<ffi::Buffer<ffi::F16>>()
16
+ .Ret<ffi::Buffer<ffi::U8>>()
17
+ .Ret<ffi::Buffer<ffi::F16>>()
18
+ .Ret<ffi::Buffer<ffi::F16>>());
19
+
20
+ XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "lu_cpu_custom_call_f16", "Host",
21
+ lu_cpu_custom_call_f16);
deps/exla/c_src/exla/custom_calls/lu_f32.cc ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "lu.h"
2
+
3
+ ffi::Error lu_cpu_custom_call_f32_impl(ffi::Buffer<ffi::F32> operand,
4
+ ffi::ResultBuffer<ffi::U8> p,
5
+ ffi::ResultBuffer<ffi::F32> l,
6
+ ffi::ResultBuffer<ffi::F32> u) {
7
+ return lu_cpu_custom_call_impl<float, ffi::Buffer<ffi::F32>>(operand, p, l,
8
+ u);
9
+ }
10
+
11
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(lu_cpu_custom_call_f32,
12
+ lu_cpu_custom_call_f32_impl,
13
+ ffi::Ffi::Bind()
14
+ .Arg<ffi::Buffer<ffi::F32>>()
15
+ .Ret<ffi::Buffer<ffi::U8>>()
16
+ .Ret<ffi::Buffer<ffi::F32>>()
17
+ .Ret<ffi::Buffer<ffi::F32>>());
18
+
19
+ XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "lu_cpu_custom_call_f32", "Host",
20
+ lu_cpu_custom_call_f32);
deps/exla/c_src/exla/custom_calls/lu_f64.cc ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "lu.h"
2
+
3
+ ffi::Error lu_cpu_custom_call_f64_impl(ffi::Buffer<ffi::F64> operand,
4
+ ffi::ResultBuffer<ffi::U8> p,
5
+ ffi::ResultBuffer<ffi::F64> l,
6
+ ffi::ResultBuffer<ffi::F64> u) {
7
+ return lu_cpu_custom_call_impl<double, ffi::Buffer<ffi::F64>>(operand, p, l,
8
+ u);
9
+ }
10
+
11
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(lu_cpu_custom_call_f64,
12
+ lu_cpu_custom_call_f64_impl,
13
+ ffi::Ffi::Bind()
14
+ .Arg<ffi::Buffer<ffi::F64>>()
15
+ .Ret<ffi::Buffer<ffi::U8>>()
16
+ .Ret<ffi::Buffer<ffi::F64>>()
17
+ .Ret<ffi::Buffer<ffi::F64>>());
18
+
19
+ XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "lu_cpu_custom_call_f64", "Host",
20
+ lu_cpu_custom_call_f64);
deps/exla/c_src/exla/custom_calls/qr.h ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <algorithm>
4
+ #include <iostream>
5
+ #include <numeric>
6
+ #include <vector>
7
+
8
+ #include "Eigen/QR"
9
+ #include "xla/ffi/api/ffi.h"
10
+ #include "xla/ffi/ffi_api.h"
11
+
12
+ namespace ffi = xla::ffi;
13
+
14
+ template <typename DataType>
15
+ void single_matrix_qr_cpu_custom_call(DataType *q_out, DataType *r_out,
16
+ DataType *in, uint64_t m, uint64_t k,
17
+ uint64_t n, bool complete) {
18
+ typedef Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic,
19
+ Eigen::RowMajor>
20
+ RowMajorMatrix;
21
+
22
+ Eigen::Map<RowMajorMatrix> input(in, m, n);
23
+ Eigen::HouseholderQR<RowMajorMatrix> qr = input.householderQr();
24
+
25
+ RowMajorMatrix Q, R;
26
+ size_t num_bytes_q;
27
+
28
+ if (complete) {
29
+ Q = qr.householderQ() * RowMajorMatrix::Identity(m, m);
30
+ R = qr.matrixQR();
31
+
32
+ num_bytes_q = m * m * sizeof(DataType);
33
+
34
+ for (uint64_t i = 0; i < m; ++i) {
35
+ for (uint64_t j = 0; j < n; ++j) {
36
+ r_out[i * n + j] = (j >= i) ? R(i, j) : static_cast<DataType>(0.0);
37
+ }
38
+ }
39
+ } else {
40
+ Q = qr.householderQ() * RowMajorMatrix::Identity(m, k);
41
+ R = qr.matrixQR().topRows(k);
42
+
43
+ num_bytes_q = m * k * sizeof(DataType);
44
+
45
+ for (uint64_t i = 0; i < k; ++i) {
46
+ for (uint64_t j = 0; j < n; ++j) {
47
+ r_out[i * n + j] = (j >= i) ? R(i, j) : static_cast<DataType>(0.0);
48
+ }
49
+ }
50
+ }
51
+
52
+ memcpy(q_out, Q.data(), num_bytes_q);
53
+ }
54
+
55
+ template <typename DataType, typename BufferType>
56
+ ffi::Error qr_cpu_custom_call_impl(BufferType operand,
57
+ ffi::Result<BufferType> q,
58
+ ffi::Result<BufferType> r) {
59
+ auto operand_dims = operand.dimensions();
60
+ auto q_dims = q->dimensions();
61
+ auto r_dims = r->dimensions();
62
+
63
+ uint64_t m = q_dims[q_dims.size() - 2];
64
+ uint64_t k = q_dims[q_dims.size() - 1];
65
+ uint64_t n = r_dims[r_dims.size() - 1];
66
+ uint64_t l = r_dims[r_dims.size() - 2];
67
+
68
+ bool complete = l == m;
69
+
70
+ uint64_t batch_items = 1;
71
+ for (auto it = operand_dims.begin(); it != operand_dims.end() - 2; it++) {
72
+ batch_items *= *it;
73
+ }
74
+
75
+ uint64_t q_stride = m * k;
76
+ uint64_t r_stride = n * l;
77
+ uint64_t inner_stride = m * n;
78
+
79
+ for (uint64_t i = 0; i < batch_items; i++) {
80
+ single_matrix_qr_cpu_custom_call<DataType>(
81
+ (DataType *)q->untyped_data() + i * q_stride,
82
+ (DataType *)r->untyped_data() + i * r_stride,
83
+ (DataType *)operand.untyped_data() + i * inner_stride, m, k, n,
84
+ complete);
85
+ }
86
+
87
+ return ffi::Error::Success();
88
+ }
deps/exla/c_src/exla/custom_calls/qr_bf16.cc ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "../exla_types.h"
2
+ #include "qr.h"
3
+
4
+ ffi::Error qr_cpu_custom_call_bf16_impl(ffi::Buffer<ffi::BF16> operand,
5
+ ffi::ResultBuffer<ffi::BF16> q,
6
+ ffi::ResultBuffer<ffi::BF16> r) {
7
+ return qr_cpu_custom_call_impl<exla::bfloat16, ffi::Buffer<ffi::BF16>>(
8
+ operand, q, r);
9
+ }
10
+
11
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(qr_cpu_custom_call_bf16,
12
+ qr_cpu_custom_call_bf16_impl,
13
+ ffi::Ffi::Bind()
14
+ .Arg<ffi::Buffer<ffi::BF16>>()
15
+ .Ret<ffi::Buffer<ffi::BF16>>()
16
+ .Ret<ffi::Buffer<ffi::BF16>>());
17
+
18
+ XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "qr_cpu_custom_call_bf16", "Host",
19
+ qr_cpu_custom_call_bf16);
deps/exla/c_src/exla/custom_calls/qr_f16.cc ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "../exla_types.h"
2
+ #include "qr.h"
3
+
4
+ ffi::Error qr_cpu_custom_call_f16_impl(ffi::Buffer<ffi::F16> operand,
5
+ ffi::ResultBuffer<ffi::F16> q,
6
+ ffi::ResultBuffer<ffi::F16> r) {
7
+ return qr_cpu_custom_call_impl<exla::float16, ffi::Buffer<ffi::F16>>(operand,
8
+ q, r);
9
+ }
10
+
11
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(qr_cpu_custom_call_f16,
12
+ qr_cpu_custom_call_f16_impl,
13
+ ffi::Ffi::Bind()
14
+ .Arg<ffi::Buffer<ffi::F16>>()
15
+ .Ret<ffi::Buffer<ffi::F16>>()
16
+ .Ret<ffi::Buffer<ffi::F16>>());
17
+
18
+ XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "qr_cpu_custom_call_f16", "Host",
19
+ qr_cpu_custom_call_f16);
deps/exla/c_src/exla/custom_calls/qr_f32.cc ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "qr.h"
2
+
3
+ ffi::Error qr_cpu_custom_call_f32_impl(ffi::Buffer<ffi::F32> operand,
4
+ ffi::ResultBuffer<ffi::F32> q,
5
+ ffi::ResultBuffer<ffi::F32> r) {
6
+ return qr_cpu_custom_call_impl<float, ffi::Buffer<ffi::F32>>(operand, q, r);
7
+ }
8
+
9
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(qr_cpu_custom_call_f32,
10
+ qr_cpu_custom_call_f32_impl,
11
+ ffi::Ffi::Bind()
12
+ .Arg<ffi::Buffer<ffi::F32>>()
13
+ .Ret<ffi::Buffer<ffi::F32>>()
14
+ .Ret<ffi::Buffer<ffi::F32>>());
15
+
16
+ XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "qr_cpu_custom_call_f32", "Host",
17
+ qr_cpu_custom_call_f32);
deps/exla/c_src/exla/custom_calls/qr_f64.cc ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "qr.h"
2
+
3
+ ffi::Error qr_cpu_custom_call_f64_impl(ffi::Buffer<ffi::F64> operand,
4
+ ffi::ResultBuffer<ffi::F64> q,
5
+ ffi::ResultBuffer<ffi::F64> r) {
6
+ return qr_cpu_custom_call_impl<double, ffi::Buffer<ffi::F64>>(operand, q, r);
7
+ }
8
+
9
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(qr_cpu_custom_call_f64,
10
+ qr_cpu_custom_call_f64_impl,
11
+ ffi::Ffi::Bind()
12
+ .Arg<ffi::Buffer<ffi::F64>>()
13
+ .Ret<ffi::Buffer<ffi::F64>>()
14
+ .Ret<ffi::Buffer<ffi::F64>>());
15
+
16
+ XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "qr_cpu_custom_call_f64", "Host",
17
+ qr_cpu_custom_call_f64);
deps/exla/c_src/exla/exla.cc ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <fine.hpp>
2
+ #include <stdexcept>
3
+ #include <string>
4
+ #include <tuple>
5
+
6
+ #include "exla_client.h"
7
+ #include "exla_cuda.h"
8
+ #include "exla_log_sink.h"
9
+ #include "exla_mlir.h"
10
+ #include "exla_nif_util.h"
11
+ #include "ipc.h"
12
+ #include "mlir/IR/MLIRContext.h"
13
+ #include "stablehlo/dialect/ChloOps.h"
14
+ #include "stablehlo/dialect/StablehloOps.h"
15
+ #include "xla/pjrt/pjrt_api.h"
16
+ #include "xla/service/platform_util.h"
17
+ #include "xla/tsl/platform/statusor.h"
18
+ #include "llvm/Support/ThreadPool.h"
19
+
20
+ namespace exla {
21
+
22
+ FINE_RESOURCE(llvm::StdThreadPool);
23
+ FINE_RESOURCE(mlir::MLIRContext);
24
+ FINE_RESOURCE(mlir::Value);
25
+ FINE_RESOURCE(mlir::Region);
26
+ FINE_RESOURCE(exla::ExlaClient);
27
+ FINE_RESOURCE(exla::ExlaBuffer);
28
+ FINE_RESOURCE(exla::ExlaExecutable);
29
+ FINE_RESOURCE(exla::MLIRModule);
30
+ FINE_RESOURCE(exla::MLIRFunction);
31
+
32
+ // MLIR Functions
33
+
34
+ fine::ResourcePtr<ExlaBuffer> decode_exla_buffer(ErlNifEnv *env,
35
+ fine::Term buffer_term) {
36
+ try {
37
+ return fine::decode<fine::ResourcePtr<ExlaBuffer>>(env, buffer_term);
38
+ } catch (std::invalid_argument) {
39
+ throw std::invalid_argument(
40
+ "unable to get buffer. It may belong to another node, "
41
+ "consider using Nx.backend_transfer/1");
42
+ }
43
+ }
44
+
45
+ fine::ResourcePtr<llvm::StdThreadPool>
46
+ mlir_new_thread_pool(ErlNifEnv *env, int64_t concurrency) {
47
+ auto strategy = llvm::hardware_concurrency(concurrency);
48
+ return fine::make_resource<llvm::StdThreadPool>(strategy);
49
+ }
50
+
51
+ FINE_NIF(mlir_new_thread_pool, 0);
52
+
53
+ fine::ResourcePtr<mlir::MLIRContext>
54
+ mlir_new_context(ErlNifEnv *env,
55
+ fine::ResourcePtr<llvm::StdThreadPool> thread_pool) {
56
+ auto context = fine::make_resource<mlir::MLIRContext>(
57
+ mlir::MLIRContext::Threading::DISABLED);
58
+
59
+ context->setThreadPool(*thread_pool);
60
+ context->getOrLoadDialect<mlir::func::FuncDialect>();
61
+ context->getOrLoadDialect<mlir::stablehlo::StablehloDialect>();
62
+ context->getOrLoadDialect<mlir::chlo::ChloDialect>();
63
+
64
+ return context;
65
+ }
66
+
67
+ FINE_NIF(mlir_new_context, 0);
68
+
69
+ fine::ResourcePtr<MLIRModule>
70
+ mlir_new_module(ErlNifEnv *env, fine::ResourcePtr<mlir::MLIRContext> ctx) {
71
+ return fine::make_resource<MLIRModule>(ctx);
72
+ }
73
+
74
+ FINE_NIF(mlir_new_module, 0);
75
+
76
+ fine::ResourcePtr<MLIRFunction> mlir_create_function(
77
+ ErlNifEnv *env, fine::ResourcePtr<MLIRModule> module, std::string func_name,
78
+ std::vector<std::string> arg_type_strings,
79
+ std::vector<std::string> ret_type_strings, bool is_public) {
80
+ auto arg_types = std::vector<mlir::Type>{};
81
+
82
+ for (auto const &type_string : arg_type_strings) {
83
+ auto type = module->ParseType(type_string);
84
+ arg_types.push_back(type);
85
+ }
86
+
87
+ auto ret_types = std::vector<mlir::Type>{};
88
+
89
+ for (auto const &type_string : ret_type_strings) {
90
+ auto type = module->ParseType(type_string);
91
+ ret_types.push_back(type);
92
+ }
93
+
94
+ auto func_op =
95
+ module->CreateFunction(func_name, arg_types, ret_types, is_public);
96
+ return fine::make_resource<MLIRFunction>(module, std::move(func_op));
97
+ }
98
+
99
+ FINE_NIF(mlir_create_function, 0);
100
+
101
+ std::vector<fine::ResourcePtr<mlir::Value>>
102
+ mlir_get_function_arguments(ErlNifEnv *env,
103
+ fine::ResourcePtr<MLIRFunction> function) {
104
+ auto args = function->GetArguments();
105
+ std::vector<fine::ResourcePtr<mlir::Value>> values;
106
+ values.reserve(args.size());
107
+
108
+ for (const auto &arg : args) {
109
+ values.push_back(fine::make_resource<mlir::Value>(arg));
110
+ }
111
+
112
+ return values;
113
+ }
114
+
115
+ FINE_NIF(mlir_get_function_arguments, 0);
116
+
117
+ std::vector<fine::ResourcePtr<mlir::Value>>
118
+ mlir_op(ErlNifEnv *env, fine::ResourcePtr<MLIRFunction> function,
119
+ std::string op_name,
120
+ std::vector<fine::ResourcePtr<mlir::Value>> operands,
121
+ std::vector<std::string> result_type_strings,
122
+ std::vector<std::tuple<fine::Atom, std::string>> attributes_kwlist,
123
+ std::vector<fine::ResourcePtr<mlir::Region>> regions) {
124
+ auto result_types = std::vector<mlir::Type>{};
125
+
126
+ for (auto const &type_string : result_type_strings) {
127
+ auto type = function->module()->ParseType(type_string);
128
+ result_types.push_back(type);
129
+ }
130
+
131
+ auto attributes = std::vector<std::tuple<std::string, mlir::Attribute>>{};
132
+
133
+ for (auto const &[key, value] : attributes_kwlist) {
134
+ auto attribute_value = function->module()->ParseAttribute(value);
135
+ attributes.push_back(std::make_tuple(key.to_string(), attribute_value));
136
+ }
137
+
138
+ return function->Op(op_name, operands, result_types, attributes, regions);
139
+ }
140
+
141
+ FINE_NIF(mlir_op, 0);
142
+
143
+ std::tuple<fine::ResourcePtr<mlir::Region>,
144
+ std::vector<fine::ResourcePtr<mlir::Value>>>
145
+ mlir_push_region(ErlNifEnv *env, fine::ResourcePtr<MLIRFunction> function,
146
+ std::vector<std::string> arg_types) {
147
+ auto types = std::vector<mlir::Type>{};
148
+
149
+ for (auto const &type_string : arg_types) {
150
+ auto type = function->module()->ParseType(type_string);
151
+ types.push_back(type);
152
+ }
153
+
154
+ return function->PushRegion(types);
155
+ }
156
+
157
+ FINE_NIF(mlir_push_region, 0);
158
+
159
+ fine::Ok<> mlir_pop_region(ErlNifEnv *env,
160
+ fine::ResourcePtr<MLIRFunction> function) {
161
+ function->PopRegion();
162
+ return fine::Ok();
163
+ }
164
+
165
+ FINE_NIF(mlir_pop_region, 0);
166
+
167
+ mlir::Type mlir_get_typespec(ErlNifEnv *env,
168
+ fine::ResourcePtr<mlir::Value> value) {
169
+ return value->getType();
170
+ }
171
+
172
+ FINE_NIF(mlir_get_typespec, 0);
173
+
174
+ std::string mlir_module_to_string(ErlNifEnv *env,
175
+ fine::ResourcePtr<MLIRModule> module) {
176
+ return module->ToString();
177
+ }
178
+
179
+ FINE_NIF(mlir_module_to_string, 0);
180
+
181
+ template <typename T> T unwrap(tsl::StatusOr<T> status_or) {
182
+ if (!status_or.ok()) {
183
+ throw std::runtime_error(status_or.status().message().data());
184
+ }
185
+
186
+ return std::move(status_or.value());
187
+ }
188
+
189
+ void unwrap(tsl::Status status) {
190
+ if (!status.ok()) {
191
+ throw std::runtime_error(status.message().data());
192
+ }
193
+ }
194
+
195
+ fine::ResourcePtr<ExlaExecutable>
196
+ mlir_compile(ErlNifEnv *env, fine::ResourcePtr<ExlaClient> client,
197
+ fine::ResourcePtr<MLIRModule> module,
198
+ std::vector<xla::Shape> argument_layouts, int64_t num_replicas,
199
+ int64_t num_partitions, bool use_spmd, int64_t device_id) {
200
+ auto build_options = xla::ExecutableBuildOptions();
201
+
202
+ build_options.set_num_replicas(num_replicas);
203
+ build_options.set_num_partitions(num_partitions);
204
+ build_options.set_use_spmd_partitioning(use_spmd);
205
+
206
+ auto compile_portable_executable = false;
207
+ if (device_id >= 0) {
208
+ compile_portable_executable = true;
209
+ build_options.set_device_ordinal(device_id);
210
+ }
211
+
212
+ return unwrap(client->Compile(module->module(), argument_layouts,
213
+ build_options, compile_portable_executable));
214
+ }
215
+
216
+ FINE_NIF(mlir_compile, ERL_NIF_DIRTY_JOB_CPU_BOUND);
217
+
218
+ // ExlaBuffer Functions
219
+
220
+ std::variant<std::tuple<fine::Atom, uint64_t, uint64_t>,
221
+ std::tuple<fine::Atom, std::string, uint64_t, uint64_t>,
222
+ std::tuple<fine::Atom, std::string, uint64_t>>
223
+ get_buffer_device_pointer(ErlNifEnv *env, fine::ResourcePtr<ExlaClient> client,
224
+ fine::Term buffer_term, fine::Atom pointer_kind) {
225
+ auto buffer = decode_exla_buffer(env, buffer_term);
226
+
227
+ uint64_t device_size = unwrap(buffer->GetOnDeviceSizeInBytes());
228
+ uint64_t ptr = unwrap(buffer->GetDevicePointer(client->client()));
229
+
230
+ if (pointer_kind == "local") {
231
+ return std::make_tuple(pointer_kind, ptr, device_size);
232
+ }
233
+
234
+ if (pointer_kind == "host_ipc") {
235
+ auto handle_name =
236
+ "exla:ipc:" + std::to_string(device_size) + ":" + std::to_string(ptr);
237
+ auto fd = get_ipc_handle(handle_name.c_str(), device_size);
238
+
239
+ if (fd == -1) {
240
+ throw std::runtime_error("unable to get IPC handle");
241
+ }
242
+
243
+ auto ipc_ptr = open_ipc_handle(fd, device_size);
244
+ if (ipc_ptr == nullptr) {
245
+ throw std::runtime_error("unable to open IPC handle");
246
+ }
247
+
248
+ memcpy(ipc_ptr, reinterpret_cast<void *>(ptr), device_size);
249
+
250
+ return std::make_tuple(pointer_kind, handle_name, static_cast<uint64_t>(fd),
251
+ device_size);
252
+ }
253
+
254
+ if (pointer_kind == "cuda_ipc") {
255
+ auto maybe_handle = get_cuda_ipc_handle(ptr);
256
+ if (!maybe_handle) {
257
+ throw std::runtime_error("unable to get cuda IPC handle");
258
+ }
259
+
260
+ return std::make_tuple(pointer_kind, maybe_handle.value(), device_size);
261
+ }
262
+
263
+ throw std::invalid_argument("unexpected pointer type");
264
+ }
265
+
266
+ FINE_NIF(get_buffer_device_pointer, 0);
267
+
268
+ fine::ResourcePtr<ExlaBuffer> create_buffer_from_device_pointer(
269
+ ErlNifEnv *env, fine::ResourcePtr<ExlaClient> client,
270
+ fine::Atom pointer_kind, fine::Term pointer_data, xla::Shape shape,
271
+ int64_t device_id) {
272
+ void *ptr = nullptr;
273
+ std::function<void()> on_delete_callback = []() {};
274
+
275
+ if (pointer_kind == "cuda_ipc") {
276
+ auto cuda_ipc_handle_bin = fine::decode<ErlNifBinary>(env, pointer_data);
277
+ auto maybe_pointer = get_pointer_for_ipc_handle(
278
+ cuda_ipc_handle_bin.data, cuda_ipc_handle_bin.size, device_id);
279
+ if (!maybe_pointer) {
280
+ throw std::runtime_error("unable to get pointer for IPC handle");
281
+ }
282
+ ptr = maybe_pointer.value();
283
+ } else if (pointer_kind == "host_ipc") {
284
+ auto tuple =
285
+ fine::decode<std::tuple<uint64_t, std::string>>(env, pointer_data);
286
+ auto fd = std::get<0>(tuple);
287
+ auto memname = std::get<1>(tuple);
288
+ auto device_size = xla::ShapeUtil::ByteSizeOf(shape);
289
+ ptr = open_ipc_handle(fd, device_size);
290
+ if (ptr == nullptr) {
291
+ throw std::runtime_error("unable to get pointer for IPC handle");
292
+ }
293
+ on_delete_callback = [fd, memname, ptr, device_size]() {
294
+ close_ipc_handle(fd, ptr, memname.c_str(), device_size);
295
+ };
296
+ } else if (pointer_kind == "local") {
297
+ auto ptr_int = fine::decode<int64_t>(env, pointer_data);
298
+ ptr = reinterpret_cast<void *>(ptr_int);
299
+ } else {
300
+ throw std::invalid_argument("unexpected pointer type");
301
+ }
302
+
303
+ auto device = unwrap(
304
+ client->client()->LookupDevice(xla::PjRtGlobalDeviceId(device_id)));
305
+ auto memory_space = unwrap(device->default_memory_space());
306
+ auto buffer = unwrap(client->client()->CreateViewOfDeviceBuffer(
307
+ ptr, shape, memory_space, on_delete_callback));
308
+ return fine::make_resource<ExlaBuffer>(std::move(buffer));
309
+ }
310
+
311
+ FINE_NIF(create_buffer_from_device_pointer, 0);
312
+
313
+ fine::ResourcePtr<ExlaBuffer>
314
+ binary_to_device_mem(ErlNifEnv *env, fine::ResourcePtr<ExlaClient> client,
315
+ fine::Term data, xla::Shape shape, int64_t device_id) {
316
+ return unwrap(client->BufferFromBinary(data, shape, device_id));
317
+ }
318
+
319
+ FINE_NIF(binary_to_device_mem, ERL_NIF_DIRTY_JOB_IO_BOUND);
320
+
321
+ fine::Term read_device_mem(ErlNifEnv *env, fine::Term buffer_term,
322
+ int64_t size) {
323
+ auto buffer = decode_exla_buffer(env, buffer_term);
324
+ return unwrap(buffer->ToBinary(env, size));
325
+ }
326
+
327
+ FINE_NIF(read_device_mem, ERL_NIF_DIRTY_JOB_IO_BOUND);
328
+
329
+ std::variant<fine::Ok<>, fine::Error<fine::Atom>>
330
+ deallocate_device_mem(ErlNifEnv *env, fine::Term buffer_term) {
331
+ auto buffer = decode_exla_buffer(env, buffer_term);
332
+
333
+ tsl::Status dealloc_status = buffer->Deallocate();
334
+
335
+ if (!dealloc_status.ok()) {
336
+ return fine::Error(atoms::already_deallocated);
337
+ } else {
338
+ return fine::Ok();
339
+ }
340
+ }
341
+
342
+ FINE_NIF(deallocate_device_mem, ERL_NIF_DIRTY_JOB_IO_BOUND);
343
+
344
+ fine::Ok<> transfer_to_infeed(ErlNifEnv *env,
345
+ fine::ResourcePtr<ExlaClient> client,
346
+ int64_t device_id,
347
+ std::vector<ErlNifBinary> buffers,
348
+ std::vector<xla::Shape> shapes) {
349
+ unwrap(client->TransferToInfeed(env, buffers, shapes, device_id));
350
+
351
+ return fine::Ok();
352
+ }
353
+
354
+ FINE_NIF(transfer_to_infeed, ERL_NIF_DIRTY_JOB_IO_BOUND);
355
+
356
+ fine::Ok<> transfer_from_outfeed(ErlNifEnv *env,
357
+ fine::ResourcePtr<ExlaClient> client,
358
+ int64_t device_id,
359
+ std::vector<xla::Shape> shapes, ErlNifPid pid,
360
+ fine::Term ref) {
361
+ for (auto &shape : shapes) {
362
+ auto msg_env = enif_alloc_env();
363
+ auto msg = unwrap(client->TransferFromOutfeed(msg_env, device_id, shape));
364
+ enif_send(env, &pid, msg_env, enif_make_tuple(msg_env, 2, ref, msg));
365
+ enif_free_env(msg_env);
366
+ }
367
+
368
+ return fine::Ok();
369
+ }
370
+
371
+ FINE_NIF(transfer_from_outfeed, ERL_NIF_DIRTY_JOB_IO_BOUND);
372
+
373
+ fine::ResourcePtr<ExlaBuffer>
374
+ copy_buffer_to_device(ErlNifEnv *env, fine::ResourcePtr<ExlaClient> client,
375
+ fine::Term buffer_term, int64_t device_id) {
376
+ auto buffer = decode_exla_buffer(env, buffer_term);
377
+
378
+ auto device = unwrap(
379
+ client->client()->LookupDevice(xla::PjRtGlobalDeviceId(device_id)));
380
+
381
+ return unwrap(buffer->CopyToDevice(device));
382
+ }
383
+
384
+ FINE_NIF(copy_buffer_to_device, ERL_NIF_DIRTY_JOB_IO_BOUND);
385
+
386
+ // ExlaClient Functions
387
+
388
+ fine::ResourcePtr<ExlaClient> get_host_client(ErlNifEnv *env) {
389
+ return unwrap(GetHostClient());
390
+ }
391
+
392
+ FINE_NIF(get_host_client, 0);
393
+
394
+ fine::ResourcePtr<ExlaClient>
395
+ get_gpu_client(ErlNifEnv *env, double memory_fraction, bool preallocate) {
396
+ return unwrap(GetGpuClient(memory_fraction, preallocate,
397
+ xla::GpuAllocatorConfig::Kind::kBFC));
398
+ }
399
+
400
+ FINE_NIF(get_gpu_client, 0);
401
+
402
+ fine::ResourcePtr<ExlaClient> get_tpu_client(ErlNifEnv *env) {
403
+ return unwrap(GetTpuClient());
404
+ }
405
+
406
+ FINE_NIF(get_tpu_client, 0);
407
+
408
+ fine::ResourcePtr<ExlaClient> get_c_api_client(ErlNifEnv *env,
409
+ std::string device_type) {
410
+ return unwrap(GetCApiClient(device_type));
411
+ }
412
+
413
+ FINE_NIF(get_c_api_client, 0);
414
+
415
+ fine::Ok<> load_pjrt_plugin(ErlNifEnv *env, std::string device_type,
416
+ std::string library_path) {
417
+ unwrap(pjrt::LoadPjrtPlugin(device_type, library_path));
418
+ return fine::Ok();
419
+ }
420
+
421
+ FINE_NIF(load_pjrt_plugin, 0);
422
+
423
+ int64_t get_device_count(ErlNifEnv *env, fine::ResourcePtr<ExlaClient> client) {
424
+ return client->client()->device_count();
425
+ }
426
+
427
+ FINE_NIF(get_device_count, 0);
428
+
429
+ std::map<fine::Atom, int64_t> get_supported_platforms(ErlNifEnv *env) {
430
+ auto platforms = unwrap(xla::PlatformUtil::GetSupportedPlatforms());
431
+
432
+ std::map<fine::Atom, int64_t> platform_info;
433
+
434
+ for (auto &platform : platforms) {
435
+ auto key = fine::Atom(absl::AsciiStrToLower(platform->Name()));
436
+ auto device_count = platform->VisibleDeviceCount();
437
+ platform_info.insert({key, device_count});
438
+ }
439
+
440
+ return platform_info;
441
+ }
442
+
443
+ FINE_NIF(get_supported_platforms, 0);
444
+
445
+ // ExlaExecutable Functions
446
+
447
+ ExlaExecutable::RunResult run(ErlNifEnv *env,
448
+ fine::ResourcePtr<ExlaExecutable> executable,
449
+ ExlaExecutable::RunArguments arguments,
450
+ int64_t device_id) {
451
+ return unwrap(executable->Run(env, arguments, device_id));
452
+ }
453
+
454
+ ExlaExecutable::RunResult run_cpu(ErlNifEnv *env,
455
+ fine::ResourcePtr<ExlaExecutable> executable,
456
+ ExlaExecutable::RunArguments arguments,
457
+ int64_t device_id) {
458
+ return run(env, executable, arguments, device_id);
459
+ }
460
+
461
+ FINE_NIF(run_cpu, ERL_NIF_DIRTY_JOB_CPU_BOUND);
462
+
463
+ ExlaExecutable::RunResult run_io(ErlNifEnv *env,
464
+ fine::ResourcePtr<ExlaExecutable> executable,
465
+ ExlaExecutable::RunArguments arguments,
466
+ int64_t device_id) {
467
+ return run(env, executable, arguments, device_id);
468
+ }
469
+
470
+ FINE_NIF(run_io, ERL_NIF_DIRTY_JOB_IO_BOUND);
471
+
472
+ // Serialization Functions
473
+
474
+ std::string serialize_executable(ErlNifEnv *env,
475
+ fine::ResourcePtr<ExlaExecutable> executable) {
476
+ return unwrap(executable->SerializeExecutable());
477
+ }
478
+
479
+ FINE_NIF(serialize_executable, 0);
480
+
481
+ fine::ResourcePtr<ExlaExecutable>
482
+ deserialize_executable(ErlNifEnv *env, fine::ResourcePtr<ExlaClient> client,
483
+ std::string serialized) {
484
+ return unwrap(client->DeserializeExecutable(serialized));
485
+ }
486
+
487
+ FINE_NIF(deserialize_executable, 0);
488
+
489
+ // Logging
490
+
491
+ fine::Ok<> start_log_sink(ErlNifEnv *env, ErlNifPid logger_pid) {
492
+ ExlaLogSink *sink = new ExlaLogSink(logger_pid);
493
+
494
+ // NO_DEFAULT_LOGGER doesn't behave right
495
+ for (auto *log_sink : tsl::TFGetLogSinks()) {
496
+ tsl::TFRemoveLogSink(log_sink);
497
+ }
498
+
499
+ tsl::TFAddLogSink(sink);
500
+
501
+ return fine::Ok();
502
+ }
503
+
504
+ FINE_NIF(start_log_sink, 0);
505
+
506
+ } // namespace exla
507
+
508
+ FINE_INIT("Elixir.EXLA.NIF");
deps/exla/c_src/exla/exla_client.h ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef EXLA_CLIENT_H_
2
+ #define EXLA_CLIENT_H_
3
+
4
+ #include <memory>
5
+ #include <utility>
6
+ #include <vector>
7
+
8
+ #include <fine.hpp>
9
+ #include <erl_nif.h>
10
+ #include "exla_types.h"
11
+ #include "mlir/IR/BuiltinOps.h"
12
+ #include "mlir/IR/OwningOpRef.h"
13
+ #include "xla/pjrt/gpu/gpu_helpers.h"
14
+ #include "xla/pjrt/pjrt_client.h"
15
+ #include "xla/shape.h"
16
+
17
+ // The implementations in this module are designed after implementations
18
+ // in the XLA runtime, PjRt. Deviations are made where it makes sense
19
+ // to work better with the VM.
20
+
21
+ namespace exla {
22
+
23
+ class ExlaClient;
24
+
25
+ class ExlaBuffer {
26
+ public:
27
+ ExlaBuffer(std::unique_ptr<xla::PjRtBuffer> buffer);
28
+
29
+ int device_id() { return buffer_->device()->id(); }
30
+ xla::PjRtBuffer* buffer() { return buffer_.get(); }
31
+ tsl::StatusOr<fine::ResourcePtr<ExlaBuffer>> CopyToDevice(xla::PjRtDevice* dst_device);
32
+ tsl::StatusOr<ERL_NIF_TERM> ToBinary(ErlNifEnv* env, exla::int64 size);
33
+ tsl::Status Deallocate();
34
+
35
+ tsl::StatusOr<std::uintptr_t> GetDevicePointer(xla::PjRtClient* client) {
36
+ return client->UnsafeBufferPointer(buffer_.get());
37
+ }
38
+
39
+ tsl::StatusOr<size_t> GetOnDeviceSizeInBytes() {
40
+ return buffer_.get()->GetOnDeviceSizeInBytes();
41
+ }
42
+
43
+ ~ExlaBuffer() {
44
+ // Theoretically this may block if a computation is running
45
+ // but we always block the host until the computation is done.
46
+ }
47
+
48
+ private:
49
+ std::unique_ptr<xla::PjRtBuffer> buffer_;
50
+ };
51
+
52
+ class ExlaExecutable {
53
+ public:
54
+ using ReplicaArgument = std::variant<fine::ResourcePtr<ExlaBuffer>, std::tuple<fine::Term, xla::Shape>>;
55
+ using RunArguments = std::vector<std::vector<ReplicaArgument>>;
56
+
57
+ using RunReplicaResult = std::tuple<std::vector<fine::ResourcePtr<ExlaBuffer>>, int64_t>;
58
+ using RunResult =std::vector<RunReplicaResult>;
59
+
60
+ ExlaExecutable(std::unique_ptr<xla::PjRtLoadedExecutable> executable,
61
+ absl::optional<std::string> fingerprint,
62
+ ExlaClient* client);
63
+
64
+ xla::PjRtLoadedExecutable* executable() { return executable_.get(); }
65
+
66
+ tsl::StatusOr<RunResult> Run(ErlNifEnv* env, RunArguments arguments, int device_id);
67
+
68
+ tsl::StatusOr<std::string> SerializeExecutable() { return executable_->SerializeExecutable(); }
69
+
70
+ private:
71
+ std::unique_ptr<xla::PjRtLoadedExecutable> executable_;
72
+ absl::optional<std::string> fingerprint_;
73
+ ExlaClient* client_;
74
+ };
75
+
76
+ class ExlaClient {
77
+ public:
78
+ explicit ExlaClient(std::shared_ptr<xla::PjRtClient> client);
79
+
80
+ virtual ~ExlaClient() = default;
81
+
82
+ xla::PjRtClient* client() { return client_.get(); }
83
+
84
+ // Compiles the given computation with the given compile options
85
+
86
+ tsl::StatusOr<fine::ResourcePtr<ExlaExecutable>> Compile(mlir::ModuleOp computation,
87
+ std::vector<xla::Shape> argument_layouts,
88
+ xla::ExecutableBuildOptions& options,
89
+ bool compile_portable_executable);
90
+
91
+ tsl::StatusOr<fine::ResourcePtr<ExlaBuffer>> BufferFromBinary(ERL_NIF_TERM binary_term,
92
+ xla::Shape& shape,
93
+ int device_id);
94
+
95
+ tsl::StatusOr<fine::ResourcePtr<ExlaExecutable>> DeserializeExecutable(std::string serialized_executable);
96
+
97
+ // TODO(seanmor5): This is device logic and should be refactored
98
+ tsl::Status TransferToInfeed(ErlNifEnv* env,
99
+ std::vector<ErlNifBinary> buffer_bins,
100
+ std::vector<xla::Shape> shapes,
101
+ int device_id);
102
+
103
+ tsl::StatusOr<ERL_NIF_TERM> TransferFromOutfeed(ErlNifEnv* env, int device_id, xla::Shape& shape);
104
+
105
+ private:
106
+ std::shared_ptr<xla::PjRtClient> client_;
107
+ };
108
+
109
+ tsl::StatusOr<fine::ResourcePtr<ExlaClient>> GetHostClient();
110
+
111
+ tsl::StatusOr<fine::ResourcePtr<ExlaClient>> GetGpuClient(double memory_fraction,
112
+ bool preallocate,
113
+ xla::GpuAllocatorConfig::Kind kind);
114
+
115
+ tsl::StatusOr<fine::ResourcePtr<ExlaClient>> GetTpuClient();
116
+
117
+ tsl::StatusOr<fine::ResourcePtr<ExlaClient>> GetCApiClient(std::string device_type);
118
+ } // namespace exla
119
+
120
+ #endif
deps/exla/c_src/exla/exla_log_sink.h ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef EXLA_LOG_SINK_H_
2
+ #define EXLA_LOG_SINK_H_
3
+
4
+ #include <string>
5
+
6
+ #include "absl/base/log_severity.h"
7
+ #include "exla_nif_util.h"
8
+ #include <fine.hpp>
9
+ #include "tsl/platform/logging.h"
10
+
11
+ namespace exla {
12
+
13
+ // Redirects calls to logging to the Elixir Logger. `sink_pid`
14
+ // is the PID for a GenServer in Elixir which receives messages
15
+ // with logging information on every call to `LOG(severity)`.
16
+ class ExlaLogSink : public tsl::TFLogSink {
17
+ public:
18
+ explicit ExlaLogSink(ErlNifPid sink_pid) : sink_pid_(sink_pid) {}
19
+
20
+ void Send(const tsl::TFLogEntry &entry) {
21
+ auto string = entry.ToString();
22
+ auto fname = entry.FName();
23
+ int64_t line = entry.Line();
24
+ auto severity = entry.log_severity();
25
+
26
+ if (severity == absl::LogSeverity::kFatal) {
27
+ // LOG(FATAL) aborts the program before we are able to send and
28
+ // log the information from Elixir, so we need to get it out
29
+ // there for debugging before everything crashes
30
+ std::cerr << "[FATAL] " << fname << ":" << line << " " << string << "\n";
31
+ }
32
+
33
+ auto env = enif_alloc_env();
34
+
35
+ auto message = fine::encode(
36
+ env, std::make_tuple(severity_to_atom(severity), string, fname, line));
37
+
38
+ enif_send(NULL, &sink_pid_, env, message);
39
+
40
+ enif_free_env(env);
41
+ }
42
+
43
+ private:
44
+ fine::Atom severity_to_atom(absl::LogSeverity severity) {
45
+ switch (severity) {
46
+ case absl::LogSeverity::kInfo:
47
+ return atoms::info;
48
+ case absl::LogSeverity::kWarning:
49
+ return atoms::warning;
50
+ case absl::LogSeverity::kError:
51
+ return atoms::error;
52
+ case absl::LogSeverity::kFatal:
53
+ return atoms::error;
54
+ default:
55
+ return atoms::info;
56
+ }
57
+ }
58
+
59
+ ErlNifPid sink_pid_;
60
+ };
61
+
62
+ } // namespace exla
63
+
64
+ #endif
deps/exla/c_src/exla/exla_mlir.h ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef EXLA_MLIR_BUILDER_H_
2
+ #define EXLA_MLIR_BUILDER_H_
3
+
4
+ #include <fine.hpp>
5
+ #include <stack>
6
+
7
+ #include "mlir/Dialect/Func/IR/FuncOps.h"
8
+ #include "mlir/IR/Builders.h"
9
+ #include "mlir/IR/BuiltinOps.h"
10
+ #include "mlir/IR/MLIRContext.h"
11
+ #include "mlir/IR/OwningOpRef.h"
12
+
13
+ namespace exla {
14
+
15
+ class MLIRModule;
16
+
17
+ class MLIRFunction {
18
+ public:
19
+ MLIRFunction(fine::ResourcePtr<MLIRModule> module, std::unique_ptr<mlir::func::FuncOp> func);
20
+
21
+ std::vector<fine::ResourcePtr<mlir::Value>> Op(
22
+ std::string op_name, std::vector<fine::ResourcePtr<mlir::Value>> operands,
23
+ std::vector<mlir::Type> result_types,
24
+ std::vector<std::tuple<std::string, mlir::Attribute>> attributes,
25
+ std::vector<fine::ResourcePtr<mlir::Region>> regions);
26
+
27
+ std::tuple<fine::ResourcePtr<mlir::Region>, std::vector<fine::ResourcePtr<mlir::Value>>> PushRegion(std::vector<mlir::Type> types);
28
+ void PopRegion();
29
+
30
+ llvm::MutableArrayRef<mlir::BlockArgument> GetArguments() { return func_->getBody().front().getArguments(); }
31
+
32
+ fine::ResourcePtr<MLIRModule> module() { return module_; }
33
+
34
+ private:
35
+ fine::ResourcePtr<MLIRModule> module_;
36
+ std::unique_ptr<mlir::func::FuncOp> func_;
37
+
38
+ std::stack<fine::ResourcePtr<mlir::Region>> region_stack;
39
+
40
+ void setInsertionPoint();
41
+ };
42
+
43
+ class MLIRModule {
44
+ public:
45
+ MLIRModule(fine::ResourcePtr<mlir::MLIRContext> context);
46
+
47
+ std::unique_ptr<mlir::func::FuncOp> CreateFunction(
48
+ std::string name,
49
+ std::vector<mlir::Type> arg_types,
50
+ std::vector<mlir::Type> ret_types,
51
+ bool is_public);
52
+
53
+ std::string ToString();
54
+
55
+ // Note: ParseAttribute and ParseType return nullptr if the parsing fails
56
+ mlir::Type ParseType(std::string);
57
+ mlir::Attribute ParseAttribute(std::string);
58
+
59
+ mlir::ModuleOp module() { return module_.get(); }
60
+ mlir::OpBuilder *builder() { return builder_.get(); }
61
+
62
+ private:
63
+ fine::ResourcePtr<mlir::MLIRContext> context_;
64
+ mlir::OwningOpRef<mlir::ModuleOp> module_;
65
+ std::unique_ptr<mlir::OpBuilder> builder_;
66
+ };
67
+
68
+ } // namespace exla
69
+
70
+ #endif
deps/exla/c_src/exla/exla_nif_util.h ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef EXLA_NIF_UTIL_H_
2
+ #define EXLA_NIF_UTIL_H_
3
+
4
+ #include <fine.hpp>
5
+ #include <tuple>
6
+
7
+ #include "xla/shape.h"
8
+ #include "xla/shape_util.h"
9
+ #include "mlir/IR/Types.h"
10
+ #include "stablehlo/dialect/StablehloOps.h"
11
+
12
+ namespace exla {
13
+
14
+ namespace atoms {
15
+ static auto ElixirEXLATypespec = fine::Atom("Elixir.EXLA.Typespec");
16
+ static auto __struct__ = fine::Atom("__struct__");
17
+ static auto already_deallocated = fine::Atom("already_deallocated");
18
+ static auto bf = fine::Atom("bf");
19
+ static auto c = fine::Atom("c");
20
+ static auto error = fine::Atom("error");
21
+ static auto f = fine::Atom("f");
22
+ static auto info = fine::Atom("info");
23
+ static auto pred = fine::Atom("pred");
24
+ static auto s = fine::Atom("s");
25
+ static auto shape = fine::Atom("shape");
26
+ static auto token = fine::Atom("token");
27
+ static auto type = fine::Atom("type");
28
+ static auto u = fine::Atom("u");
29
+ static auto warning = fine::Atom("warning");
30
+ } // namespace atoms
31
+ } // namespace exla
32
+
33
+ namespace fine {
34
+
35
+ // Define decoding for xla::Shape from for %EXLA.Typespec{} term
36
+ template <> struct Decoder<xla::Shape> {
37
+ static xla::Shape decode(ErlNifEnv *env, const ERL_NIF_TERM &term) {
38
+ ERL_NIF_TERM type_term;
39
+ ERL_NIF_TERM shape_term;
40
+
41
+ if (!enif_get_map_value(env, term, fine::encode(env, exla::atoms::type),
42
+ &type_term)) {
43
+ throw std::invalid_argument(
44
+ "decode failed, expected EXLA.Typespec struct");
45
+ }
46
+
47
+ if (!enif_get_map_value(env, term, fine::encode(env, exla::atoms::shape),
48
+ &shape_term)) {
49
+ throw std::invalid_argument(
50
+ "decode failed, expected EXLA.Typespec struct");
51
+ }
52
+
53
+ return xla::ShapeUtil::MakeShape(decode_type(env, type_term),
54
+ decode_shape(env, shape_term));
55
+ }
56
+
57
+ private:
58
+ static std::vector<int64_t> decode_shape(ErlNifEnv *env,
59
+ const ERL_NIF_TERM &term) {
60
+ int size;
61
+ const ERL_NIF_TERM *terms;
62
+
63
+ if (!enif_get_tuple(env, term, &size, &terms)) {
64
+ throw std::invalid_argument(
65
+ "decode failed, expected shape to be a tuple");
66
+ }
67
+
68
+ auto vector = std::vector<int64_t>();
69
+ vector.reserve(size);
70
+
71
+ for (auto i = 0; i < size; i++) {
72
+ auto elem = fine::decode<int64_t>(env, terms[i]);
73
+ vector.push_back(elem);
74
+ }
75
+
76
+ return vector;
77
+ }
78
+
79
+ static xla::PrimitiveType decode_type(ErlNifEnv *env,
80
+ const ERL_NIF_TERM &term) {
81
+ auto [element, size] =
82
+ fine::decode<std::tuple<fine::Atom, uint64_t>>(env, term);
83
+
84
+ if (element == "u") {
85
+ switch (size) {
86
+ case 2:
87
+ return xla::U2;
88
+ case 4:
89
+ return xla::U4;
90
+ case 8:
91
+ return xla::U8;
92
+ case 16:
93
+ return xla::U16;
94
+ case 32:
95
+ return xla::U32;
96
+ case 64:
97
+ return xla::U64;
98
+ }
99
+ }
100
+ if (element == "s") {
101
+ switch (size) {
102
+ case 2:
103
+ return xla::S2;
104
+ case 4:
105
+ return xla::S4;
106
+ case 8:
107
+ return xla::S8;
108
+ case 16:
109
+ return xla::S16;
110
+ case 32:
111
+ return xla::S32;
112
+ case 64:
113
+ return xla::S64;
114
+ }
115
+ }
116
+ if (element == "f") {
117
+ switch (size) {
118
+ case 8:
119
+ return xla::F8E5M2;
120
+ case 16:
121
+ return xla::F16;
122
+ case 32:
123
+ return xla::F32;
124
+ case 64:
125
+ return xla::F64;
126
+ }
127
+ }
128
+ if (element == "bf") {
129
+ switch (size) {
130
+ case 16:
131
+ return xla::BF16;
132
+ }
133
+ }
134
+ if (element == "c") {
135
+ switch (size) {
136
+ case 64:
137
+ return xla::C64;
138
+ case 128:
139
+ return xla::C128;
140
+ }
141
+ }
142
+ if (element == "pred") {
143
+ return xla::PRED;
144
+ }
145
+
146
+ throw std::invalid_argument("decode failed, unexpected type");
147
+ }
148
+ };
149
+
150
+ // Define encoding for mlir::Type into %EXLA.Typespec{} term
151
+ template <> struct Encoder<mlir::Type> {
152
+ static ERL_NIF_TERM encode(ErlNifEnv *env, const mlir::Type &type) {
153
+ ERL_NIF_TERM keys[] = {
154
+ fine::encode(env, exla::atoms::__struct__),
155
+ fine::encode(env, exla::atoms::type),
156
+ fine::encode(env, exla::atoms::shape),
157
+ };
158
+
159
+ ERL_NIF_TERM values[] = {
160
+ fine::encode(env, exla::atoms::ElixirEXLATypespec),
161
+ encode_type(env, type),
162
+ encode_shape(env, type),
163
+ };
164
+
165
+ ERL_NIF_TERM map;
166
+ if (!enif_make_map_from_arrays(env, keys, values, 3, &map)) {
167
+ throw std::runtime_error("encode: failed to make a map");
168
+ }
169
+
170
+ return map;
171
+ }
172
+
173
+ private:
174
+ static ERL_NIF_TERM encode_type(ErlNifEnv *env, const mlir::Type &type) {
175
+ if (mlir::isa<mlir::stablehlo::TokenType>(type)) {
176
+ return fine::encode(env, exla::atoms::token);
177
+ }
178
+
179
+ std::optional<fine::Atom> type_name;
180
+ std::optional<uint64_t> type_size;
181
+
182
+ if (mlir::isa<mlir::RankedTensorType>(type)) {
183
+ auto tensor_type = mlir::cast<mlir::RankedTensorType>(type);
184
+ auto element_type = tensor_type.getElementType();
185
+
186
+ if (element_type.isSignlessInteger(1)) {
187
+ type_name = exla::atoms::pred;
188
+ type_size = 8;
189
+ } else if (auto integer_type =
190
+ mlir::dyn_cast<mlir::IntegerType>(element_type)) {
191
+ if (integer_type.isUnsigned()) {
192
+ type_name = exla::atoms::u;
193
+ } else {
194
+ type_name = exla::atoms::s;
195
+ }
196
+
197
+ type_size = integer_type.getWidth();
198
+ } else if (element_type.isBF16()) {
199
+ type_name = exla::atoms::bf;
200
+ type_size = 16;
201
+ } else if (auto float_type =
202
+ mlir::dyn_cast<mlir::FloatType>(element_type)) {
203
+ type_name = exla::atoms::f;
204
+ type_size = float_type.getWidth();
205
+ } else if (auto complex_type =
206
+ mlir::dyn_cast<mlir::ComplexType>(element_type)) {
207
+ auto element_type = complex_type.getElementType();
208
+ type_name = exla::atoms::c;
209
+ type_size = mlir::cast<mlir::FloatType>(element_type).getWidth() * 2;
210
+ }
211
+ }
212
+
213
+ if (type_name) {
214
+ return fine::encode(
215
+ env, std::make_tuple(type_name.value(), type_size.value()));
216
+ } else {
217
+ throw std::invalid_argument("encode failed, unexpected mlir type");
218
+ }
219
+ }
220
+
221
+ static ERL_NIF_TERM encode_shape(ErlNifEnv *env, const mlir::Type &type) {
222
+ if (mlir::isa<mlir::stablehlo::TokenType>(type)) {
223
+ return enif_make_tuple(env, 0);
224
+ }
225
+
226
+ if (mlir::isa<mlir::RankedTensorType>(type)) {
227
+ auto tensor_type = mlir::cast<mlir::RankedTensorType>(type);
228
+ auto dims_array = tensor_type.getShape();
229
+
230
+ auto dims = std::vector<ERL_NIF_TERM>{};
231
+ dims.reserve(dims_array.size());
232
+
233
+ for (auto dim : dims_array) {
234
+ dims.push_back(fine::encode<int64_t>(env, dim));
235
+ }
236
+
237
+ return enif_make_tuple_from_array(env, dims.data(), dims.size());
238
+ }
239
+
240
+ throw std::invalid_argument("encode failed, unexpected mlir type");
241
+ }
242
+ };
243
+ } // namespace fine
244
+
245
+ // Helper Macros
246
+ //
247
+ // See:
248
+ // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/stream_executor/lib/statusor.h
249
+
250
+ #define EXLA_STATUS_MACROS_CONCAT_NAME(x, y) \
251
+ EXLA_STATUS_MACROS_CONCAT_NAME_IMPL(x, y)
252
+
253
+ #define EXLA_STATUS_MACROS_CONCAT_NAME_IMPL(x, y) x##y
254
+
255
+ // Macro to be used to consume StatusOr. Will bind lhs
256
+ // to value if the status is OK, otherwise will return
257
+ // the status.
258
+ #define EXLA_ASSIGN_OR_RETURN(lhs, rexpr) \
259
+ EXLA_ASSIGN_OR_RETURN_IMPL( \
260
+ EXLA_STATUS_MACROS_CONCAT_NAME(_status_or_value, __COUNTER__), lhs, \
261
+ rexpr)
262
+
263
+ #define EXLA_ASSIGN_OR_RETURN_IMPL(statusor, lhs, rexpr) \
264
+ auto statusor = (rexpr); \
265
+ if (!statusor.ok()) { \
266
+ return statusor.status(); \
267
+ } \
268
+ lhs = std::move(statusor.value());
269
+
270
+ #endif
deps/exla/cache/0.10.0/objs/exla_mlir.o ADDED
Binary file (58.9 kB). View file
 
deps/exla/cache/0.10.0/objs/ipc.o ADDED
Binary file (2.3 kB). View file
 
deps/exla/cache/xla_extension/include/_virtual_includes/FXdiv/fxdiv.h ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #ifndef FXDIV_H
3
+ #define FXDIV_H
4
+
5
+ #if defined(__cplusplus) && (__cplusplus >= 201103L)
6
+ #include <cstddef>
7
+ #include <cstdint>
8
+ #include <climits>
9
+ #elif !defined(__OPENCL_VERSION__)
10
+ #include <stddef.h>
11
+ #include <stdint.h>
12
+ #include <limits.h>
13
+ #endif
14
+
15
+ #if defined(_MSC_VER)
16
+ #include <intrin.h>
17
+ #if defined(_M_IX86) || defined(_M_X64)
18
+ #include <immintrin.h>
19
+ #endif
20
+ #endif
21
+
22
+ #ifndef FXDIV_USE_INLINE_ASSEMBLY
23
+ #define FXDIV_USE_INLINE_ASSEMBLY 0
24
+ #endif
25
+
26
+ static inline uint64_t fxdiv_mulext_uint32_t(uint32_t a, uint32_t b) {
27
+ #if defined(_MSC_VER) && defined(_M_IX86)
28
+ return (uint64_t) __emulu((unsigned int) a, (unsigned int) b);
29
+ #else
30
+ return (uint64_t) a * (uint64_t) b;
31
+ #endif
32
+ }
33
+
34
+ static inline uint32_t fxdiv_mulhi_uint32_t(uint32_t a, uint32_t b) {
35
+ #if defined(__OPENCL_VERSION__)
36
+ return mul_hi(a, b);
37
+ #elif defined(__CUDA_ARCH__)
38
+ return (uint32_t) __umulhi((unsigned int) a, (unsigned int) b);
39
+ #elif defined(_MSC_VER) && defined(_M_IX86)
40
+ return (uint32_t) (__emulu((unsigned int) a, (unsigned int) b) >> 32);
41
+ #elif defined(_MSC_VER) && defined(_M_ARM)
42
+ return (uint32_t) _MulUnsignedHigh((unsigned long) a, (unsigned long) b);
43
+ #else
44
+ return (uint32_t) (((uint64_t) a * (uint64_t) b) >> 32);
45
+ #endif
46
+ }
47
+
48
+ static inline uint64_t fxdiv_mulhi_uint64_t(uint64_t a, uint64_t b) {
49
+ #if defined(__OPENCL_VERSION__)
50
+ return mul_hi(a, b);
51
+ #elif defined(__CUDA_ARCH__)
52
+ return (uint64_t) __umul64hi((unsigned long long) a, (unsigned long long) b);
53
+ #elif defined(_MSC_VER) && defined(_M_X64)
54
+ return (uint64_t) __umulh((unsigned __int64) a, (unsigned __int64) b);
55
+ #elif defined(__GNUC__) && defined(__SIZEOF_INT128__)
56
+ return (uint64_t) (((((unsigned __int128) a) * ((unsigned __int128) b))) >> 64);
57
+ #else
58
+ const uint32_t a_lo = (uint32_t) a;
59
+ const uint32_t a_hi = (uint32_t) (a >> 32);
60
+ const uint32_t b_lo = (uint32_t) b;
61
+ const uint32_t b_hi = (uint32_t) (b >> 32);
62
+
63
+ const uint64_t t = fxdiv_mulext_uint32_t(a_hi, b_lo) +
64
+ (uint64_t) fxdiv_mulhi_uint32_t(a_lo, b_lo);
65
+ return fxdiv_mulext_uint32_t(a_hi, b_hi) + (t >> 32) +
66
+ ((fxdiv_mulext_uint32_t(a_lo, b_hi) + (uint64_t) (uint32_t) t) >> 32);
67
+ #endif
68
+ }
69
+
70
+ static inline size_t fxdiv_mulhi_size_t(size_t a, size_t b) {
71
+ #if SIZE_MAX == UINT32_MAX
72
+ return (size_t) fxdiv_mulhi_uint32_t((uint32_t) a, (uint32_t) b);
73
+ #elif SIZE_MAX == UINT64_MAX
74
+ return (size_t) fxdiv_mulhi_uint64_t((uint64_t) a, (uint64_t) b);
75
+ #else
76
+ #error Unsupported platform
77
+ #endif
78
+ }
79
+
80
+ struct fxdiv_divisor_uint32_t {
81
+ uint32_t value;
82
+ uint32_t m;
83
+ uint8_t s1;
84
+ uint8_t s2;
85
+ };
86
+
87
+ struct fxdiv_result_uint32_t {
88
+ uint32_t quotient;
89
+ uint32_t remainder;
90
+ };
91
+
92
+ struct fxdiv_divisor_uint64_t {
93
+ uint64_t value;
94
+ uint64_t m;
95
+ uint8_t s1;
96
+ uint8_t s2;
97
+ };
98
+
99
+ struct fxdiv_result_uint64_t {
100
+ uint64_t quotient;
101
+ uint64_t remainder;
102
+ };
103
+
104
+ struct fxdiv_divisor_size_t {
105
+ size_t value;
106
+ size_t m;
107
+ uint8_t s1;
108
+ uint8_t s2;
109
+ };
110
+
111
+ struct fxdiv_result_size_t {
112
+ size_t quotient;
113
+ size_t remainder;
114
+ };
115
+
116
+ static inline struct fxdiv_divisor_uint32_t fxdiv_init_uint32_t(uint32_t d) {
117
+ struct fxdiv_divisor_uint32_t result = { d };
118
+ if (d == 1) {
119
+ result.m = UINT32_C(1);
120
+ result.s1 = 0;
121
+ result.s2 = 0;
122
+ } else {
123
+ #if defined(__OPENCL_VERSION__)
124
+ const uint32_t l_minus_1 = 31 - clz(d - 1);
125
+ #elif defined(__CUDA_ARCH__)
126
+ const uint32_t l_minus_1 = 31 - __clz((int) (d - 1));
127
+ #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64) || defined(_M_ARM) || defined(_M_ARM64))
128
+ unsigned long l_minus_1;
129
+ _BitScanReverse(&l_minus_1, (unsigned long) (d - 1));
130
+ #elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) && FXDIV_USE_INLINE_ASSEMBLY
131
+ uint32_t l_minus_1;
132
+ __asm__("BSRL %[d_minus_1], %[l_minus_1]"
133
+ : [l_minus_1] "=r" (l_minus_1)
134
+ : [d_minus_1] "r" (d - 1)
135
+ : "cc");
136
+ #elif defined(__GNUC__)
137
+ const uint32_t l_minus_1 = 31 - __builtin_clz(d - 1);
138
+ #else
139
+ /* Based on Algorithm 2 from Hacker's delight */
140
+
141
+ uint32_t l_minus_1 = 0;
142
+ uint32_t x = d - 1;
143
+ uint32_t y = x >> 16;
144
+ if (y != 0) {
145
+ l_minus_1 += 16;
146
+ x = y;
147
+ }
148
+ y = x >> 8;
149
+ if (y != 0) {
150
+ l_minus_1 += 8;
151
+ x = y;
152
+ }
153
+ y = x >> 4;
154
+ if (y != 0) {
155
+ l_minus_1 += 4;
156
+ x = y;
157
+ }
158
+ y = x >> 2;
159
+ if (y != 0) {
160
+ l_minus_1 += 2;
161
+ x = y;
162
+ }
163
+ if ((x & 2) != 0) {
164
+ l_minus_1 += 1;
165
+ }
166
+ #endif
167
+ uint32_t u_hi = (UINT32_C(2) << (uint32_t) l_minus_1) - d;
168
+
169
+ /* Division of 64-bit number u_hi:UINT32_C(0) by 32-bit number d, 32-bit quotient output q */
170
+ #if defined(__GNUC__) && defined(__i386__) && FXDIV_USE_INLINE_ASSEMBLY
171
+ uint32_t q;
172
+ __asm__("DIVL %[d]"
173
+ : "=a" (q), "+d" (u_hi)
174
+ : [d] "r" (d), "a" (0)
175
+ : "cc");
176
+ #elif (defined(_MSC_VER) && _MSC_VER >= 1920) && !defined(__clang__) && !defined(__INTEL_COMPILER) && (defined(_M_IX86) || defined(_M_X64))
177
+ unsigned int remainder;
178
+ const uint32_t q = (uint32_t) _udiv64((unsigned __int64) ((uint64_t) u_hi << 32), (unsigned int) d, &remainder);
179
+ #else
180
+ const uint32_t q = ((uint64_t) u_hi << 32) / d;
181
+ #endif
182
+
183
+ result.m = q + UINT32_C(1);
184
+ result.s1 = 1;
185
+ result.s2 = (uint8_t) l_minus_1;
186
+ }
187
+ return result;
188
+ }
189
+
190
+ static inline struct fxdiv_divisor_uint64_t fxdiv_init_uint64_t(uint64_t d) {
191
+ struct fxdiv_divisor_uint64_t result = { d };
192
+ if (d == 1) {
193
+ result.m = UINT64_C(1);
194
+ result.s1 = 0;
195
+ result.s2 = 0;
196
+ } else {
197
+ #if defined(__OPENCL_VERSION__)
198
+ const uint32_t nlz_d = clz(d);
199
+ const uint32_t l_minus_1 = 63 - clz(d - 1);
200
+ #elif defined(__CUDA_ARCH__)
201
+ const uint32_t nlz_d = __clzll((long long) d);
202
+ const uint32_t l_minus_1 = 63 - __clzll((long long) (d - 1));
203
+ #elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64))
204
+ unsigned long l_minus_1;
205
+ _BitScanReverse64(&l_minus_1, (unsigned __int64) (d - 1));
206
+ unsigned long bsr_d;
207
+ _BitScanReverse64(&bsr_d, (unsigned __int64) d);
208
+ const uint32_t nlz_d = bsr_d ^ 0x3F;
209
+ #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_ARM))
210
+ const uint64_t d_minus_1 = d - 1;
211
+ const uint8_t d_is_power_of_2 = (d & d_minus_1) == 0;
212
+ unsigned long l_minus_1;
213
+ if ((uint32_t) (d_minus_1 >> 32) == 0) {
214
+ _BitScanReverse(&l_minus_1, (unsigned long) d_minus_1);
215
+ } else {
216
+ _BitScanReverse(&l_minus_1, (unsigned long) (uint32_t) (d_minus_1 >> 32));
217
+ l_minus_1 += 32;
218
+ }
219
+ const uint32_t nlz_d = ((uint8_t) l_minus_1 ^ UINT8_C(0x3F)) - d_is_power_of_2;
220
+ #elif defined(__GNUC__) && defined(__x86_64__) && FXDIV_USE_INLINE_ASSEMBLY
221
+ uint64_t l_minus_1;
222
+ __asm__("BSRQ %[d_minus_1], %[l_minus_1]"
223
+ : [l_minus_1] "=r" (l_minus_1)
224
+ : [d_minus_1] "r" (d - 1)
225
+ : "cc");
226
+ #elif defined(__GNUC__)
227
+ const uint32_t l_minus_1 = 63 - __builtin_clzll(d - 1);
228
+ const uint32_t nlz_d = __builtin_clzll(d);
229
+ #else
230
+ /* Based on Algorithm 2 from Hacker's delight */
231
+ const uint64_t d_minus_1 = d - 1;
232
+ const uint32_t d_is_power_of_2 = (d & d_minus_1) == 0;
233
+ uint32_t l_minus_1 = 0;
234
+ uint32_t x = (uint32_t) d_minus_1;
235
+ uint32_t y = d_minus_1 >> 32;
236
+ if (y != 0) {
237
+ l_minus_1 += 32;
238
+ x = y;
239
+ }
240
+ y = x >> 16;
241
+ if (y != 0) {
242
+ l_minus_1 += 16;
243
+ x = y;
244
+ }
245
+ y = x >> 8;
246
+ if (y != 0) {
247
+ l_minus_1 += 8;
248
+ x = y;
249
+ }
250
+ y = x >> 4;
251
+ if (y != 0) {
252
+ l_minus_1 += 4;
253
+ x = y;
254
+ }
255
+ y = x >> 2;
256
+ if (y != 0) {
257
+ l_minus_1 += 2;
258
+ x = y;
259
+ }
260
+ if ((x & 2) != 0) {
261
+ l_minus_1 += 1;
262
+ }
263
+ const uint32_t nlz_d = (l_minus_1 ^ UINT32_C(0x3F)) - d_is_power_of_2;
264
+ #endif
265
+ uint64_t u_hi = (UINT64_C(2) << (uint32_t) l_minus_1) - d;
266
+
267
+ /* Division of 128-bit number u_hi:UINT64_C(0) by 64-bit number d, 64-bit quotient output q */
268
+ #if defined(__GNUC__) && defined(__x86_64__) && FXDIV_USE_INLINE_ASSEMBLY
269
+ uint64_t q;
270
+ __asm__("DIVQ %[d]"
271
+ : "=a" (q), "+d" (u_hi)
272
+ : [d] "r" (d), "a" (UINT64_C(0))
273
+ : "cc");
274
+ #elif 0 && defined(__GNUC__) && defined(__SIZEOF_INT128__)
275
+ /* GCC, Clang, and Intel Compiler fail to inline optimized implementation and call into support library for 128-bit division */
276
+ const uint64_t q = (uint64_t) (((unsigned __int128) u_hi << 64) / ((unsigned __int128) d));
277
+ #elif (defined(_MSC_VER) && _MSC_VER >= 1920) && !defined(__clang__) && !defined(__INTEL_COMPILER) && defined(_M_X64)
278
+ unsigned __int64 remainder;
279
+ const uint64_t q = (uint64_t) _udiv128((unsigned __int64) u_hi, 0, (unsigned __int64) d, &remainder);
280
+ #else
281
+ /* Implementation based on code from Hacker's delight */
282
+
283
+ /* Normalize divisor and shift divident left */
284
+ d <<= nlz_d;
285
+ u_hi <<= nlz_d;
286
+ /* Break divisor up into two 32-bit digits */
287
+ const uint64_t d_hi = (uint32_t) (d >> 32);
288
+ const uint32_t d_lo = (uint32_t) d;
289
+
290
+ /* Compute the first quotient digit, q1 */
291
+ uint64_t q1 = u_hi / d_hi;
292
+ uint64_t r1 = u_hi - q1 * d_hi;
293
+
294
+ while ((q1 >> 32) != 0 || fxdiv_mulext_uint32_t((uint32_t) q1, d_lo) > (r1 << 32)) {
295
+ q1 -= 1;
296
+ r1 += d_hi;
297
+ if ((r1 >> 32) != 0) {
298
+ break;
299
+ }
300
+ }
301
+
302
+ /* Multiply and subtract. */
303
+ u_hi = (u_hi << 32) - q1 * d;
304
+
305
+ /* Compute the second quotient digit, q0 */
306
+ uint64_t q0 = u_hi / d_hi;
307
+ uint64_t r0 = u_hi - q0 * d_hi;
308
+
309
+ while ((q0 >> 32) != 0 || fxdiv_mulext_uint32_t((uint32_t) q0, d_lo) > (r0 << 32)) {
310
+ q0 -= 1;
311
+ r0 += d_hi;
312
+ if ((r0 >> 32) != 0) {
313
+ break;
314
+ }
315
+ }
316
+ const uint64_t q = (q1 << 32) | (uint32_t) q0;
317
+ #endif
318
+ result.m = q + UINT64_C(1);
319
+ result.s1 = 1;
320
+ result.s2 = (uint8_t) l_minus_1;
321
+ }
322
+ return result;
323
+ }
324
+
325
+ static inline struct fxdiv_divisor_size_t fxdiv_init_size_t(size_t d) {
326
+ #if SIZE_MAX == UINT32_MAX
327
+ const struct fxdiv_divisor_uint32_t uint_result = fxdiv_init_uint32_t((uint32_t) d);
328
+ #elif SIZE_MAX == UINT64_MAX
329
+ const struct fxdiv_divisor_uint64_t uint_result = fxdiv_init_uint64_t((uint64_t) d);
330
+ #else
331
+ #error Unsupported platform
332
+ #endif
333
+ struct fxdiv_divisor_size_t size_result = {
334
+ (size_t) uint_result.value,
335
+ (size_t) uint_result.m,
336
+ uint_result.s1,
337
+ uint_result.s2
338
+ };
339
+ return size_result;
340
+ }
341
+
342
+ static inline uint32_t fxdiv_quotient_uint32_t(uint32_t n, const struct fxdiv_divisor_uint32_t divisor) {
343
+ const uint32_t t = fxdiv_mulhi_uint32_t(n, divisor.m);
344
+ return (t + ((n - t) >> divisor.s1)) >> divisor.s2;
345
+ }
346
+
347
+ static inline uint64_t fxdiv_quotient_uint64_t(uint64_t n, const struct fxdiv_divisor_uint64_t divisor) {
348
+ const uint64_t t = fxdiv_mulhi_uint64_t(n, divisor.m);
349
+ return (t + ((n - t) >> divisor.s1)) >> divisor.s2;
350
+ }
351
+
352
+ static inline size_t fxdiv_quotient_size_t(size_t n, const struct fxdiv_divisor_size_t divisor) {
353
+ #if SIZE_MAX == UINT32_MAX
354
+ const struct fxdiv_divisor_uint32_t uint32_divisor = {
355
+ (uint32_t) divisor.value,
356
+ (uint32_t) divisor.m,
357
+ divisor.s1,
358
+ divisor.s2
359
+ };
360
+ return fxdiv_quotient_uint32_t((uint32_t) n, uint32_divisor);
361
+ #elif SIZE_MAX == UINT64_MAX
362
+ const struct fxdiv_divisor_uint64_t uint64_divisor = {
363
+ (uint64_t) divisor.value,
364
+ (uint64_t) divisor.m,
365
+ divisor.s1,
366
+ divisor.s2
367
+ };
368
+ return fxdiv_quotient_uint64_t((uint64_t) n, uint64_divisor);
369
+ #else
370
+ #error Unsupported platform
371
+ #endif
372
+ }
373
+
374
+ static inline uint32_t fxdiv_remainder_uint32_t(uint32_t n, const struct fxdiv_divisor_uint32_t divisor) {
375
+ const uint32_t quotient = fxdiv_quotient_uint32_t(n, divisor);
376
+ return n - quotient * divisor.value;
377
+ }
378
+
379
+ static inline uint64_t fxdiv_remainder_uint64_t(uint64_t n, const struct fxdiv_divisor_uint64_t divisor) {
380
+ const uint64_t quotient = fxdiv_quotient_uint64_t(n, divisor);
381
+ return n - quotient * divisor.value;
382
+ }
383
+
384
+ static inline size_t fxdiv_remainder_size_t(size_t n, const struct fxdiv_divisor_size_t divisor) {
385
+ const size_t quotient = fxdiv_quotient_size_t(n, divisor);
386
+ return n - quotient * divisor.value;
387
+ }
388
+
389
+ static inline uint32_t fxdiv_round_down_uint32_t(uint32_t n, const struct fxdiv_divisor_uint32_t granularity) {
390
+ const uint32_t quotient = fxdiv_quotient_uint32_t(n, granularity);
391
+ return quotient * granularity.value;
392
+ }
393
+
394
+ static inline uint64_t fxdiv_round_down_uint64_t(uint64_t n, const struct fxdiv_divisor_uint64_t granularity) {
395
+ const uint64_t quotient = fxdiv_quotient_uint64_t(n, granularity);
396
+ return quotient * granularity.value;
397
+ }
398
+
399
+ static inline size_t fxdiv_round_down_size_t(size_t n, const struct fxdiv_divisor_size_t granularity) {
400
+ const size_t quotient = fxdiv_quotient_size_t(n, granularity);
401
+ return quotient * granularity.value;
402
+ }
403
+
404
+ static inline struct fxdiv_result_uint32_t fxdiv_divide_uint32_t(uint32_t n, const struct fxdiv_divisor_uint32_t divisor) {
405
+ const uint32_t quotient = fxdiv_quotient_uint32_t(n, divisor);
406
+ const uint32_t remainder = n - quotient * divisor.value;
407
+ struct fxdiv_result_uint32_t result = { quotient, remainder };
408
+ return result;
409
+ }
410
+
411
+ static inline struct fxdiv_result_uint64_t fxdiv_divide_uint64_t(uint64_t n, const struct fxdiv_divisor_uint64_t divisor) {
412
+ const uint64_t quotient = fxdiv_quotient_uint64_t(n, divisor);
413
+ const uint64_t remainder = n - quotient * divisor.value;
414
+ struct fxdiv_result_uint64_t result = { quotient, remainder };
415
+ return result;
416
+ }
417
+
418
+ static inline struct fxdiv_result_size_t fxdiv_divide_size_t(size_t n, const struct fxdiv_divisor_size_t divisor) {
419
+ const size_t quotient = fxdiv_quotient_size_t(n, divisor);
420
+ const size_t remainder = n - quotient * divisor.value;
421
+ struct fxdiv_result_size_t result = { quotient, remainder };
422
+ return result;
423
+ }
424
+
425
+ #endif /* FXDIV_H */
deps/exla/cache/xla_extension/include/_virtual_includes/cpuinfo/cpuinfo.h ADDED
@@ -0,0 +1,2331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #ifndef CPUINFO_H
3
+ #define CPUINFO_H
4
+
5
+ #ifndef __cplusplus
6
+ #include <stdbool.h>
7
+ #endif
8
+
9
+ #ifdef __APPLE__
10
+ #include <TargetConditionals.h>
11
+ #endif
12
+
13
+ #include <stdint.h>
14
+
15
+ /* Identify architecture and define corresponding macro */
16
+
17
+ #if defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || defined(_M_IX86)
18
+ #define CPUINFO_ARCH_X86 1
19
+ #endif
20
+
21
+ #if defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64)
22
+ #define CPUINFO_ARCH_X86_64 1
23
+ #endif
24
+
25
+ #if defined(__arm__) || defined(_M_ARM)
26
+ #define CPUINFO_ARCH_ARM 1
27
+ #endif
28
+
29
+ #if defined(__aarch64__) || defined(_M_ARM64)
30
+ #define CPUINFO_ARCH_ARM64 1
31
+ #endif
32
+
33
+ #if defined(__PPC64__) || defined(__powerpc64__) || defined(_ARCH_PPC64)
34
+ #define CPUINFO_ARCH_PPC64 1
35
+ #endif
36
+
37
+ #if defined(__asmjs__)
38
+ #define CPUINFO_ARCH_ASMJS 1
39
+ #endif
40
+
41
+ #if defined(__wasm__)
42
+ #if defined(__wasm_simd128__)
43
+ #define CPUINFO_ARCH_WASMSIMD 1
44
+ #else
45
+ #define CPUINFO_ARCH_WASM 1
46
+ #endif
47
+ #endif
48
+
49
+ #if defined(__riscv)
50
+ #if (__riscv_xlen == 32)
51
+ #define CPUINFO_ARCH_RISCV32 1
52
+ #elif (__riscv_xlen == 64)
53
+ #define CPUINFO_ARCH_RISCV64 1
54
+ #endif
55
+ #endif
56
+
57
+ /* Define other architecture-specific macros as 0 */
58
+
59
+ #ifndef CPUINFO_ARCH_X86
60
+ #define CPUINFO_ARCH_X86 0
61
+ #endif
62
+
63
+ #ifndef CPUINFO_ARCH_X86_64
64
+ #define CPUINFO_ARCH_X86_64 0
65
+ #endif
66
+
67
+ #ifndef CPUINFO_ARCH_ARM
68
+ #define CPUINFO_ARCH_ARM 0
69
+ #endif
70
+
71
+ #ifndef CPUINFO_ARCH_ARM64
72
+ #define CPUINFO_ARCH_ARM64 0
73
+ #endif
74
+
75
+ #ifndef CPUINFO_ARCH_PPC64
76
+ #define CPUINFO_ARCH_PPC64 0
77
+ #endif
78
+
79
+ #ifndef CPUINFO_ARCH_ASMJS
80
+ #define CPUINFO_ARCH_ASMJS 0
81
+ #endif
82
+
83
+ #ifndef CPUINFO_ARCH_WASM
84
+ #define CPUINFO_ARCH_WASM 0
85
+ #endif
86
+
87
+ #ifndef CPUINFO_ARCH_WASMSIMD
88
+ #define CPUINFO_ARCH_WASMSIMD 0
89
+ #endif
90
+
91
+ #ifndef CPUINFO_ARCH_RISCV32
92
+ #define CPUINFO_ARCH_RISCV32 0
93
+ #endif
94
+
95
+ #ifndef CPUINFO_ARCH_RISCV64
96
+ #define CPUINFO_ARCH_RISCV64 0
97
+ #endif
98
+
99
+ #if CPUINFO_ARCH_X86 && defined(_MSC_VER)
100
+ #define CPUINFO_ABI __cdecl
101
+ #elif CPUINFO_ARCH_X86 && defined(__GNUC__)
102
+ #define CPUINFO_ABI __attribute__((__cdecl__))
103
+ #else
104
+ #define CPUINFO_ABI
105
+ #endif
106
+
107
+ #define CPUINFO_CACHE_UNIFIED 0x00000001
108
+ #define CPUINFO_CACHE_INCLUSIVE 0x00000002
109
+ #define CPUINFO_CACHE_COMPLEX_INDEXING 0x00000004
110
+
111
+ struct cpuinfo_cache {
112
+ /** Cache size in bytes */
113
+ uint32_t size;
114
+ /** Number of ways of associativity */
115
+ uint32_t associativity;
116
+ /** Number of sets */
117
+ uint32_t sets;
118
+ /** Number of partitions */
119
+ uint32_t partitions;
120
+ /** Line size in bytes */
121
+ uint32_t line_size;
122
+ /**
123
+ * Binary characteristics of the cache (unified cache, inclusive cache,
124
+ * cache with complex indexing).
125
+ *
126
+ * @see CPUINFO_CACHE_UNIFIED, CPUINFO_CACHE_INCLUSIVE,
127
+ * CPUINFO_CACHE_COMPLEX_INDEXING
128
+ */
129
+ uint32_t flags;
130
+ /** Index of the first logical processor that shares this cache */
131
+ uint32_t processor_start;
132
+ /** Number of logical processors that share this cache */
133
+ uint32_t processor_count;
134
+ };
135
+
136
+ struct cpuinfo_trace_cache {
137
+ uint32_t uops;
138
+ uint32_t associativity;
139
+ };
140
+
141
+ #define CPUINFO_PAGE_SIZE_4KB 0x1000
142
+ #define CPUINFO_PAGE_SIZE_1MB 0x100000
143
+ #define CPUINFO_PAGE_SIZE_2MB 0x200000
144
+ #define CPUINFO_PAGE_SIZE_4MB 0x400000
145
+ #define CPUINFO_PAGE_SIZE_16MB 0x1000000
146
+ #define CPUINFO_PAGE_SIZE_1GB 0x40000000
147
+
148
+ struct cpuinfo_tlb {
149
+ uint32_t entries;
150
+ uint32_t associativity;
151
+ uint64_t pages;
152
+ };
153
+
154
+ /** Vendor of processor core design */
155
+ enum cpuinfo_vendor {
156
+ /** Processor vendor is not known to the library, or the library failed
157
+ to get vendor information from the OS. */
158
+ cpuinfo_vendor_unknown = 0,
159
+
160
+ /* Active vendors of modern CPUs */
161
+
162
+ /**
163
+ * Intel Corporation. Vendor of x86, x86-64, IA64, and ARM processor
164
+ * microarchitectures.
165
+ *
166
+ * Sold its ARM design subsidiary in 2006. The last ARM processor design
167
+ * was released in 2004.
168
+ */
169
+ cpuinfo_vendor_intel = 1,
170
+ /** Advanced Micro Devices, Inc. Vendor of x86 and x86-64 processor
171
+ microarchitectures. */
172
+ cpuinfo_vendor_amd = 2,
173
+ /** ARM Holdings plc. Vendor of ARM and ARM64 processor
174
+ microarchitectures. */
175
+ cpuinfo_vendor_arm = 3,
176
+ /** Qualcomm Incorporated. Vendor of ARM and ARM64 processor
177
+ microarchitectures. */
178
+ cpuinfo_vendor_qualcomm = 4,
179
+ /** Apple Inc. Vendor of ARM and ARM64 processor microarchitectures. */
180
+ cpuinfo_vendor_apple = 5,
181
+ /** Samsung Electronics Co., Ltd. Vendir if ARM64 processor
182
+ microarchitectures. */
183
+ cpuinfo_vendor_samsung = 6,
184
+ /** Nvidia Corporation. Vendor of ARM64-compatible processor
185
+ microarchitectures. */
186
+ cpuinfo_vendor_nvidia = 7,
187
+ /** MIPS Technologies, Inc. Vendor of MIPS processor microarchitectures.
188
+ */
189
+ cpuinfo_vendor_mips = 8,
190
+ /** International Business Machines Corporation. Vendor of PowerPC
191
+ processor microarchitectures. */
192
+ cpuinfo_vendor_ibm = 9,
193
+ /** Ingenic Semiconductor. Vendor of MIPS processor microarchitectures.
194
+ */
195
+ cpuinfo_vendor_ingenic = 10,
196
+ /**
197
+ * VIA Technologies, Inc. Vendor of x86 and x86-64 processor
198
+ * microarchitectures.
199
+ *
200
+ * Processors are designed by Centaur Technology, a subsidiary of VIA
201
+ * Technologies.
202
+ */
203
+ cpuinfo_vendor_via = 11,
204
+ /** Cavium, Inc. Vendor of ARM64 processor microarchitectures. */
205
+ cpuinfo_vendor_cavium = 12,
206
+ /** Broadcom, Inc. Vendor of ARM processor microarchitectures. */
207
+ cpuinfo_vendor_broadcom = 13,
208
+ /** Applied Micro Circuits Corporation (APM). Vendor of ARM64 processor
209
+ microarchitectures. */
210
+ cpuinfo_vendor_apm = 14,
211
+ /**
212
+ * Huawei Technologies Co., Ltd. Vendor of ARM64 processor
213
+ * microarchitectures.
214
+ *
215
+ * Processors are designed by HiSilicon, a subsidiary of Huawei.
216
+ */
217
+ cpuinfo_vendor_huawei = 15,
218
+ /**
219
+ * Hygon (Chengdu Haiguang Integrated Circuit Design Co., Ltd), Vendor
220
+ * of x86-64 processor microarchitectures.
221
+ *
222
+ * Processors are variants of AMD cores.
223
+ */
224
+ cpuinfo_vendor_hygon = 16,
225
+ /** SiFive, Inc. Vendor of RISC-V processor microarchitectures. */
226
+ cpuinfo_vendor_sifive = 17,
227
+
228
+ /* Active vendors of embedded CPUs */
229
+
230
+ /** Texas Instruments Inc. Vendor of ARM processor microarchitectures.
231
+ */
232
+ cpuinfo_vendor_texas_instruments = 30,
233
+ /** Marvell Technology Group Ltd. Vendor of ARM processor
234
+ * microarchitectures.
235
+ */
236
+ cpuinfo_vendor_marvell = 31,
237
+ /** RDC Semiconductor Co., Ltd. Vendor of x86 processor
238
+ microarchitectures. */
239
+ cpuinfo_vendor_rdc = 32,
240
+ /** DM&P Electronics Inc. Vendor of x86 processor microarchitectures. */
241
+ cpuinfo_vendor_dmp = 33,
242
+ /** Motorola, Inc. Vendor of PowerPC and ARM processor
243
+ microarchitectures. */
244
+ cpuinfo_vendor_motorola = 34,
245
+
246
+ /* Defunct CPU vendors */
247
+
248
+ /**
249
+ * Transmeta Corporation. Vendor of x86 processor microarchitectures.
250
+ *
251
+ * Now defunct. The last processor design was released in 2004.
252
+ * Transmeta processors implemented VLIW ISA and used binary translation
253
+ * to execute x86 code.
254
+ */
255
+ cpuinfo_vendor_transmeta = 50,
256
+ /**
257
+ * Cyrix Corporation. Vendor of x86 processor microarchitectures.
258
+ *
259
+ * Now defunct. The last processor design was released in 1996.
260
+ */
261
+ cpuinfo_vendor_cyrix = 51,
262
+ /**
263
+ * Rise Technology. Vendor of x86 processor microarchitectures.
264
+ *
265
+ * Now defunct. The last processor design was released in 1999.
266
+ */
267
+ cpuinfo_vendor_rise = 52,
268
+ /**
269
+ * National Semiconductor. Vendor of x86 processor microarchitectures.
270
+ *
271
+ * Sold its x86 design subsidiary in 1999. The last processor design was
272
+ * released in 1998.
273
+ */
274
+ cpuinfo_vendor_nsc = 53,
275
+ /**
276
+ * Silicon Integrated Systems. Vendor of x86 processor
277
+ * microarchitectures.
278
+ *
279
+ * Sold its x86 design subsidiary in 2001. The last processor design was
280
+ * released in 2001.
281
+ */
282
+ cpuinfo_vendor_sis = 54,
283
+ /**
284
+ * NexGen. Vendor of x86 processor microarchitectures.
285
+ *
286
+ * Now defunct. The last processor design was released in 1994.
287
+ * NexGen designed the first x86 microarchitecture which decomposed x86
288
+ * instructions into simple microoperations.
289
+ */
290
+ cpuinfo_vendor_nexgen = 55,
291
+ /**
292
+ * United Microelectronics Corporation. Vendor of x86 processor
293
+ * microarchitectures.
294
+ *
295
+ * Ceased x86 in the early 1990s. The last processor design was released
296
+ * in 1991. Designed U5C and U5D processors. Both are 486 level.
297
+ */
298
+ cpuinfo_vendor_umc = 56,
299
+ /**
300
+ * Digital Equipment Corporation. Vendor of ARM processor
301
+ * microarchitecture.
302
+ *
303
+ * Sold its ARM designs in 1997. The last processor design was released
304
+ * in 1997.
305
+ */
306
+ cpuinfo_vendor_dec = 57,
307
+ };
308
+
309
+ /**
310
+ * Processor microarchitecture
311
+ *
312
+ * Processors with different microarchitectures often have different instruction
313
+ * performance characteristics, and may have dramatically different pipeline
314
+ * organization.
315
+ */
316
+ enum cpuinfo_uarch {
317
+ /** Microarchitecture is unknown, or the library failed to get
318
+ information about the microarchitecture from OS */
319
+ cpuinfo_uarch_unknown = 0,
320
+
321
+ /** Pentium and Pentium MMX microarchitecture. */
322
+ cpuinfo_uarch_p5 = 0x00100100,
323
+ /** Intel Quark microarchitecture. */
324
+ cpuinfo_uarch_quark = 0x00100101,
325
+
326
+ /** Pentium Pro, Pentium II, and Pentium III. */
327
+ cpuinfo_uarch_p6 = 0x00100200,
328
+ /** Pentium M. */
329
+ cpuinfo_uarch_dothan = 0x00100201,
330
+ /** Intel Core microarchitecture. */
331
+ cpuinfo_uarch_yonah = 0x00100202,
332
+ /** Intel Core 2 microarchitecture on 65 nm process. */
333
+ cpuinfo_uarch_conroe = 0x00100203,
334
+ /** Intel Core 2 microarchitecture on 45 nm process. */
335
+ cpuinfo_uarch_penryn = 0x00100204,
336
+ /** Intel Nehalem and Westmere microarchitectures (Core i3/i5/i7 1st
337
+ gen). */
338
+ cpuinfo_uarch_nehalem = 0x00100205,
339
+ /** Intel Sandy Bridge microarchitecture (Core i3/i5/i7 2nd gen). */
340
+ cpuinfo_uarch_sandy_bridge = 0x00100206,
341
+ /** Intel Ivy Bridge microarchitecture (Core i3/i5/i7 3rd gen). */
342
+ cpuinfo_uarch_ivy_bridge = 0x00100207,
343
+ /** Intel Haswell microarchitecture (Core i3/i5/i7 4th gen). */
344
+ cpuinfo_uarch_haswell = 0x00100208,
345
+ /** Intel Broadwell microarchitecture. */
346
+ cpuinfo_uarch_broadwell = 0x00100209,
347
+ /** Intel Sky Lake microarchitecture (14 nm, including
348
+ Kaby/Coffee/Whiskey/Amber/Comet/Cascade/Cooper Lake). */
349
+ cpuinfo_uarch_sky_lake = 0x0010020A,
350
+ /** DEPRECATED (Intel Kaby Lake microarchitecture). */
351
+ cpuinfo_uarch_kaby_lake = 0x0010020A,
352
+ /** Intel Palm Cove microarchitecture (10 nm, Cannon Lake). */
353
+ cpuinfo_uarch_palm_cove = 0x0010020B,
354
+ /** Intel Sunny Cove microarchitecture (10 nm, Ice Lake). */
355
+ cpuinfo_uarch_sunny_cove = 0x0010020C,
356
+
357
+ /** Pentium 4 with Willamette, Northwood, or Foster cores. */
358
+ cpuinfo_uarch_willamette = 0x00100300,
359
+ /** Pentium 4 with Prescott and later cores. */
360
+ cpuinfo_uarch_prescott = 0x00100301,
361
+
362
+ /** Intel Atom on 45 nm process. */
363
+ cpuinfo_uarch_bonnell = 0x00100400,
364
+ /** Intel Atom on 32 nm process. */
365
+ cpuinfo_uarch_saltwell = 0x00100401,
366
+ /** Intel Silvermont microarchitecture (22 nm out-of-order Atom). */
367
+ cpuinfo_uarch_silvermont = 0x00100402,
368
+ /** Intel Airmont microarchitecture (14 nm out-of-order Atom). */
369
+ cpuinfo_uarch_airmont = 0x00100403,
370
+ /** Intel Goldmont microarchitecture (Denverton, Apollo Lake). */
371
+ cpuinfo_uarch_goldmont = 0x00100404,
372
+ /** Intel Goldmont Plus microarchitecture (Gemini Lake). */
373
+ cpuinfo_uarch_goldmont_plus = 0x00100405,
374
+
375
+ /** Intel Knights Ferry HPC boards. */
376
+ cpuinfo_uarch_knights_ferry = 0x00100500,
377
+ /** Intel Knights Corner HPC boards (aka Xeon Phi). */
378
+ cpuinfo_uarch_knights_corner = 0x00100501,
379
+ /** Intel Knights Landing microarchitecture (second-gen MIC). */
380
+ cpuinfo_uarch_knights_landing = 0x00100502,
381
+ /** Intel Knights Hill microarchitecture (third-gen MIC). */
382
+ cpuinfo_uarch_knights_hill = 0x00100503,
383
+ /** Intel Knights Mill Xeon Phi. */
384
+ cpuinfo_uarch_knights_mill = 0x00100504,
385
+
386
+ /** Intel/Marvell XScale series. */
387
+ cpuinfo_uarch_xscale = 0x00100600,
388
+
389
+ /** AMD K5. */
390
+ cpuinfo_uarch_k5 = 0x00200100,
391
+ /** AMD K6 and alike. */
392
+ cpuinfo_uarch_k6 = 0x00200101,
393
+ /** AMD Athlon and Duron. */
394
+ cpuinfo_uarch_k7 = 0x00200102,
395
+ /** AMD Athlon 64, Opteron 64. */
396
+ cpuinfo_uarch_k8 = 0x00200103,
397
+ /** AMD Family 10h (Barcelona, Istambul, Magny-Cours). */
398
+ cpuinfo_uarch_k10 = 0x00200104,
399
+ /**
400
+ * AMD Bulldozer microarchitecture
401
+ * Zambezi FX-series CPUs, Zurich, Valencia and Interlagos Opteron CPUs.
402
+ */
403
+ cpuinfo_uarch_bulldozer = 0x00200105,
404
+ /**
405
+ * AMD Piledriver microarchitecture
406
+ * Vishera FX-series CPUs, Trinity and Richland APUs, Delhi, Seoul, Abu
407
+ * Dhabi Opteron CPUs.
408
+ */
409
+ cpuinfo_uarch_piledriver = 0x00200106,
410
+ /** AMD Steamroller microarchitecture (Kaveri APUs). */
411
+ cpuinfo_uarch_steamroller = 0x00200107,
412
+ /** AMD Excavator microarchitecture (Carizzo APUs). */
413
+ cpuinfo_uarch_excavator = 0x00200108,
414
+ /** AMD Zen microarchitecture (12/14 nm Ryzen and EPYC CPUs). */
415
+ cpuinfo_uarch_zen = 0x00200109,
416
+ /** AMD Zen 2 microarchitecture (7 nm Ryzen and EPYC CPUs). */
417
+ cpuinfo_uarch_zen2 = 0x0020010A,
418
+ /** AMD Zen 3 microarchitecture. */
419
+ cpuinfo_uarch_zen3 = 0x0020010B,
420
+ /** AMD Zen 4 microarchitecture. */
421
+ cpuinfo_uarch_zen4 = 0x0020010C,
422
+ /** AMD Zen 5 microarchitecture. */
423
+ cpuinfo_uarch_zen5 = 0x0020010D,
424
+
425
+ /** NSC Geode and AMD Geode GX and LX. */
426
+ cpuinfo_uarch_geode = 0x00200200,
427
+ /** AMD Bobcat mobile microarchitecture. */
428
+ cpuinfo_uarch_bobcat = 0x00200201,
429
+ /** AMD Jaguar mobile microarchitecture. */
430
+ cpuinfo_uarch_jaguar = 0x00200202,
431
+ /** AMD Puma mobile microarchitecture. */
432
+ cpuinfo_uarch_puma = 0x00200203,
433
+
434
+ /** ARM7 series. */
435
+ cpuinfo_uarch_arm7 = 0x00300100,
436
+ /** ARM9 series. */
437
+ cpuinfo_uarch_arm9 = 0x00300101,
438
+ /** ARM 1136, ARM 1156, ARM 1176, or ARM 11MPCore. */
439
+ cpuinfo_uarch_arm11 = 0x00300102,
440
+
441
+ /** ARM Cortex-A5. */
442
+ cpuinfo_uarch_cortex_a5 = 0x00300205,
443
+ /** ARM Cortex-A7. */
444
+ cpuinfo_uarch_cortex_a7 = 0x00300207,
445
+ /** ARM Cortex-A8. */
446
+ cpuinfo_uarch_cortex_a8 = 0x00300208,
447
+ /** ARM Cortex-A9. */
448
+ cpuinfo_uarch_cortex_a9 = 0x00300209,
449
+ /** ARM Cortex-A12. */
450
+ cpuinfo_uarch_cortex_a12 = 0x00300212,
451
+ /** ARM Cortex-A15. */
452
+ cpuinfo_uarch_cortex_a15 = 0x00300215,
453
+ /** ARM Cortex-A17. */
454
+ cpuinfo_uarch_cortex_a17 = 0x00300217,
455
+
456
+ /** ARM Cortex-A32. */
457
+ cpuinfo_uarch_cortex_a32 = 0x00300332,
458
+ /** ARM Cortex-A35. */
459
+ cpuinfo_uarch_cortex_a35 = 0x00300335,
460
+ /** ARM Cortex-A53. */
461
+ cpuinfo_uarch_cortex_a53 = 0x00300353,
462
+ /** ARM Cortex-A55 revision 0 (restricted dual-issue capabilities
463
+ compared to revision 1+). */
464
+ cpuinfo_uarch_cortex_a55r0 = 0x00300354,
465
+ /** ARM Cortex-A55. */
466
+ cpuinfo_uarch_cortex_a55 = 0x00300355,
467
+ /** ARM Cortex-A57. */
468
+ cpuinfo_uarch_cortex_a57 = 0x00300357,
469
+ /** ARM Cortex-A65. */
470
+ cpuinfo_uarch_cortex_a65 = 0x00300365,
471
+ /** ARM Cortex-A72. */
472
+ cpuinfo_uarch_cortex_a72 = 0x00300372,
473
+ /** ARM Cortex-A73. */
474
+ cpuinfo_uarch_cortex_a73 = 0x00300373,
475
+ /** ARM Cortex-A75. */
476
+ cpuinfo_uarch_cortex_a75 = 0x00300375,
477
+ /** ARM Cortex-A76. */
478
+ cpuinfo_uarch_cortex_a76 = 0x00300376,
479
+ /** ARM Cortex-A77. */
480
+ cpuinfo_uarch_cortex_a77 = 0x00300377,
481
+ /** ARM Cortex-A78. */
482
+ cpuinfo_uarch_cortex_a78 = 0x00300378,
483
+
484
+ /** ARM Neoverse N1. */
485
+ cpuinfo_uarch_neoverse_n1 = 0x00300400,
486
+ /** ARM Neoverse E1. */
487
+ cpuinfo_uarch_neoverse_e1 = 0x00300401,
488
+ /** ARM Neoverse V1. */
489
+ cpuinfo_uarch_neoverse_v1 = 0x00300402,
490
+ /** ARM Neoverse N2. */
491
+ cpuinfo_uarch_neoverse_n2 = 0x00300403,
492
+ /** ARM Neoverse V2. */
493
+ cpuinfo_uarch_neoverse_v2 = 0x00300404,
494
+
495
+ /** ARM Cortex-X1. */
496
+ cpuinfo_uarch_cortex_x1 = 0x00300501,
497
+ /** ARM Cortex-X2. */
498
+ cpuinfo_uarch_cortex_x2 = 0x00300502,
499
+ /** ARM Cortex-X3. */
500
+ cpuinfo_uarch_cortex_x3 = 0x00300503,
501
+ /** ARM Cortex-X4. */
502
+ cpuinfo_uarch_cortex_x4 = 0x00300504,
503
+
504
+ /** ARM Cortex-A510. */
505
+ cpuinfo_uarch_cortex_a510 = 0x00300551,
506
+ /** ARM Cortex-A520. */
507
+ cpuinfo_uarch_cortex_a520 = 0x00300552,
508
+ /** ARM Cortex-A710. */
509
+ cpuinfo_uarch_cortex_a710 = 0x00300571,
510
+ /** ARM Cortex-A715. */
511
+ cpuinfo_uarch_cortex_a715 = 0x00300572,
512
+ /** ARM Cortex-A720. */
513
+ cpuinfo_uarch_cortex_a720 = 0x00300573,
514
+
515
+ /** Qualcomm Scorpion. */
516
+ cpuinfo_uarch_scorpion = 0x00400100,
517
+ /** Qualcomm Krait. */
518
+ cpuinfo_uarch_krait = 0x00400101,
519
+ /** Qualcomm Kryo. */
520
+ cpuinfo_uarch_kryo = 0x00400102,
521
+ /** Qualcomm Falkor. */
522
+ cpuinfo_uarch_falkor = 0x00400103,
523
+ /** Qualcomm Saphira. */
524
+ cpuinfo_uarch_saphira = 0x00400104,
525
+ /** Qualcomm Oryon. */
526
+ cpuinfo_uarch_oryon = 0x00400105,
527
+
528
+ /** Nvidia Denver. */
529
+ cpuinfo_uarch_denver = 0x00500100,
530
+ /** Nvidia Denver 2. */
531
+ cpuinfo_uarch_denver2 = 0x00500101,
532
+ /** Nvidia Carmel. */
533
+ cpuinfo_uarch_carmel = 0x00500102,
534
+
535
+ /** Samsung Exynos M1 (Exynos 8890 big cores). */
536
+ cpuinfo_uarch_exynos_m1 = 0x00600100,
537
+ /** Samsung Exynos M2 (Exynos 8895 big cores). */
538
+ cpuinfo_uarch_exynos_m2 = 0x00600101,
539
+ /** Samsung Exynos M3 (Exynos 9810 big cores). */
540
+ cpuinfo_uarch_exynos_m3 = 0x00600102,
541
+ /** Samsung Exynos M4 (Exynos 9820 big cores). */
542
+ cpuinfo_uarch_exynos_m4 = 0x00600103,
543
+ /** Samsung Exynos M5 (Exynos 9830 big cores). */
544
+ cpuinfo_uarch_exynos_m5 = 0x00600104,
545
+
546
+ /* Deprecated synonym for Cortex-A76 */
547
+ cpuinfo_uarch_cortex_a76ae = 0x00300376,
548
+ /* Deprecated names for Exynos. */
549
+ cpuinfo_uarch_mongoose_m1 = 0x00600100,
550
+ cpuinfo_uarch_mongoose_m2 = 0x00600101,
551
+ cpuinfo_uarch_meerkat_m3 = 0x00600102,
552
+ cpuinfo_uarch_meerkat_m4 = 0x00600103,
553
+
554
+ /** Apple A6 and A6X processors. */
555
+ cpuinfo_uarch_swift = 0x00700100,
556
+ /** Apple A7 processor. */
557
+ cpuinfo_uarch_cyclone = 0x00700101,
558
+ /** Apple A8 and A8X processor. */
559
+ cpuinfo_uarch_typhoon = 0x00700102,
560
+ /** Apple A9 and A9X processor. */
561
+ cpuinfo_uarch_twister = 0x00700103,
562
+ /** Apple A10 and A10X processor. */
563
+ cpuinfo_uarch_hurricane = 0x00700104,
564
+ /** Apple A11 processor (big cores). */
565
+ cpuinfo_uarch_monsoon = 0x00700105,
566
+ /** Apple A11 processor (little cores). */
567
+ cpuinfo_uarch_mistral = 0x00700106,
568
+ /** Apple A12 processor (big cores). */
569
+ cpuinfo_uarch_vortex = 0x00700107,
570
+ /** Apple A12 processor (little cores). */
571
+ cpuinfo_uarch_tempest = 0x00700108,
572
+ /** Apple A13 processor (big cores). */
573
+ cpuinfo_uarch_lightning = 0x00700109,
574
+ /** Apple A13 processor (little cores). */
575
+ cpuinfo_uarch_thunder = 0x0070010A,
576
+ /** Apple A14 / M1 processor (big cores). */
577
+ cpuinfo_uarch_firestorm = 0x0070010B,
578
+ /** Apple A14 / M1 processor (little cores). */
579
+ cpuinfo_uarch_icestorm = 0x0070010C,
580
+ /** Apple A15 / M2 processor (big cores). */
581
+ cpuinfo_uarch_avalanche = 0x0070010D,
582
+ /** Apple A15 / M2 processor (little cores). */
583
+ cpuinfo_uarch_blizzard = 0x0070010E,
584
+
585
+ /** Cavium ThunderX. */
586
+ cpuinfo_uarch_thunderx = 0x00800100,
587
+ /** Cavium ThunderX2 (originally Broadcom Vulkan). */
588
+ cpuinfo_uarch_thunderx2 = 0x00800200,
589
+
590
+ /** Marvell PJ4. */
591
+ cpuinfo_uarch_pj4 = 0x00900100,
592
+
593
+ /** Broadcom Brahma B15. */
594
+ cpuinfo_uarch_brahma_b15 = 0x00A00100,
595
+ /** Broadcom Brahma B53. */
596
+ cpuinfo_uarch_brahma_b53 = 0x00A00101,
597
+
598
+ /** Applied Micro X-Gene. */
599
+ cpuinfo_uarch_xgene = 0x00B00100,
600
+
601
+ /* Hygon Dhyana (a modification of AMD Zen for Chinese market). */
602
+ cpuinfo_uarch_dhyana = 0x01000100,
603
+
604
+ /** HiSilicon TaiShan v110 (Huawei Kunpeng 920 series processors). */
605
+ cpuinfo_uarch_taishan_v110 = 0x00C00100,
606
+ };
607
+
608
+ struct cpuinfo_processor {
609
+ /** SMT (hyperthread) ID within a core */
610
+ uint32_t smt_id;
611
+ /** Core containing this logical processor */
612
+ const struct cpuinfo_core* core;
613
+ /** Cluster of cores containing this logical processor */
614
+ const struct cpuinfo_cluster* cluster;
615
+ /** Physical package containing this logical processor */
616
+ const struct cpuinfo_package* package;
617
+ #if defined(__linux__)
618
+ /**
619
+ * Linux-specific ID for the logical processor:
620
+ * - Linux kernel exposes information about this logical processor in
621
+ * /sys/devices/system/cpu/cpu<linux_id>/
622
+ * - Bit <linux_id> in the cpu_set_t identifies this logical processor
623
+ */
624
+ int linux_id;
625
+ #endif
626
+ #if defined(_WIN32) || defined(__CYGWIN__)
627
+ /** Windows-specific ID for the group containing the logical processor.
628
+ */
629
+ uint16_t windows_group_id;
630
+ /**
631
+ * Windows-specific ID of the logical processor within its group:
632
+ * - Bit <windows_processor_id> in the KAFFINITY mask identifies this
633
+ * logical processor within its group.
634
+ */
635
+ uint16_t windows_processor_id;
636
+ #endif
637
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
638
+ /** APIC ID (unique x86-specific ID of the logical processor) */
639
+ uint32_t apic_id;
640
+ #endif
641
+ struct {
642
+ /** Level 1 instruction cache */
643
+ const struct cpuinfo_cache* l1i;
644
+ /** Level 1 data cache */
645
+ const struct cpuinfo_cache* l1d;
646
+ /** Level 2 unified or data cache */
647
+ const struct cpuinfo_cache* l2;
648
+ /** Level 3 unified or data cache */
649
+ const struct cpuinfo_cache* l3;
650
+ /** Level 4 unified or data cache */
651
+ const struct cpuinfo_cache* l4;
652
+ } cache;
653
+ };
654
+
655
+ struct cpuinfo_core {
656
+ /** Index of the first logical processor on this core. */
657
+ uint32_t processor_start;
658
+ /** Number of logical processors on this core */
659
+ uint32_t processor_count;
660
+ /** Core ID within a package */
661
+ uint32_t core_id;
662
+ /** Cluster containing this core */
663
+ const struct cpuinfo_cluster* cluster;
664
+ /** Physical package containing this core. */
665
+ const struct cpuinfo_package* package;
666
+ /** Vendor of the CPU microarchitecture for this core */
667
+ enum cpuinfo_vendor vendor;
668
+ /** CPU microarchitecture for this core */
669
+ enum cpuinfo_uarch uarch;
670
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
671
+ /** Value of CPUID leaf 1 EAX register for this core */
672
+ uint32_t cpuid;
673
+ #elif CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
674
+ /** Value of Main ID Register (MIDR) for this core */
675
+ uint32_t midr;
676
+ #endif
677
+ /** Clock rate (non-Turbo) of the core, in Hz */
678
+ uint64_t frequency;
679
+ };
680
+
681
+ struct cpuinfo_cluster {
682
+ /** Index of the first logical processor in the cluster */
683
+ uint32_t processor_start;
684
+ /** Number of logical processors in the cluster */
685
+ uint32_t processor_count;
686
+ /** Index of the first core in the cluster */
687
+ uint32_t core_start;
688
+ /** Number of cores on the cluster */
689
+ uint32_t core_count;
690
+ /** Cluster ID within a package */
691
+ uint32_t cluster_id;
692
+ /** Physical package containing the cluster */
693
+ const struct cpuinfo_package* package;
694
+ /** CPU microarchitecture vendor of the cores in the cluster */
695
+ enum cpuinfo_vendor vendor;
696
+ /** CPU microarchitecture of the cores in the cluster */
697
+ enum cpuinfo_uarch uarch;
698
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
699
+ /** Value of CPUID leaf 1 EAX register of the cores in the cluster */
700
+ uint32_t cpuid;
701
+ #elif CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
702
+ /** Value of Main ID Register (MIDR) of the cores in the cluster */
703
+ uint32_t midr;
704
+ #endif
705
+ /** Clock rate (non-Turbo) of the cores in the cluster, in Hz */
706
+ uint64_t frequency;
707
+ };
708
+
709
+ #define CPUINFO_PACKAGE_NAME_MAX 48
710
+
711
+ struct cpuinfo_package {
712
+ /** SoC or processor chip model name */
713
+ char name[CPUINFO_PACKAGE_NAME_MAX];
714
+ /** Index of the first logical processor on this physical package */
715
+ uint32_t processor_start;
716
+ /** Number of logical processors on this physical package */
717
+ uint32_t processor_count;
718
+ /** Index of the first core on this physical package */
719
+ uint32_t core_start;
720
+ /** Number of cores on this physical package */
721
+ uint32_t core_count;
722
+ /** Index of the first cluster of cores on this physical package */
723
+ uint32_t cluster_start;
724
+ /** Number of clusters of cores on this physical package */
725
+ uint32_t cluster_count;
726
+ };
727
+
728
+ struct cpuinfo_uarch_info {
729
+ /** Type of CPU microarchitecture */
730
+ enum cpuinfo_uarch uarch;
731
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
732
+ /** Value of CPUID leaf 1 EAX register for the microarchitecture */
733
+ uint32_t cpuid;
734
+ #elif CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
735
+ /** Value of Main ID Register (MIDR) for the microarchitecture */
736
+ uint32_t midr;
737
+ #endif
738
+ /** Number of logical processors with the microarchitecture */
739
+ uint32_t processor_count;
740
+ /** Number of cores with the microarchitecture */
741
+ uint32_t core_count;
742
+ };
743
+
744
+ #ifdef __cplusplus
745
+ extern "C" {
746
+ #endif
747
+
748
+ bool CPUINFO_ABI cpuinfo_initialize(void);
749
+
750
+ void CPUINFO_ABI cpuinfo_deinitialize(void);
751
+
752
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
753
+ /* This structure is not a part of stable API. Use cpuinfo_has_x86_* functions
754
+ * instead. */
755
+ struct cpuinfo_x86_isa {
756
+ #if CPUINFO_ARCH_X86
757
+ bool rdtsc;
758
+ #endif
759
+ bool rdtscp;
760
+ bool rdpid;
761
+ bool sysenter;
762
+ #if CPUINFO_ARCH_X86
763
+ bool syscall;
764
+ #endif
765
+ bool msr;
766
+ bool clzero;
767
+ bool clflush;
768
+ bool clflushopt;
769
+ bool mwait;
770
+ bool mwaitx;
771
+ #if CPUINFO_ARCH_X86
772
+ bool emmx;
773
+ #endif
774
+ bool fxsave;
775
+ bool xsave;
776
+ #if CPUINFO_ARCH_X86
777
+ bool fpu;
778
+ bool mmx;
779
+ bool mmx_plus;
780
+ #endif
781
+ bool three_d_now;
782
+ bool three_d_now_plus;
783
+ #if CPUINFO_ARCH_X86
784
+ bool three_d_now_geode;
785
+ #endif
786
+ bool prefetch;
787
+ bool prefetchw;
788
+ bool prefetchwt1;
789
+ #if CPUINFO_ARCH_X86
790
+ bool daz;
791
+ bool sse;
792
+ bool sse2;
793
+ #endif
794
+ bool sse3;
795
+ bool ssse3;
796
+ bool sse4_1;
797
+ bool sse4_2;
798
+ bool sse4a;
799
+ bool misaligned_sse;
800
+ bool avx;
801
+ bool avxvnni;
802
+ bool fma3;
803
+ bool fma4;
804
+ bool xop;
805
+ bool f16c;
806
+ bool avx2;
807
+ bool avx512f;
808
+ bool avx512pf;
809
+ bool avx512er;
810
+ bool avx512cd;
811
+ bool avx512dq;
812
+ bool avx512bw;
813
+ bool avx512vl;
814
+ bool avx512ifma;
815
+ bool avx512vbmi;
816
+ bool avx512vbmi2;
817
+ bool avx512bitalg;
818
+ bool avx512vpopcntdq;
819
+ bool avx512vnni;
820
+ bool avx512bf16;
821
+ bool avx512fp16;
822
+ bool avx512vp2intersect;
823
+ bool avx512_4vnniw;
824
+ bool avx512_4fmaps;
825
+ bool avx10_1;
826
+ bool avx10_2;
827
+ bool amx_bf16;
828
+ bool amx_tile;
829
+ bool amx_int8;
830
+ bool amx_fp16;
831
+ bool avx_vnni_int8;
832
+ bool avx_vnni_int16;
833
+ bool avx_ne_convert;
834
+ bool hle;
835
+ bool rtm;
836
+ bool xtest;
837
+ bool mpx;
838
+ #if CPUINFO_ARCH_X86
839
+ bool cmov;
840
+ bool cmpxchg8b;
841
+ #endif
842
+ bool cmpxchg16b;
843
+ bool clwb;
844
+ bool movbe;
845
+ #if CPUINFO_ARCH_X86_64
846
+ bool lahf_sahf;
847
+ #endif
848
+ bool fs_gs_base;
849
+ bool lzcnt;
850
+ bool popcnt;
851
+ bool tbm;
852
+ bool bmi;
853
+ bool bmi2;
854
+ bool adx;
855
+ bool aes;
856
+ bool vaes;
857
+ bool pclmulqdq;
858
+ bool vpclmulqdq;
859
+ bool gfni;
860
+ bool rdrand;
861
+ bool rdseed;
862
+ bool sha;
863
+ bool rng;
864
+ bool ace;
865
+ bool ace2;
866
+ bool phe;
867
+ bool pmm;
868
+ bool lwp;
869
+ };
870
+
871
+ extern struct cpuinfo_x86_isa cpuinfo_isa;
872
+ #endif
873
+
874
+ static inline bool cpuinfo_has_x86_rdtsc(void) {
875
+ #if CPUINFO_ARCH_X86_64
876
+ return true;
877
+ #elif CPUINFO_ARCH_X86
878
+ #if defined(__ANDROID__)
879
+ return true;
880
+ #else
881
+ return cpuinfo_isa.rdtsc;
882
+ #endif
883
+ #else
884
+ return false;
885
+ #endif
886
+ }
887
+
888
+ static inline bool cpuinfo_has_x86_rdtscp(void) {
889
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
890
+ return cpuinfo_isa.rdtscp;
891
+ #else
892
+ return false;
893
+ #endif
894
+ }
895
+
896
+ static inline bool cpuinfo_has_x86_rdpid(void) {
897
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
898
+ return cpuinfo_isa.rdpid;
899
+ #else
900
+ return false;
901
+ #endif
902
+ }
903
+
904
+ static inline bool cpuinfo_has_x86_clzero(void) {
905
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
906
+ return cpuinfo_isa.clzero;
907
+ #else
908
+ return false;
909
+ #endif
910
+ }
911
+
912
+ static inline bool cpuinfo_has_x86_mwait(void) {
913
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
914
+ return cpuinfo_isa.mwait;
915
+ #else
916
+ return false;
917
+ #endif
918
+ }
919
+
920
+ static inline bool cpuinfo_has_x86_mwaitx(void) {
921
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
922
+ return cpuinfo_isa.mwaitx;
923
+ #else
924
+ return false;
925
+ #endif
926
+ }
927
+
928
+ static inline bool cpuinfo_has_x86_fxsave(void) {
929
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
930
+ return cpuinfo_isa.fxsave;
931
+ #else
932
+ return false;
933
+ #endif
934
+ }
935
+
936
+ static inline bool cpuinfo_has_x86_xsave(void) {
937
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
938
+ return cpuinfo_isa.xsave;
939
+ #else
940
+ return false;
941
+ #endif
942
+ }
943
+
944
+ static inline bool cpuinfo_has_x86_fpu(void) {
945
+ #if CPUINFO_ARCH_X86_64
946
+ return true;
947
+ #elif CPUINFO_ARCH_X86
948
+ #if defined(__ANDROID__)
949
+ return true;
950
+ #else
951
+ return cpuinfo_isa.fpu;
952
+ #endif
953
+ #else
954
+ return false;
955
+ #endif
956
+ }
957
+
958
+ static inline bool cpuinfo_has_x86_mmx(void) {
959
+ #if CPUINFO_ARCH_X86_64
960
+ return true;
961
+ #elif CPUINFO_ARCH_X86
962
+ #if defined(__ANDROID__)
963
+ return true;
964
+ #else
965
+ return cpuinfo_isa.mmx;
966
+ #endif
967
+ #else
968
+ return false;
969
+ #endif
970
+ }
971
+
972
+ static inline bool cpuinfo_has_x86_mmx_plus(void) {
973
+ #if CPUINFO_ARCH_X86_64
974
+ return true;
975
+ #elif CPUINFO_ARCH_X86
976
+ #if defined(__ANDROID__)
977
+ return true;
978
+ #else
979
+ return cpuinfo_isa.mmx_plus;
980
+ #endif
981
+ #else
982
+ return false;
983
+ #endif
984
+ }
985
+
986
+ static inline bool cpuinfo_has_x86_3dnow(void) {
987
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
988
+ return cpuinfo_isa.three_d_now;
989
+ #else
990
+ return false;
991
+ #endif
992
+ }
993
+
994
+ static inline bool cpuinfo_has_x86_3dnow_plus(void) {
995
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
996
+ return cpuinfo_isa.three_d_now_plus;
997
+ #else
998
+ return false;
999
+ #endif
1000
+ }
1001
+
1002
+ static inline bool cpuinfo_has_x86_3dnow_geode(void) {
1003
+ #if CPUINFO_ARCH_X86_64
1004
+ return false;
1005
+ #elif CPUINFO_ARCH_X86
1006
+ #if defined(__ANDROID__)
1007
+ return false;
1008
+ #else
1009
+ return cpuinfo_isa.three_d_now_geode;
1010
+ #endif
1011
+ #else
1012
+ return false;
1013
+ #endif
1014
+ }
1015
+
1016
+ static inline bool cpuinfo_has_x86_prefetch(void) {
1017
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1018
+ return cpuinfo_isa.prefetch;
1019
+ #else
1020
+ return false;
1021
+ #endif
1022
+ }
1023
+
1024
+ static inline bool cpuinfo_has_x86_prefetchw(void) {
1025
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1026
+ return cpuinfo_isa.prefetchw;
1027
+ #else
1028
+ return false;
1029
+ #endif
1030
+ }
1031
+
1032
+ static inline bool cpuinfo_has_x86_prefetchwt1(void) {
1033
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1034
+ return cpuinfo_isa.prefetchwt1;
1035
+ #else
1036
+ return false;
1037
+ #endif
1038
+ }
1039
+
1040
+ static inline bool cpuinfo_has_x86_daz(void) {
1041
+ #if CPUINFO_ARCH_X86_64
1042
+ return true;
1043
+ #elif CPUINFO_ARCH_X86
1044
+ #if defined(__ANDROID__)
1045
+ return true;
1046
+ #else
1047
+ return cpuinfo_isa.daz;
1048
+ #endif
1049
+ #else
1050
+ return false;
1051
+ #endif
1052
+ }
1053
+
1054
+ static inline bool cpuinfo_has_x86_sse(void) {
1055
+ #if CPUINFO_ARCH_X86_64
1056
+ return true;
1057
+ #elif CPUINFO_ARCH_X86
1058
+ #if defined(__ANDROID__)
1059
+ return true;
1060
+ #else
1061
+ return cpuinfo_isa.sse;
1062
+ #endif
1063
+ #else
1064
+ return false;
1065
+ #endif
1066
+ }
1067
+
1068
+ static inline bool cpuinfo_has_x86_sse2(void) {
1069
+ #if CPUINFO_ARCH_X86_64
1070
+ return true;
1071
+ #elif CPUINFO_ARCH_X86
1072
+ #if defined(__ANDROID__)
1073
+ return true;
1074
+ #else
1075
+ return cpuinfo_isa.sse2;
1076
+ #endif
1077
+ #else
1078
+ return false;
1079
+ #endif
1080
+ }
1081
+
1082
+ static inline bool cpuinfo_has_x86_sse3(void) {
1083
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1084
+ #if defined(__ANDROID__)
1085
+ return true;
1086
+ #else
1087
+ return cpuinfo_isa.sse3;
1088
+ #endif
1089
+ #else
1090
+ return false;
1091
+ #endif
1092
+ }
1093
+
1094
+ static inline bool cpuinfo_has_x86_ssse3(void) {
1095
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1096
+ #if defined(__ANDROID__)
1097
+ return true;
1098
+ #else
1099
+ return cpuinfo_isa.ssse3;
1100
+ #endif
1101
+ #else
1102
+ return false;
1103
+ #endif
1104
+ }
1105
+
1106
+ static inline bool cpuinfo_has_x86_sse4_1(void) {
1107
+ #if CPUINFO_ARCH_X86_64
1108
+ #if defined(__ANDROID__)
1109
+ return true;
1110
+ #else
1111
+ return cpuinfo_isa.sse4_1;
1112
+ #endif
1113
+ #elif CPUINFO_ARCH_X86
1114
+ return cpuinfo_isa.sse4_1;
1115
+ #else
1116
+ return false;
1117
+ #endif
1118
+ }
1119
+
1120
+ static inline bool cpuinfo_has_x86_sse4_2(void) {
1121
+ #if CPUINFO_ARCH_X86_64
1122
+ #if defined(__ANDROID__)
1123
+ return true;
1124
+ #else
1125
+ return cpuinfo_isa.sse4_2;
1126
+ #endif
1127
+ #elif CPUINFO_ARCH_X86
1128
+ return cpuinfo_isa.sse4_2;
1129
+ #else
1130
+ return false;
1131
+ #endif
1132
+ }
1133
+
1134
+ static inline bool cpuinfo_has_x86_sse4a(void) {
1135
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1136
+ return cpuinfo_isa.sse4a;
1137
+ #else
1138
+ return false;
1139
+ #endif
1140
+ }
1141
+
1142
+ static inline bool cpuinfo_has_x86_misaligned_sse(void) {
1143
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1144
+ return cpuinfo_isa.misaligned_sse;
1145
+ #else
1146
+ return false;
1147
+ #endif
1148
+ }
1149
+
1150
+ static inline bool cpuinfo_has_x86_avx(void) {
1151
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1152
+ return cpuinfo_isa.avx;
1153
+ #else
1154
+ return false;
1155
+ #endif
1156
+ }
1157
+
1158
+ static inline bool cpuinfo_has_x86_avxvnni(void) {
1159
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1160
+ return cpuinfo_isa.avxvnni;
1161
+ #else
1162
+ return false;
1163
+ #endif
1164
+ }
1165
+
1166
+ static inline bool cpuinfo_has_x86_fma3(void) {
1167
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1168
+ return cpuinfo_isa.fma3;
1169
+ #else
1170
+ return false;
1171
+ #endif
1172
+ }
1173
+
1174
+ static inline bool cpuinfo_has_x86_fma4(void) {
1175
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1176
+ return cpuinfo_isa.fma4;
1177
+ #else
1178
+ return false;
1179
+ #endif
1180
+ }
1181
+
1182
+ static inline bool cpuinfo_has_x86_xop(void) {
1183
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1184
+ return cpuinfo_isa.xop;
1185
+ #else
1186
+ return false;
1187
+ #endif
1188
+ }
1189
+
1190
+ static inline bool cpuinfo_has_x86_f16c(void) {
1191
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1192
+ return cpuinfo_isa.f16c;
1193
+ #else
1194
+ return false;
1195
+ #endif
1196
+ }
1197
+
1198
+ static inline bool cpuinfo_has_x86_avx2(void) {
1199
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1200
+ return cpuinfo_isa.avx2;
1201
+ #else
1202
+ return false;
1203
+ #endif
1204
+ }
1205
+
1206
+ static inline bool cpuinfo_has_x86_avx512f(void) {
1207
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1208
+ return cpuinfo_isa.avx512f;
1209
+ #else
1210
+ return false;
1211
+ #endif
1212
+ }
1213
+
1214
+ static inline bool cpuinfo_has_x86_avx512pf(void) {
1215
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1216
+ return cpuinfo_isa.avx512pf;
1217
+ #else
1218
+ return false;
1219
+ #endif
1220
+ }
1221
+
1222
+ static inline bool cpuinfo_has_x86_avx512er(void) {
1223
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1224
+ return cpuinfo_isa.avx512er;
1225
+ #else
1226
+ return false;
1227
+ #endif
1228
+ }
1229
+
1230
+ static inline bool cpuinfo_has_x86_avx512cd(void) {
1231
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1232
+ return cpuinfo_isa.avx512cd;
1233
+ #else
1234
+ return false;
1235
+ #endif
1236
+ }
1237
+
1238
+ static inline bool cpuinfo_has_x86_avx512dq(void) {
1239
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1240
+ return cpuinfo_isa.avx512dq;
1241
+ #else
1242
+ return false;
1243
+ #endif
1244
+ }
1245
+
1246
+ static inline bool cpuinfo_has_x86_avx512bw(void) {
1247
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1248
+ return cpuinfo_isa.avx512bw;
1249
+ #else
1250
+ return false;
1251
+ #endif
1252
+ }
1253
+
1254
+ static inline bool cpuinfo_has_x86_avx512vl(void) {
1255
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1256
+ return cpuinfo_isa.avx512vl;
1257
+ #else
1258
+ return false;
1259
+ #endif
1260
+ }
1261
+
1262
+ static inline bool cpuinfo_has_x86_avx512ifma(void) {
1263
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1264
+ return cpuinfo_isa.avx512ifma;
1265
+ #else
1266
+ return false;
1267
+ #endif
1268
+ }
1269
+
1270
+ static inline bool cpuinfo_has_x86_avx512vbmi(void) {
1271
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1272
+ return cpuinfo_isa.avx512vbmi;
1273
+ #else
1274
+ return false;
1275
+ #endif
1276
+ }
1277
+
1278
+ static inline bool cpuinfo_has_x86_avx512vbmi2(void) {
1279
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1280
+ return cpuinfo_isa.avx512vbmi2;
1281
+ #else
1282
+ return false;
1283
+ #endif
1284
+ }
1285
+
1286
+ static inline bool cpuinfo_has_x86_avx512bitalg(void) {
1287
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1288
+ return cpuinfo_isa.avx512bitalg;
1289
+ #else
1290
+ return false;
1291
+ #endif
1292
+ }
1293
+
1294
+ static inline bool cpuinfo_has_x86_avx512vpopcntdq(void) {
1295
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1296
+ return cpuinfo_isa.avx512vpopcntdq;
1297
+ #else
1298
+ return false;
1299
+ #endif
1300
+ }
1301
+
1302
+ static inline bool cpuinfo_has_x86_avx512vnni(void) {
1303
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1304
+ return cpuinfo_isa.avx512vnni;
1305
+ #else
1306
+ return false;
1307
+ #endif
1308
+ }
1309
+
1310
+ static inline bool cpuinfo_has_x86_avx512bf16(void) {
1311
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1312
+ return cpuinfo_isa.avx512bf16;
1313
+ #else
1314
+ return false;
1315
+ #endif
1316
+ }
1317
+
1318
+ static inline bool cpuinfo_has_x86_avx512fp16(void) {
1319
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1320
+ return cpuinfo_isa.avx512fp16;
1321
+ #else
1322
+ return false;
1323
+ #endif
1324
+ }
1325
+
1326
+ static inline bool cpuinfo_has_x86_avx512vp2intersect(void) {
1327
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1328
+ return cpuinfo_isa.avx512vp2intersect;
1329
+ #else
1330
+ return false;
1331
+ #endif
1332
+ }
1333
+
1334
+ static inline bool cpuinfo_has_x86_avx512_4vnniw(void) {
1335
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1336
+ return cpuinfo_isa.avx512_4vnniw;
1337
+ #else
1338
+ return false;
1339
+ #endif
1340
+ }
1341
+
1342
+ static inline bool cpuinfo_has_x86_avx512_4fmaps(void) {
1343
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1344
+ return cpuinfo_isa.avx512_4fmaps;
1345
+ #else
1346
+ return false;
1347
+ #endif
1348
+ }
1349
+
1350
+ /* [NOTE] Intel Advanced Matrix Extensions (AMX) detection
1351
+ *
1352
+ * I. AMX is a new extensions to the x86 ISA to work on matrices, consists of
1353
+ * 1) 2-dimentional registers (tiles), hold sub-matrices from larger matrices in memory
1354
+ * 2) Accelerator called Tile Matrix Multiply (TMUL), contains instructions operating on tiles
1355
+ *
1356
+ * II. Platforms that supports AMX:
1357
+ * +-----------------+-----+----------+----------+----------+----------+
1358
+ * | Platforms | Gen | amx-bf16 | amx-tile | amx-int8 | amx-fp16 |
1359
+ * +-----------------+-----+----------+----------+----------+----------+
1360
+ * | Sapphire Rapids | 4th | YES | YES | YES | NO |
1361
+ * +-----------------+-----+----------+----------+----------+----------+
1362
+ * | Emerald Rapids | 5th | YES | YES | YES | NO |
1363
+ * +-----------------+-----+----------+----------+----------+----------+
1364
+ * | Granite Rapids | 6th | YES | YES | YES | YES |
1365
+ * +-----------------+-----+----------+----------+----------+----------+
1366
+ *
1367
+ * Reference: https://www.intel.com/content/www/us/en/products/docs
1368
+ * /accelerator-engines/advanced-matrix-extensions/overview.html
1369
+ */
1370
+ static inline bool cpuinfo_has_x86_amx_bf16(void) {
1371
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1372
+ return cpuinfo_isa.amx_bf16;
1373
+ #else
1374
+ return false;
1375
+ #endif
1376
+ }
1377
+
1378
+ static inline bool cpuinfo_has_x86_amx_tile(void) {
1379
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1380
+ return cpuinfo_isa.amx_tile;
1381
+ #else
1382
+ return false;
1383
+ #endif
1384
+ }
1385
+
1386
+ static inline bool cpuinfo_has_x86_amx_int8(void) {
1387
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1388
+ return cpuinfo_isa.amx_int8;
1389
+ #else
1390
+ return false;
1391
+ #endif
1392
+ }
1393
+
1394
+ static inline bool cpuinfo_has_x86_amx_fp16(void) {
1395
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1396
+ return cpuinfo_isa.amx_fp16;
1397
+ #else
1398
+ return false;
1399
+ #endif
1400
+ }
1401
+
1402
+ /*
1403
+ * Intel AVX Vector Neural Network Instructions (VNNI) INT8
1404
+ * Supported Platfroms: Sierra Forest, Arrow Lake, Lunar Lake
1405
+ */
1406
+ static inline bool cpuinfo_has_x86_avx_vnni_int8(void) {
1407
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1408
+ return cpuinfo_isa.avx_vnni_int8;
1409
+ #else
1410
+ return false;
1411
+ #endif
1412
+ }
1413
+
1414
+ /*
1415
+ * Intel AVX Vector Neural Network Instructions (VNNI) INT16
1416
+ * Supported Platfroms: Arrow Lake, Lunar Lake
1417
+ */
1418
+ static inline bool cpuinfo_has_x86_avx_vnni_int16(void) {
1419
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1420
+ return cpuinfo_isa.avx_vnni_int16;
1421
+ #else
1422
+ return false;
1423
+ #endif
1424
+ }
1425
+
1426
+ /*
1427
+ * A new set of instructions, which can convert low precision floating point
1428
+ * like BF16/FP16 to high precision floating point FP32, as well as convert FP32
1429
+ * elements to BF16. This instruction allows the platform to have improved AI
1430
+ * capabilities and better compatibility.
1431
+ *
1432
+ * Supported Platforms: Sierra Forest, Arrow Lake, Lunar Lake
1433
+ */
1434
+ static inline bool cpuinfo_has_x86_avx_ne_convert(void) {
1435
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1436
+ return cpuinfo_isa.avx_ne_convert;
1437
+ #else
1438
+ return false;
1439
+ #endif
1440
+ }
1441
+
1442
+ static inline bool cpuinfo_has_x86_avx10_1(void) {
1443
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1444
+ return cpuinfo_isa.avx10_1;
1445
+ #else
1446
+ return false;
1447
+ #endif
1448
+ }
1449
+
1450
+ static inline bool cpuinfo_has_x86_avx10_2(void) {
1451
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1452
+ return cpuinfo_isa.avx10_2;
1453
+ #else
1454
+ return false;
1455
+ #endif
1456
+ }
1457
+
1458
+ static inline bool cpuinfo_has_x86_hle(void) {
1459
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1460
+ return cpuinfo_isa.hle;
1461
+ #else
1462
+ return false;
1463
+ #endif
1464
+ }
1465
+
1466
+ static inline bool cpuinfo_has_x86_rtm(void) {
1467
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1468
+ return cpuinfo_isa.rtm;
1469
+ #else
1470
+ return false;
1471
+ #endif
1472
+ }
1473
+
1474
+ static inline bool cpuinfo_has_x86_xtest(void) {
1475
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1476
+ return cpuinfo_isa.xtest;
1477
+ #else
1478
+ return false;
1479
+ #endif
1480
+ }
1481
+
1482
+ static inline bool cpuinfo_has_x86_mpx(void) {
1483
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1484
+ return cpuinfo_isa.mpx;
1485
+ #else
1486
+ return false;
1487
+ #endif
1488
+ }
1489
+
1490
+ static inline bool cpuinfo_has_x86_cmov(void) {
1491
+ #if CPUINFO_ARCH_X86_64
1492
+ return true;
1493
+ #elif CPUINFO_ARCH_X86
1494
+ return cpuinfo_isa.cmov;
1495
+ #else
1496
+ return false;
1497
+ #endif
1498
+ }
1499
+
1500
+ static inline bool cpuinfo_has_x86_cmpxchg8b(void) {
1501
+ #if CPUINFO_ARCH_X86_64
1502
+ return true;
1503
+ #elif CPUINFO_ARCH_X86
1504
+ return cpuinfo_isa.cmpxchg8b;
1505
+ #else
1506
+ return false;
1507
+ #endif
1508
+ }
1509
+
1510
+ static inline bool cpuinfo_has_x86_cmpxchg16b(void) {
1511
+ #if CPUINFO_ARCH_X86_64
1512
+ return cpuinfo_isa.cmpxchg16b;
1513
+ #else
1514
+ return false;
1515
+ #endif
1516
+ }
1517
+
1518
+ static inline bool cpuinfo_has_x86_clwb(void) {
1519
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1520
+ return cpuinfo_isa.clwb;
1521
+ #else
1522
+ return false;
1523
+ #endif
1524
+ }
1525
+
1526
+ static inline bool cpuinfo_has_x86_movbe(void) {
1527
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1528
+ return cpuinfo_isa.movbe;
1529
+ #else
1530
+ return false;
1531
+ #endif
1532
+ }
1533
+
1534
+ static inline bool cpuinfo_has_x86_lahf_sahf(void) {
1535
+ #if CPUINFO_ARCH_X86
1536
+ return true;
1537
+ #elif CPUINFO_ARCH_X86_64
1538
+ return cpuinfo_isa.lahf_sahf;
1539
+ #else
1540
+ return false;
1541
+ #endif
1542
+ }
1543
+
1544
+ static inline bool cpuinfo_has_x86_lzcnt(void) {
1545
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1546
+ return cpuinfo_isa.lzcnt;
1547
+ #else
1548
+ return false;
1549
+ #endif
1550
+ }
1551
+
1552
+ static inline bool cpuinfo_has_x86_popcnt(void) {
1553
+ #if CPUINFO_ARCH_X86_64
1554
+ #if defined(__ANDROID__)
1555
+ return true;
1556
+ #else
1557
+ return cpuinfo_isa.popcnt;
1558
+ #endif
1559
+ #elif CPUINFO_ARCH_X86
1560
+ return cpuinfo_isa.popcnt;
1561
+ #else
1562
+ return false;
1563
+ #endif
1564
+ }
1565
+
1566
+ static inline bool cpuinfo_has_x86_tbm(void) {
1567
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1568
+ return cpuinfo_isa.tbm;
1569
+ #else
1570
+ return false;
1571
+ #endif
1572
+ }
1573
+
1574
+ static inline bool cpuinfo_has_x86_bmi(void) {
1575
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1576
+ return cpuinfo_isa.bmi;
1577
+ #else
1578
+ return false;
1579
+ #endif
1580
+ }
1581
+
1582
+ static inline bool cpuinfo_has_x86_bmi2(void) {
1583
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1584
+ return cpuinfo_isa.bmi2;
1585
+ #else
1586
+ return false;
1587
+ #endif
1588
+ }
1589
+
1590
+ static inline bool cpuinfo_has_x86_adx(void) {
1591
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1592
+ return cpuinfo_isa.adx;
1593
+ #else
1594
+ return false;
1595
+ #endif
1596
+ }
1597
+
1598
+ static inline bool cpuinfo_has_x86_aes(void) {
1599
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1600
+ return cpuinfo_isa.aes;
1601
+ #else
1602
+ return false;
1603
+ #endif
1604
+ }
1605
+
1606
+ static inline bool cpuinfo_has_x86_vaes(void) {
1607
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1608
+ return cpuinfo_isa.vaes;
1609
+ #else
1610
+ return false;
1611
+ #endif
1612
+ }
1613
+
1614
+ static inline bool cpuinfo_has_x86_pclmulqdq(void) {
1615
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1616
+ return cpuinfo_isa.pclmulqdq;
1617
+ #else
1618
+ return false;
1619
+ #endif
1620
+ }
1621
+
1622
+ static inline bool cpuinfo_has_x86_vpclmulqdq(void) {
1623
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1624
+ return cpuinfo_isa.vpclmulqdq;
1625
+ #else
1626
+ return false;
1627
+ #endif
1628
+ }
1629
+
1630
+ static inline bool cpuinfo_has_x86_gfni(void) {
1631
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1632
+ return cpuinfo_isa.gfni;
1633
+ #else
1634
+ return false;
1635
+ #endif
1636
+ }
1637
+
1638
+ static inline bool cpuinfo_has_x86_rdrand(void) {
1639
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1640
+ return cpuinfo_isa.rdrand;
1641
+ #else
1642
+ return false;
1643
+ #endif
1644
+ }
1645
+
1646
+ static inline bool cpuinfo_has_x86_rdseed(void) {
1647
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1648
+ return cpuinfo_isa.rdseed;
1649
+ #else
1650
+ return false;
1651
+ #endif
1652
+ }
1653
+
1654
+ static inline bool cpuinfo_has_x86_sha(void) {
1655
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1656
+ return cpuinfo_isa.sha;
1657
+ #else
1658
+ return false;
1659
+ #endif
1660
+ }
1661
+
1662
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1663
+ /* This structure is not a part of stable API. Use cpuinfo_has_arm_* functions
1664
+ * instead. */
1665
+ struct cpuinfo_arm_isa {
1666
+ #if CPUINFO_ARCH_ARM
1667
+ bool thumb;
1668
+ bool thumb2;
1669
+ bool thumbee;
1670
+ bool jazelle;
1671
+ bool armv5e;
1672
+ bool armv6;
1673
+ bool armv6k;
1674
+ bool armv7;
1675
+ bool armv7mp;
1676
+ bool armv8;
1677
+ bool idiv;
1678
+
1679
+ bool vfpv2;
1680
+ bool vfpv3;
1681
+ bool d32;
1682
+ bool fp16;
1683
+ bool fma;
1684
+
1685
+ bool wmmx;
1686
+ bool wmmx2;
1687
+ bool neon;
1688
+ #endif
1689
+ #if CPUINFO_ARCH_ARM64
1690
+ bool atomics;
1691
+ bool bf16;
1692
+ bool sve;
1693
+ bool sve2;
1694
+ bool i8mm;
1695
+ bool sme;
1696
+ bool sme2;
1697
+ bool sme2p1;
1698
+ bool sme_i16i32;
1699
+ bool sme_bi32i32;
1700
+ bool sme_b16b16;
1701
+ bool sme_f16f16;
1702
+ uint32_t svelen;
1703
+ uint32_t smelen;
1704
+ #endif
1705
+ bool rdm;
1706
+ bool fp16arith;
1707
+ bool dot;
1708
+ bool jscvt;
1709
+ bool fcma;
1710
+ bool fhm;
1711
+
1712
+ bool aes;
1713
+ bool sha1;
1714
+ bool sha2;
1715
+ bool pmull;
1716
+ bool crc32;
1717
+ };
1718
+
1719
+ extern struct cpuinfo_arm_isa cpuinfo_isa;
1720
+ #endif
1721
+
1722
+ static inline bool cpuinfo_has_arm_thumb(void) {
1723
+ #if CPUINFO_ARCH_ARM
1724
+ return cpuinfo_isa.thumb;
1725
+ #else
1726
+ return false;
1727
+ #endif
1728
+ }
1729
+
1730
+ static inline bool cpuinfo_has_arm_thumb2(void) {
1731
+ #if CPUINFO_ARCH_ARM
1732
+ return cpuinfo_isa.thumb2;
1733
+ #else
1734
+ return false;
1735
+ #endif
1736
+ }
1737
+
1738
+ static inline bool cpuinfo_has_arm_v5e(void) {
1739
+ #if CPUINFO_ARCH_ARM
1740
+ return cpuinfo_isa.armv5e;
1741
+ #else
1742
+ return false;
1743
+ #endif
1744
+ }
1745
+
1746
+ static inline bool cpuinfo_has_arm_v6(void) {
1747
+ #if CPUINFO_ARCH_ARM
1748
+ return cpuinfo_isa.armv6;
1749
+ #else
1750
+ return false;
1751
+ #endif
1752
+ }
1753
+
1754
+ static inline bool cpuinfo_has_arm_v6k(void) {
1755
+ #if CPUINFO_ARCH_ARM
1756
+ return cpuinfo_isa.armv6k;
1757
+ #else
1758
+ return false;
1759
+ #endif
1760
+ }
1761
+
1762
+ static inline bool cpuinfo_has_arm_v7(void) {
1763
+ #if CPUINFO_ARCH_ARM
1764
+ return cpuinfo_isa.armv7;
1765
+ #else
1766
+ return false;
1767
+ #endif
1768
+ }
1769
+
1770
+ static inline bool cpuinfo_has_arm_v7mp(void) {
1771
+ #if CPUINFO_ARCH_ARM
1772
+ return cpuinfo_isa.armv7mp;
1773
+ #else
1774
+ return false;
1775
+ #endif
1776
+ }
1777
+
1778
+ static inline bool cpuinfo_has_arm_v8(void) {
1779
+ #if CPUINFO_ARCH_ARM64
1780
+ return true;
1781
+ #elif CPUINFO_ARCH_ARM
1782
+ return cpuinfo_isa.armv8;
1783
+ #else
1784
+ return false;
1785
+ #endif
1786
+ }
1787
+
1788
+ static inline bool cpuinfo_has_arm_idiv(void) {
1789
+ #if CPUINFO_ARCH_ARM64
1790
+ return true;
1791
+ #elif CPUINFO_ARCH_ARM
1792
+ return cpuinfo_isa.idiv;
1793
+ #else
1794
+ return false;
1795
+ #endif
1796
+ }
1797
+
1798
+ static inline bool cpuinfo_has_arm_vfpv2(void) {
1799
+ #if CPUINFO_ARCH_ARM
1800
+ return cpuinfo_isa.vfpv2;
1801
+ #else
1802
+ return false;
1803
+ #endif
1804
+ }
1805
+
1806
+ static inline bool cpuinfo_has_arm_vfpv3(void) {
1807
+ #if CPUINFO_ARCH_ARM64
1808
+ return true;
1809
+ #elif CPUINFO_ARCH_ARM
1810
+ return cpuinfo_isa.vfpv3;
1811
+ #else
1812
+ return false;
1813
+ #endif
1814
+ }
1815
+
1816
+ static inline bool cpuinfo_has_arm_vfpv3_d32(void) {
1817
+ #if CPUINFO_ARCH_ARM64
1818
+ return true;
1819
+ #elif CPUINFO_ARCH_ARM
1820
+ return cpuinfo_isa.vfpv3 && cpuinfo_isa.d32;
1821
+ #else
1822
+ return false;
1823
+ #endif
1824
+ }
1825
+
1826
+ static inline bool cpuinfo_has_arm_vfpv3_fp16(void) {
1827
+ #if CPUINFO_ARCH_ARM64
1828
+ return true;
1829
+ #elif CPUINFO_ARCH_ARM
1830
+ return cpuinfo_isa.vfpv3 && cpuinfo_isa.fp16;
1831
+ #else
1832
+ return false;
1833
+ #endif
1834
+ }
1835
+
1836
+ static inline bool cpuinfo_has_arm_vfpv3_fp16_d32(void) {
1837
+ #if CPUINFO_ARCH_ARM64
1838
+ return true;
1839
+ #elif CPUINFO_ARCH_ARM
1840
+ return cpuinfo_isa.vfpv3 && cpuinfo_isa.fp16 && cpuinfo_isa.d32;
1841
+ #else
1842
+ return false;
1843
+ #endif
1844
+ }
1845
+
1846
+ static inline bool cpuinfo_has_arm_vfpv4(void) {
1847
+ #if CPUINFO_ARCH_ARM64
1848
+ return true;
1849
+ #elif CPUINFO_ARCH_ARM
1850
+ return cpuinfo_isa.vfpv3 && cpuinfo_isa.fma;
1851
+ #else
1852
+ return false;
1853
+ #endif
1854
+ }
1855
+
1856
+ static inline bool cpuinfo_has_arm_vfpv4_d32(void) {
1857
+ #if CPUINFO_ARCH_ARM64
1858
+ return true;
1859
+ #elif CPUINFO_ARCH_ARM
1860
+ return cpuinfo_isa.vfpv3 && cpuinfo_isa.fma && cpuinfo_isa.d32;
1861
+ #else
1862
+ return false;
1863
+ #endif
1864
+ }
1865
+
1866
+ static inline bool cpuinfo_has_arm_fp16_arith(void) {
1867
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1868
+ return cpuinfo_isa.fp16arith;
1869
+ #else
1870
+ return false;
1871
+ #endif
1872
+ }
1873
+
1874
+ static inline bool cpuinfo_has_arm_bf16(void) {
1875
+ #if CPUINFO_ARCH_ARM64
1876
+ return cpuinfo_isa.bf16;
1877
+ #else
1878
+ return false;
1879
+ #endif
1880
+ }
1881
+
1882
+ static inline bool cpuinfo_has_arm_wmmx(void) {
1883
+ #if CPUINFO_ARCH_ARM
1884
+ return cpuinfo_isa.wmmx;
1885
+ #else
1886
+ return false;
1887
+ #endif
1888
+ }
1889
+
1890
+ static inline bool cpuinfo_has_arm_wmmx2(void) {
1891
+ #if CPUINFO_ARCH_ARM
1892
+ return cpuinfo_isa.wmmx2;
1893
+ #else
1894
+ return false;
1895
+ #endif
1896
+ }
1897
+
1898
+ static inline bool cpuinfo_has_arm_neon(void) {
1899
+ #if CPUINFO_ARCH_ARM64
1900
+ return true;
1901
+ #elif CPUINFO_ARCH_ARM
1902
+ return cpuinfo_isa.neon;
1903
+ #else
1904
+ return false;
1905
+ #endif
1906
+ }
1907
+
1908
+ static inline bool cpuinfo_has_arm_neon_fp16(void) {
1909
+ #if CPUINFO_ARCH_ARM64
1910
+ return true;
1911
+ #elif CPUINFO_ARCH_ARM
1912
+ return cpuinfo_isa.neon && cpuinfo_isa.fp16;
1913
+ #else
1914
+ return false;
1915
+ #endif
1916
+ }
1917
+
1918
+ static inline bool cpuinfo_has_arm_neon_fma(void) {
1919
+ #if CPUINFO_ARCH_ARM64
1920
+ return true;
1921
+ #elif CPUINFO_ARCH_ARM
1922
+ return cpuinfo_isa.neon && cpuinfo_isa.fma;
1923
+ #else
1924
+ return false;
1925
+ #endif
1926
+ }
1927
+
1928
+ static inline bool cpuinfo_has_arm_neon_v8(void) {
1929
+ #if CPUINFO_ARCH_ARM64
1930
+ return true;
1931
+ #elif CPUINFO_ARCH_ARM
1932
+ return cpuinfo_isa.neon && cpuinfo_isa.armv8;
1933
+ #else
1934
+ return false;
1935
+ #endif
1936
+ }
1937
+
1938
+ static inline bool cpuinfo_has_arm_atomics(void) {
1939
+ #if CPUINFO_ARCH_ARM64
1940
+ return cpuinfo_isa.atomics;
1941
+ #else
1942
+ return false;
1943
+ #endif
1944
+ }
1945
+
1946
+ static inline bool cpuinfo_has_arm_neon_rdm(void) {
1947
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1948
+ return cpuinfo_isa.rdm;
1949
+ #else
1950
+ return false;
1951
+ #endif
1952
+ }
1953
+
1954
+ static inline bool cpuinfo_has_arm_neon_fp16_arith(void) {
1955
+ #if CPUINFO_ARCH_ARM
1956
+ return cpuinfo_isa.neon && cpuinfo_isa.fp16arith;
1957
+ #elif CPUINFO_ARCH_ARM64
1958
+ return cpuinfo_isa.fp16arith;
1959
+ #else
1960
+ return false;
1961
+ #endif
1962
+ }
1963
+
1964
+ static inline bool cpuinfo_has_arm_fhm(void) {
1965
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1966
+ return cpuinfo_isa.fhm;
1967
+ #else
1968
+ return false;
1969
+ #endif
1970
+ }
1971
+
1972
+ static inline bool cpuinfo_has_arm_neon_dot(void) {
1973
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1974
+ return cpuinfo_isa.dot;
1975
+ #else
1976
+ return false;
1977
+ #endif
1978
+ }
1979
+
1980
+ static inline bool cpuinfo_has_arm_neon_bf16(void) {
1981
+ #if CPUINFO_ARCH_ARM64
1982
+ return cpuinfo_isa.bf16;
1983
+ #else
1984
+ return false;
1985
+ #endif
1986
+ }
1987
+
1988
+ static inline bool cpuinfo_has_arm_jscvt(void) {
1989
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1990
+ return cpuinfo_isa.jscvt;
1991
+ #else
1992
+ return false;
1993
+ #endif
1994
+ }
1995
+
1996
+ static inline bool cpuinfo_has_arm_fcma(void) {
1997
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1998
+ return cpuinfo_isa.fcma;
1999
+ #else
2000
+ return false;
2001
+ #endif
2002
+ }
2003
+
2004
+ static inline bool cpuinfo_has_arm_i8mm(void) {
2005
+ #if CPUINFO_ARCH_ARM64
2006
+ return cpuinfo_isa.i8mm;
2007
+ #else
2008
+ return false;
2009
+ #endif
2010
+ }
2011
+
2012
+ static inline bool cpuinfo_has_arm_aes(void) {
2013
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
2014
+ return cpuinfo_isa.aes;
2015
+ #else
2016
+ return false;
2017
+ #endif
2018
+ }
2019
+
2020
+ static inline bool cpuinfo_has_arm_sha1(void) {
2021
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
2022
+ return cpuinfo_isa.sha1;
2023
+ #else
2024
+ return false;
2025
+ #endif
2026
+ }
2027
+
2028
+ static inline bool cpuinfo_has_arm_sha2(void) {
2029
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
2030
+ return cpuinfo_isa.sha2;
2031
+ #else
2032
+ return false;
2033
+ #endif
2034
+ }
2035
+
2036
+ static inline bool cpuinfo_has_arm_pmull(void) {
2037
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
2038
+ return cpuinfo_isa.pmull;
2039
+ #else
2040
+ return false;
2041
+ #endif
2042
+ }
2043
+
2044
+ static inline bool cpuinfo_has_arm_crc32(void) {
2045
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
2046
+ return cpuinfo_isa.crc32;
2047
+ #else
2048
+ return false;
2049
+ #endif
2050
+ }
2051
+
2052
+ static inline bool cpuinfo_has_arm_sve(void) {
2053
+ #if CPUINFO_ARCH_ARM64
2054
+ return cpuinfo_isa.sve;
2055
+ #else
2056
+ return false;
2057
+ #endif
2058
+ }
2059
+
2060
+ static inline bool cpuinfo_has_arm_sve_bf16(void) {
2061
+ #if CPUINFO_ARCH_ARM64
2062
+ return cpuinfo_isa.sve && cpuinfo_isa.bf16;
2063
+ #else
2064
+ return false;
2065
+ #endif
2066
+ }
2067
+
2068
+ static inline bool cpuinfo_has_arm_sve2(void) {
2069
+ #if CPUINFO_ARCH_ARM64
2070
+ return cpuinfo_isa.sve2;
2071
+ #else
2072
+ return false;
2073
+ #endif
2074
+ }
2075
+
2076
+ // Function to get the max SVE vector length on ARM CPU's which support SVE.
2077
+ static inline uint32_t cpuinfo_get_max_arm_sve_length(void) {
2078
+ #if CPUINFO_ARCH_ARM64
2079
+ return cpuinfo_isa.svelen * 8; // bytes * 8 = bit length(vector length)
2080
+ #else
2081
+ return 0;
2082
+ #endif
2083
+ }
2084
+
2085
+ // Function to get the max SME vector length on ARM CPU's which support SME.
2086
+ static inline uint32_t cpuinfo_get_max_arm_sme_length(void) {
2087
+ #if CPUINFO_ARCH_ARM64
2088
+ return cpuinfo_isa.smelen * 8; // bytes * 8 = bit length(vector length)
2089
+ #else
2090
+ return 0;
2091
+ #endif
2092
+ }
2093
+
2094
+ static inline bool cpuinfo_has_arm_sme(void) {
2095
+ #if CPUINFO_ARCH_ARM64
2096
+ return cpuinfo_isa.sme;
2097
+ #else
2098
+ return false;
2099
+ #endif
2100
+ }
2101
+
2102
+ static inline bool cpuinfo_has_arm_sme2(void) {
2103
+ #if CPUINFO_ARCH_ARM64
2104
+ return cpuinfo_isa.sme2;
2105
+ #else
2106
+ return false;
2107
+ #endif
2108
+ }
2109
+
2110
+ static inline bool cpuinfo_has_arm_sme2p1(void) {
2111
+ #if CPUINFO_ARCH_ARM64
2112
+ return cpuinfo_isa.sme2p1;
2113
+ #else
2114
+ return false;
2115
+ #endif
2116
+ }
2117
+
2118
+ static inline bool cpuinfo_has_arm_sme_i16i32(void) {
2119
+ #if CPUINFO_ARCH_ARM64
2120
+ return cpuinfo_isa.sme_i16i32;
2121
+ #else
2122
+ return false;
2123
+ #endif
2124
+ }
2125
+
2126
+ static inline bool cpuinfo_has_arm_sme_bi32i32(void) {
2127
+ #if CPUINFO_ARCH_ARM64
2128
+ return cpuinfo_isa.sme_bi32i32;
2129
+ #else
2130
+ return false;
2131
+ #endif
2132
+ }
2133
+
2134
+ static inline bool cpuinfo_has_arm_sme_b16b16(void) {
2135
+ #if CPUINFO_ARCH_ARM64
2136
+ return cpuinfo_isa.sme_b16b16;
2137
+ #else
2138
+ return false;
2139
+ #endif
2140
+ }
2141
+
2142
+ static inline bool cpuinfo_has_arm_sme_f16f16(void) {
2143
+ #if CPUINFO_ARCH_ARM64
2144
+ return cpuinfo_isa.sme_f16f16;
2145
+ #else
2146
+ return false;
2147
+ #endif
2148
+ }
2149
+
2150
+ #if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64
2151
+ /* This structure is not a part of stable API. Use cpuinfo_has_riscv_* functions
2152
+ * instead. */
2153
+ struct cpuinfo_riscv_isa {
2154
+ /**
2155
+ * Keep fields in line with the canonical order as defined by
2156
+ * Section 27.11 Subset Naming Convention.
2157
+ */
2158
+ /* RV32I/64I/128I Base ISA. */
2159
+ bool i;
2160
+ #if CPUINFO_ARCH_RISCV32
2161
+ /* RV32E Base ISA. */
2162
+ bool e;
2163
+ #endif
2164
+ /* Integer Multiply/Divide Extension. */
2165
+ bool m;
2166
+ /* Atomic Extension. */
2167
+ bool a;
2168
+ /* Single-Precision Floating-Point Extension. */
2169
+ bool f;
2170
+ /* Double-Precision Floating-Point Extension. */
2171
+ bool d;
2172
+ /* Compressed Extension. */
2173
+ bool c;
2174
+ /* Vector Extension. */
2175
+ bool v;
2176
+ };
2177
+
2178
+ extern struct cpuinfo_riscv_isa cpuinfo_isa;
2179
+ #endif
2180
+
2181
+ static inline bool cpuinfo_has_riscv_i(void) {
2182
+ #if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64
2183
+ return cpuinfo_isa.i;
2184
+ #else
2185
+ return false;
2186
+ #endif
2187
+ }
2188
+
2189
+ static inline bool cpuinfo_has_riscv_e(void) {
2190
+ #if CPUINFO_ARCH_RISCV32
2191
+ return cpuinfo_isa.e;
2192
+ #else
2193
+ return false;
2194
+ #endif
2195
+ }
2196
+
2197
+ static inline bool cpuinfo_has_riscv_m(void) {
2198
+ #if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64
2199
+ return cpuinfo_isa.m;
2200
+ #else
2201
+ return false;
2202
+ #endif
2203
+ }
2204
+
2205
+ static inline bool cpuinfo_has_riscv_a(void) {
2206
+ #if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64
2207
+ return cpuinfo_isa.a;
2208
+ #else
2209
+ return false;
2210
+ #endif
2211
+ }
2212
+
2213
+ static inline bool cpuinfo_has_riscv_f(void) {
2214
+ #if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64
2215
+ return cpuinfo_isa.f;
2216
+ #else
2217
+ return false;
2218
+ #endif
2219
+ }
2220
+
2221
+ static inline bool cpuinfo_has_riscv_d(void) {
2222
+ #if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64
2223
+ return cpuinfo_isa.d;
2224
+ #else
2225
+ return false;
2226
+ #endif
2227
+ }
2228
+
2229
+ static inline bool cpuinfo_has_riscv_g(void) {
2230
+ // The 'G' extension is simply shorthand for 'IMAFD'.
2231
+ return cpuinfo_has_riscv_i() && cpuinfo_has_riscv_m() && cpuinfo_has_riscv_a() && cpuinfo_has_riscv_f() &&
2232
+ cpuinfo_has_riscv_d();
2233
+ }
2234
+
2235
+ static inline bool cpuinfo_has_riscv_c(void) {
2236
+ #if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64
2237
+ return cpuinfo_isa.c;
2238
+ #else
2239
+ return false;
2240
+ #endif
2241
+ }
2242
+
2243
+ static inline bool cpuinfo_has_riscv_v(void) {
2244
+ #if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64
2245
+ return cpuinfo_isa.v;
2246
+ #else
2247
+ return false;
2248
+ #endif
2249
+ }
2250
+
2251
+ const struct cpuinfo_processor* CPUINFO_ABI cpuinfo_get_processors(void);
2252
+ const struct cpuinfo_core* CPUINFO_ABI cpuinfo_get_cores(void);
2253
+ const struct cpuinfo_cluster* CPUINFO_ABI cpuinfo_get_clusters(void);
2254
+ const struct cpuinfo_package* CPUINFO_ABI cpuinfo_get_packages(void);
2255
+ const struct cpuinfo_uarch_info* CPUINFO_ABI cpuinfo_get_uarchs(void);
2256
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l1i_caches(void);
2257
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l1d_caches(void);
2258
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l2_caches(void);
2259
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l3_caches(void);
2260
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l4_caches(void);
2261
+
2262
+ const struct cpuinfo_processor* CPUINFO_ABI cpuinfo_get_processor(uint32_t index);
2263
+ const struct cpuinfo_core* CPUINFO_ABI cpuinfo_get_core(uint32_t index);
2264
+ const struct cpuinfo_cluster* CPUINFO_ABI cpuinfo_get_cluster(uint32_t index);
2265
+ const struct cpuinfo_package* CPUINFO_ABI cpuinfo_get_package(uint32_t index);
2266
+ const struct cpuinfo_uarch_info* CPUINFO_ABI cpuinfo_get_uarch(uint32_t index);
2267
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l1i_cache(uint32_t index);
2268
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l1d_cache(uint32_t index);
2269
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l2_cache(uint32_t index);
2270
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l3_cache(uint32_t index);
2271
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l4_cache(uint32_t index);
2272
+
2273
+ uint32_t CPUINFO_ABI cpuinfo_get_processors_count(void);
2274
+ uint32_t CPUINFO_ABI cpuinfo_get_cores_count(void);
2275
+ uint32_t CPUINFO_ABI cpuinfo_get_clusters_count(void);
2276
+ uint32_t CPUINFO_ABI cpuinfo_get_packages_count(void);
2277
+ uint32_t CPUINFO_ABI cpuinfo_get_uarchs_count(void);
2278
+ uint32_t CPUINFO_ABI cpuinfo_get_l1i_caches_count(void);
2279
+ uint32_t CPUINFO_ABI cpuinfo_get_l1d_caches_count(void);
2280
+ uint32_t CPUINFO_ABI cpuinfo_get_l2_caches_count(void);
2281
+ uint32_t CPUINFO_ABI cpuinfo_get_l3_caches_count(void);
2282
+ uint32_t CPUINFO_ABI cpuinfo_get_l4_caches_count(void);
2283
+
2284
+ /**
2285
+ * Returns upper bound on cache size.
2286
+ */
2287
+ uint32_t CPUINFO_ABI cpuinfo_get_max_cache_size(void);
2288
+
2289
+ /**
2290
+ * Identify the logical processor that executes the current thread.
2291
+ *
2292
+ * There is no guarantee that the thread will stay on the same logical processor
2293
+ * for any time. Callers should treat the result as only a hint, and be prepared
2294
+ * to handle NULL return value.
2295
+ */
2296
+ const struct cpuinfo_processor* CPUINFO_ABI cpuinfo_get_current_processor(void);
2297
+
2298
+ /**
2299
+ * Identify the core that executes the current thread.
2300
+ *
2301
+ * There is no guarantee that the thread will stay on the same core for any
2302
+ * time. Callers should treat the result as only a hint, and be prepared to
2303
+ * handle NULL return value.
2304
+ */
2305
+ const struct cpuinfo_core* CPUINFO_ABI cpuinfo_get_current_core(void);
2306
+
2307
+ /**
2308
+ * Identify the microarchitecture index of the core that executes the current
2309
+ * thread. If the system does not support such identification, the function
2310
+ * returns 0.
2311
+ *
2312
+ * There is no guarantee that the thread will stay on the same type of core for
2313
+ * any time. Callers should treat the result as only a hint.
2314
+ */
2315
+ uint32_t CPUINFO_ABI cpuinfo_get_current_uarch_index(void);
2316
+
2317
+ /**
2318
+ * Identify the microarchitecture index of the core that executes the current
2319
+ * thread. If the system does not support such identification, the function
2320
+ * returns the user-specified default value.
2321
+ *
2322
+ * There is no guarantee that the thread will stay on the same type of core for
2323
+ * any time. Callers should treat the result as only a hint.
2324
+ */
2325
+ uint32_t CPUINFO_ABI cpuinfo_get_current_uarch_index_with_default(uint32_t default_uarch_index);
2326
+
2327
+ #ifdef __cplusplus
2328
+ } /* extern "C" */
2329
+ #endif
2330
+
2331
+ #endif /* CPUINFO_H */
deps/exla/cache/xla_extension/include/_virtual_includes/fft/ducc/google/threading.h ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2023 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef THIRD_PARTY_DUCC_GOOGLE_THREADING_H_
17
+ #define THIRD_PARTY_DUCC_GOOGLE_THREADING_H_
18
+
19
+ #include "ducc/src/ducc0/infra/threading.h"
20
+ #include "unsupported/Eigen/CXX11/ThreadPool"
21
+
22
+ namespace ducc0 {
23
+ namespace google {
24
+
25
+ using std::size_t;
26
+
27
+ // Pseudo thread-pool for single-threaded execution.
28
+ class NoThreadPool : public ducc0::detail_threading::thread_pool {
29
+ public:
30
+ size_t nthreads() const override { return 1; }
31
+ size_t adjust_nthreads(size_t nthreads_in) const override { return 1; };
32
+ void submit(std::function<void()> work) override { work(); }
33
+ };
34
+
35
+ // Thread-pool wrapper around Eigen's ThreadPool.
36
+ class EigenThreadPool : public ducc0::detail_threading::thread_pool {
37
+ public:
38
+ EigenThreadPool(Eigen::ThreadPoolInterface& pool) : pool_{&pool} {}
39
+ size_t nthreads() const override { return pool_->NumThreads(); }
40
+ size_t adjust_nthreads(size_t nthreads_in) const override {
41
+ // If called by a thread in the pool, return 1
42
+ if (pool_->CurrentThreadId() >= 0) {
43
+ return 1;
44
+ } else if (nthreads_in == 0) {
45
+ return pool_->NumThreads();
46
+ }
47
+ return std::min<size_t>(nthreads_in, pool_->NumThreads());
48
+ };
49
+ void submit(std::function<void()> work) override {
50
+ pool_->Schedule(std::move(work));
51
+ }
52
+
53
+ private:
54
+ Eigen::ThreadPoolInterface* pool_;
55
+ };
56
+
57
+ } // namespace google
58
+ } // namespace ducc0
59
+
60
+ #endif // THIRD_PARTY_DUCC_GOOGLE_THREADING_H_
deps/exla/cache/xla_extension/include/_virtual_includes/fft/ducc/src/ducc0/fft/fft.h ADDED
@@ -0,0 +1,1002 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ This file is part of the ducc FFT library
3
+
4
+ Copyright (C) 2010-2023 Max-Planck-Society
5
+ Copyright (C) 2019 Peter Bell
6
+
7
+ Authors: Martin Reinecke, Peter Bell
8
+ */
9
+
10
+ /* SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0-or-later */
11
+
12
+ /*
13
+ All rights reserved.
14
+
15
+ Redistribution and use in source and binary forms, with or without modification,
16
+ are permitted provided that the following conditions are met:
17
+
18
+ * Redistributions of source code must retain the above copyright notice, this
19
+ list of conditions and the following disclaimer.
20
+ * Redistributions in binary form must reproduce the above copyright notice, this
21
+ list of conditions and the following disclaimer in the documentation and/or
22
+ other materials provided with the distribution.
23
+ * Neither the name of the copyright holder nor the names of its contributors may
24
+ be used to endorse or promote products derived from this software without
25
+ specific prior written permission.
26
+
27
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
28
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
29
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
30
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
31
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
32
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
33
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
34
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
36
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37
+ */
38
+
39
+ /*
40
+ * This code is free software; you can redistribute it and/or modify
41
+ * it under the terms of the GNU General Public License as published by
42
+ * the Free Software Foundation; either version 2 of the License, or
43
+ * (at your option) any later version.
44
+ *
45
+ * This code is distributed in the hope that it will be useful,
46
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
47
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
48
+ * GNU General Public License for more details.
49
+ *
50
+ * You should have received a copy of the GNU General Public License
51
+ * along with this code; if not, write to the Free Software
52
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
53
+ */
54
+
55
+ #ifndef DUCC0_FFT_H
56
+ #define DUCC0_FFT_H
57
+
58
+ #include <cstddef>
59
+ #include <typeindex>
60
+ #include <memory>
61
+ #include <vector>
62
+ #include <complex>
63
+ #include "ducc0/infra/error_handling.h"
64
+ #include "ducc0/infra/aligned_array.h"
65
+ #include "ducc0/infra/mav.h"
66
+ #include "ducc0/math/cmplx.h"
67
+ #include "ducc0/math/unity_roots.h"
68
+
69
+ namespace ducc0 {
70
+
71
+ namespace detail_fft {
72
+
73
+ using namespace std;
74
+
75
+ template<typename T> using Troots = shared_ptr<const UnityRoots<T,Cmplx<T>>>;
76
+ template<typename T> inline auto tidx() { return type_index(typeid(T)); }
77
+
78
+ template<typename T> inline void PM(T &a, T &b, T c, T d)
79
+ { a=c+d; b=c-d; }
80
+ template<typename T> inline void PMINPLACE(T &a, T &b)
81
+ { T t = a; a+=b; b=t-b; }
82
+ template<typename T> inline void MPINPLACE(T &a, T &b)
83
+ { T t = a; a-=b; b=t+b; }
84
+ template<bool fwd, typename T, typename T2> void special_mul (const Cmplx<T> &v1, const Cmplx<T2> &v2, Cmplx<T> &res)
85
+ {
86
+ res = fwd ? Cmplx<T>(v1.r*v2.r+v1.i*v2.i, v1.i*v2.r-v1.r*v2.i)
87
+ : Cmplx<T>(v1.r*v2.r-v1.i*v2.i, v1.r*v2.i+v1.i*v2.r);
88
+ }
89
+
90
+ struct util1d // hack to avoid duplicate symbols
91
+ {
92
+ /* returns the smallest composite of 2, 3, 5, 7 and 11 which is >= n */
93
+ DUCC0_NOINLINE static size_t good_size_cmplx(size_t n)
94
+ {
95
+ if (n<=12) return n;
96
+
97
+ size_t bestfac=2*n;
98
+ for (size_t f11=1; f11<bestfac; f11*=11)
99
+ for (size_t f117=f11; f117<bestfac; f117*=7)
100
+ for (size_t f1175=f117; f1175<bestfac; f1175*=5)
101
+ {
102
+ size_t x=f1175;
103
+ while (x<n) x*=2;
104
+ for (;;)
105
+ {
106
+ if (x<n)
107
+ x*=3;
108
+ else if (x>n)
109
+ {
110
+ if (x<bestfac) bestfac=x;
111
+ if (x&1) break;
112
+ x>>=1;
113
+ }
114
+ else
115
+ return n;
116
+ }
117
+ }
118
+ return bestfac;
119
+ }
120
+ /* returns the smallest composite of 2, 3, 5, 7 and 11 which is >= n
121
+ and a multiple of required_factor. */
122
+ DUCC0_NOINLINE static size_t good_size_cmplx(size_t n,
123
+ size_t required_factor)
124
+ {
125
+ MR_assert(required_factor>=1, "required_factor must not be 0");
126
+ return good_size_cmplx((n+required_factor-1)/required_factor) * required_factor;
127
+ }
128
+
129
+ /* returns the smallest composite of 2, 3, 5 which is >= n */
130
+ DUCC0_NOINLINE static size_t good_size_real(size_t n)
131
+ {
132
+ if (n<=6) return n;
133
+
134
+ size_t bestfac=2*n;
135
+ for (size_t f5=1; f5<bestfac; f5*=5)
136
+ {
137
+ size_t x = f5;
138
+ while (x<n) x *= 2;
139
+ for (;;)
140
+ {
141
+ if (x<n)
142
+ x*=3;
143
+ else if (x>n)
144
+ {
145
+ if (x<bestfac) bestfac=x;
146
+ if (x&1) break;
147
+ x>>=1;
148
+ }
149
+ else
150
+ return n;
151
+ }
152
+ }
153
+ return bestfac;
154
+ }
155
+ /* returns the smallest composite of 2, 3, 5 which is >= n
156
+ and a multiple of required_factor. */
157
+ DUCC0_NOINLINE static size_t good_size_real(size_t n,
158
+ size_t required_factor)
159
+ {
160
+ MR_assert(required_factor>=1, "required_factor must not be 0");
161
+ return good_size_real((n+required_factor-1)/required_factor) * required_factor;
162
+ }
163
+
164
+ DUCC0_NOINLINE static vector<size_t> prime_factors(size_t N)
165
+ {
166
+ MR_assert(N>0, "need a positive number");
167
+ vector<size_t> factors;
168
+ while ((N&1)==0)
169
+ { N>>=1; factors.push_back(2); }
170
+ for (size_t divisor=3; divisor*divisor<=N; divisor+=2)
171
+ while ((N%divisor)==0)
172
+ {
173
+ factors.push_back(divisor);
174
+ N/=divisor;
175
+ }
176
+ if (N>1) factors.push_back(N);
177
+ return factors;
178
+ }
179
+ };
180
+
181
+ // T: "type", f/c: "float/complex", s/v: "scalar/vector"
182
+ template <typename Tfs> class cfftpass
183
+ {
184
+ public:
185
+ virtual ~cfftpass(){}
186
+ using Tcs = Cmplx<Tfs>;
187
+
188
+ // number of Tcd values required as scratch space during "exec"
189
+ // will be provided in "buf"
190
+ virtual size_t bufsize() const = 0;
191
+ virtual bool needs_copy() const = 0;
192
+ virtual void *exec(const type_index &ti, void *in, void *copy, void *buf,
193
+ bool fwd, size_t nthreads=1) const = 0;
194
+
195
+ static vector<size_t> factorize(size_t N)
196
+ {
197
+ MR_assert(N>0, "need a positive number");
198
+ vector<size_t> factors;
199
+ factors.reserve(15);
200
+ while ((N&7)==0)
201
+ { factors.push_back(8); N>>=3; }
202
+ while ((N&3)==0)
203
+ { factors.push_back(4); N>>=2; }
204
+ if ((N&1)==0)
205
+ {
206
+ N>>=1;
207
+ // factor 2 should be at the front of the factor list
208
+ factors.push_back(2);
209
+ swap(factors[0], factors.back());
210
+ }
211
+ for (size_t divisor=3; divisor*divisor<=N; divisor+=2)
212
+ while ((N%divisor)==0)
213
+ {
214
+ factors.push_back(divisor);
215
+ N/=divisor;
216
+ }
217
+ if (N>1) factors.push_back(N);
218
+ return factors;
219
+ }
220
+
221
+ static shared_ptr<cfftpass> make_pass(size_t l1, size_t ido, size_t ip,
222
+ const Troots<Tfs> &roots, bool vectorize=false);
223
+ static shared_ptr<cfftpass> make_pass(size_t ip, bool vectorize=false)
224
+ {
225
+ return make_pass(1,1,ip,make_shared<UnityRoots<Tfs,Cmplx<Tfs>>>(ip),
226
+ vectorize);
227
+ }
228
+ };
229
+
230
+ template <typename Tfs> class rfftpass
231
+ {
232
+ public:
233
+ virtual ~rfftpass(){}
234
+
235
+ // number of Tfd values required as scratch space during "exec"
236
+ // will be provided in "buf"
237
+ virtual size_t bufsize() const = 0;
238
+ virtual bool needs_copy() const = 0;
239
+ virtual void *exec(const type_index &ti, void *in, void *copy, void *buf,
240
+ bool fwd, size_t nthreads=1) const = 0;
241
+
242
+ static vector<size_t> factorize(size_t N)
243
+ {
244
+ MR_assert(N>0, "need a positive number");
245
+ vector<size_t> factors;
246
+ while ((N&3)==0)
247
+ { factors.push_back(4); N>>=2; }
248
+ if ((N&1)==0)
249
+ {
250
+ N>>=1;
251
+ // factor 2 should be at the front of the factor list
252
+ factors.push_back(2);
253
+ swap(factors[0], factors.back());
254
+ }
255
+ for (size_t divisor=3; divisor*divisor<=N; divisor+=2)
256
+ while ((N%divisor)==0)
257
+ {
258
+ factors.push_back(divisor);
259
+ N/=divisor;
260
+ }
261
+ if (N>1) factors.push_back(N);
262
+ return factors;
263
+ }
264
+
265
+ static shared_ptr<rfftpass> make_pass(size_t l1, size_t ido, size_t ip,
266
+ const Troots<Tfs> &roots, bool vectorize=false);
267
+ static shared_ptr<rfftpass> make_pass(size_t ip, bool vectorize=false)
268
+ {
269
+ return make_pass(1,1,ip,make_shared<UnityRoots<Tfs,Cmplx<Tfs>>>(ip),
270
+ vectorize);
271
+ }
272
+ };
273
+
274
+ template<typename T> using Tcpass = shared_ptr<cfftpass<T>>;
275
+ template<typename T> using Trpass = shared_ptr<rfftpass<T>>;
276
+
277
+ template<typename Tfs> class pocketfft_c
278
+ {
279
+ private:
280
+ size_t N;
281
+ size_t critbuf;
282
+ Tcpass<Tfs> plan;
283
+
284
+ public:
285
+ pocketfft_c(size_t n, bool vectorize=false)
286
+ : N(n), critbuf(((N&1023)==0) ? 16 : 0),
287
+ plan(cfftpass<Tfs>::make_pass(n,vectorize)) {}
288
+ size_t length() const { return N; }
289
+ size_t bufsize() const { return N*plan->needs_copy()+2*critbuf+plan->bufsize(); }
290
+ template<typename Tfd> DUCC0_NOINLINE Cmplx<Tfd> *exec(Cmplx<Tfd> *in, Cmplx<Tfd> *buf,
291
+ Tfs fct, bool fwd, size_t nthreads=1) const
292
+ {
293
+ static const auto tic = tidx<Cmplx<Tfd> *>();
294
+ auto res = static_cast<Cmplx<Tfd> *>(plan->exec(tic,
295
+ in, buf+critbuf+plan->bufsize(), buf+critbuf, fwd, nthreads));
296
+ if (fct!=Tfs(1))
297
+ for (size_t i=0; i<N; ++i) res[i]*=fct;
298
+ return res;
299
+ }
300
+ template<typename Tfd> DUCC0_NOINLINE void exec_copyback(Cmplx<Tfd> *in, Cmplx<Tfd> *buf,
301
+ Tfs fct, bool fwd, size_t nthreads=1) const
302
+ {
303
+ static const auto tic = tidx<Cmplx<Tfd> *>();
304
+ auto res = static_cast<Cmplx<Tfd> *>(plan->exec(tic,
305
+ in, buf, buf+N*plan->needs_copy(), fwd, nthreads));
306
+ if (res==in)
307
+ {
308
+ if (fct!=Tfs(1))
309
+ for (size_t i=0; i<N; ++i) in[i]*=fct;
310
+ }
311
+ else
312
+ {
313
+ if (fct!=Tfs(1))
314
+ for (size_t i=0; i<N; ++i) in[i]=res[i]*fct;
315
+ else
316
+ copy_n(res, N, in);
317
+ }
318
+ }
319
+ template<typename Tfd> DUCC0_NOINLINE void exec(Cmplx<Tfd> *in, Tfs fct, bool fwd, size_t nthreads=1) const
320
+ {
321
+ aligned_array<Cmplx<Tfd>> buf(N*plan->needs_copy()+plan->bufsize());
322
+ exec_copyback(in, buf.data(), fct, fwd, nthreads);
323
+ }
324
+ };
325
+
326
+ template<typename Tfs> class pocketfft_r
327
+ {
328
+ private:
329
+ size_t N;
330
+ Trpass<Tfs> plan;
331
+
332
+ public:
333
+ pocketfft_r(size_t n, bool vectorize=false)
334
+ : N(n), plan(rfftpass<Tfs>::make_pass(n,vectorize)) {}
335
+ size_t length() const { return N; }
336
+ size_t bufsize() const { return N*plan->needs_copy()+plan->bufsize(); }
337
+ template<typename Tfd> DUCC0_NOINLINE Tfd *exec(Tfd *in, Tfd *buf, Tfs fct,
338
+ bool fwd, size_t nthreads=1) const
339
+ {
340
+ static const auto tifd = tidx<Tfd *>();
341
+ auto res = static_cast<Tfd *>(plan->exec(tifd, in, buf,
342
+ buf+N*plan->needs_copy(), fwd, nthreads));
343
+ if (fct!=Tfs(1))
344
+ for (size_t i=0; i<N; ++i) res[i]*=fct;
345
+ return res;
346
+ }
347
+ template<typename Tfd> DUCC0_NOINLINE void exec_copyback(Tfd *in, Tfd *buf,
348
+ Tfs fct, bool fwd, size_t nthreads=1) const
349
+ {
350
+ static const auto tifd = tidx<Tfd *>();
351
+ auto res = static_cast<Tfd *>(plan->exec(tifd, in, buf,
352
+ buf+N*plan->needs_copy(), fwd, nthreads));
353
+ if (res==in)
354
+ {
355
+ if (fct!=Tfs(1))
356
+ for (size_t i=0; i<N; ++i) in[i]*=fct;
357
+ }
358
+ else
359
+ {
360
+ if (fct!=Tfs(1))
361
+ for (size_t i=0; i<N; ++i) in[i]=res[i]*fct;
362
+ else
363
+ copy_n(res, N, in);
364
+ }
365
+ }
366
+ template<typename Tfd> DUCC0_NOINLINE void exec(Tfd *in, Tfs fct, bool fwd,
367
+ size_t nthreads=1) const
368
+ {
369
+ aligned_array<Tfd> buf(N*plan->needs_copy()+plan->bufsize());
370
+ exec_copyback(in, buf.data(), fct, fwd, nthreads);
371
+ }
372
+ };
373
+
374
+ template<typename Tfs> class pocketfft_hartley
375
+ {
376
+ private:
377
+ size_t N;
378
+ Trpass<Tfs> plan;
379
+
380
+ public:
381
+ pocketfft_hartley(size_t n, bool vectorize=false)
382
+ : N(n), plan(rfftpass<Tfs>::make_pass(n,vectorize)) {}
383
+ size_t length() const { return N; }
384
+ size_t bufsize() const { return N+plan->bufsize(); }
385
+ template<typename Tfd> DUCC0_NOINLINE Tfd *exec(Tfd *in, Tfd *buf, Tfs fct,
386
+ size_t nthreads=1) const
387
+ {
388
+ static const auto tifd = tidx<Tfd *>();
389
+ auto res = static_cast<Tfd *>(plan->exec(tifd,
390
+ in, buf, buf+N, true, nthreads));
391
+ auto res2 = (res==buf) ? in : buf;
392
+ res2[0] = fct*res[0];
393
+ size_t i=1, i1=1, i2=N-1;
394
+ for (i=1; i<N-1; i+=2, ++i1, --i2)
395
+ {
396
+ res2[i1] = fct*(res[i]+res[i+1]);
397
+ res2[i2] = fct*(res[i]-res[i+1]);
398
+ }
399
+ if (i<N)
400
+ res2[i1] = fct*res[i];
401
+
402
+ return res2;
403
+ }
404
+ template<typename Tfd> DUCC0_NOINLINE void exec_copyback(Tfd *in, Tfd *buf,
405
+ Tfs fct, size_t nthreads=1) const
406
+ {
407
+ auto res = exec(in, buf, fct, nthreads);
408
+ if (res!=in)
409
+ copy_n(res, N, in);
410
+ }
411
+ template<typename Tfd> DUCC0_NOINLINE void exec(Tfd *in, Tfs fct,
412
+ size_t nthreads=1) const
413
+ {
414
+ aligned_array<Tfd> buf(N+plan->bufsize());
415
+ exec_copyback(in, buf.data(), fct, nthreads);
416
+ }
417
+ };
418
+
419
+ template<typename Tfs> class pocketfft_fht
420
+ {
421
+ private:
422
+ size_t N;
423
+ Trpass<Tfs> plan;
424
+
425
+ public:
426
+ pocketfft_fht(size_t n, bool vectorize=false)
427
+ : N(n), plan(rfftpass<Tfs>::make_pass(n,vectorize)) {}
428
+ size_t length() const { return N; }
429
+ size_t bufsize() const { return N+plan->bufsize(); }
430
+ template<typename Tfd> DUCC0_NOINLINE Tfd *exec(Tfd *in, Tfd *buf, Tfs fct,
431
+ size_t nthreads=1) const
432
+ {
433
+ static const auto tifd = tidx<Tfd *>();
434
+ auto res = static_cast<Tfd *>(plan->exec(tifd,
435
+ in, buf, buf+N, true, nthreads));
436
+ auto res2 = (res==buf) ? in : buf;
437
+ res2[0] = fct*res[0];
438
+ size_t i=1, i1=1, i2=N-1;
439
+ for (i=1; i<N-1; i+=2, ++i1, --i2)
440
+ {
441
+ res2[i1] = fct*(res[i]-res[i+1]);
442
+ res2[i2] = fct*(res[i]+res[i+1]);
443
+ }
444
+ if (i<N)
445
+ res2[i1] = fct*res[i];
446
+
447
+ return res2;
448
+ }
449
+ template<typename Tfd> DUCC0_NOINLINE void exec_copyback(Tfd *in, Tfd *buf,
450
+ Tfs fct, size_t nthreads=1) const
451
+ {
452
+ auto res = exec(in, buf, fct, nthreads);
453
+ if (res!=in)
454
+ copy_n(res, N, in);
455
+ }
456
+ template<typename Tfd> DUCC0_NOINLINE void exec(Tfd *in, Tfs fct,
457
+ size_t nthreads=1) const
458
+ {
459
+ aligned_array<Tfd> buf(N+plan->bufsize());
460
+ exec_copyback(in, buf.data(), fct, nthreads);
461
+ }
462
+ };
463
+
464
+ // R2R transforms using FFTW's halfcomplex format
465
+ template<typename Tfs> class pocketfft_fftw
466
+ {
467
+ private:
468
+ size_t N;
469
+ Trpass<Tfs> plan;
470
+
471
+ public:
472
+ pocketfft_fftw(size_t n, bool vectorize=false)
473
+ : N(n), plan(rfftpass<Tfs>::make_pass(n,vectorize)) {}
474
+ size_t length() const { return N; }
475
+ size_t bufsize() const { return N+plan->bufsize(); }
476
+ template<typename Tfd> DUCC0_NOINLINE Tfd *exec(Tfd *in, Tfd *buf, Tfs fct,
477
+ bool fwd, size_t nthreads=1) const
478
+ {
479
+ static const auto tifd = tidx<Tfd *>();
480
+ auto res = in;
481
+ auto res2 = buf;
482
+ if (!fwd) // go to FFTPACK halfcomplex order
483
+ {
484
+ res2[0] = fct*res[0];
485
+ size_t i=1, i1=1, i2=N-1;
486
+ for (i=1; i<N-1; i+=2, ++i1, --i2)
487
+ {
488
+ res2[i] = fct*res[i1];
489
+ res2[i+1] = fct*res[i2];
490
+ }
491
+ if (i<N)
492
+ res2[i] = fct*res[i1];
493
+ swap(res, res2);
494
+ }
495
+ res = static_cast<Tfd *>(plan->exec(tifd,
496
+ res, res2, buf+N, fwd, nthreads));
497
+ if (!fwd) return res;
498
+
499
+ // go to FFTW halfcomplex order
500
+ res2 = (res==buf) ? in : buf;
501
+ res2[0] = fct*res[0];
502
+ size_t i=1, i1=1, i2=N-1;
503
+ for (i=1; i<N-1; i+=2, ++i1, --i2)
504
+ {
505
+ res2[i1] = fct*res[i];
506
+ res2[i2] = fct*res[i+1];
507
+ }
508
+ if (i<N)
509
+ res2[i1] = fct*res[i];
510
+
511
+ return res2;
512
+ }
513
+ template<typename Tfd> DUCC0_NOINLINE void exec_copyback(Tfd *in, Tfd *buf,
514
+ Tfs fct, bool fwd, size_t nthreads=1) const
515
+ {
516
+ auto res = exec(in, buf, fct, fwd, nthreads);
517
+ if (res!=in)
518
+ copy_n(res, N, in);
519
+ }
520
+ template<typename Tfd> DUCC0_NOINLINE void exec(Tfd *in, Tfs fct, bool fwd,
521
+ size_t nthreads=1) const
522
+ {
523
+ aligned_array<Tfd> buf(N+plan->bufsize());
524
+ exec_copyback(in, buf.data(), fct, fwd, nthreads);
525
+ }
526
+ };
527
+
528
+ //
529
+ // sine/cosine transforms
530
+ //
531
+
532
+ template<typename T0> class T_dct1
533
+ {
534
+ private:
535
+ pocketfft_r<T0> fftplan;
536
+
537
+ public:
538
+ DUCC0_NOINLINE T_dct1(size_t length, bool /*vectorize*/=false)
539
+ : fftplan(2*(length-1)) {}
540
+
541
+ template<typename T> DUCC0_NOINLINE T *exec(T c[], T buf[], T0 fct, bool ortho,
542
+ int /*type*/, bool /*cosine*/, size_t nthreads=1) const
543
+ {
544
+ constexpr T0 sqrt2=T0(1.414213562373095048801688724209698L);
545
+ size_t N=fftplan.length(), n=N/2+1;
546
+ if (ortho)
547
+ { c[0]*=sqrt2; c[n-1]*=sqrt2; }
548
+ auto tmp=&buf[0];
549
+ tmp[0] = c[0];
550
+ for (size_t i=1; i<n; ++i)
551
+ tmp[i] = tmp[N-i] = c[i];
552
+ auto res = fftplan.exec(tmp, &buf[N], fct, true, nthreads);
553
+ c[0] = res[0];
554
+ for (size_t i=1; i<n; ++i)
555
+ c[i] = res[2*i-1];
556
+ if (ortho)
557
+ { c[0]*=sqrt2*T0(0.5); c[n-1]*=sqrt2*T0(0.5); }
558
+ return c;
559
+ }
560
+ template<typename T> DUCC0_NOINLINE void exec_copyback(T c[], T buf[], T0 fct, bool ortho,
561
+ int /*type*/, bool /*cosine*/, size_t nthreads=1) const
562
+ {
563
+ exec(c, buf, fct, ortho, 1, true, nthreads);
564
+ }
565
+ template<typename T> DUCC0_NOINLINE void exec(T c[], T0 fct, bool ortho,
566
+ int /*type*/, bool /*cosine*/, size_t nthreads=1) const
567
+ {
568
+ aligned_array<T> buf(bufsize());
569
+ exec_copyback(c, buf.data(), fct, ortho, 1, true, nthreads);
570
+ }
571
+
572
+ size_t length() const { return fftplan.length()/2+1; }
573
+ size_t bufsize() const { return fftplan.length()+fftplan.bufsize(); }
574
+ };
575
+
576
+ template<typename T0> class T_dst1
577
+ {
578
+ private:
579
+ pocketfft_r<T0> fftplan;
580
+
581
+ public:
582
+ DUCC0_NOINLINE T_dst1(size_t length, bool /*vectorize*/=false)
583
+ : fftplan(2*(length+1)) {}
584
+
585
+ template<typename T> DUCC0_NOINLINE T *exec(T c[], T buf[], T0 fct,
586
+ bool /*ortho*/, int /*type*/, bool /*cosine*/, size_t nthreads=1) const
587
+ {
588
+ size_t N=fftplan.length(), n=N/2-1;
589
+ auto tmp = &buf[0];
590
+ tmp[0] = tmp[n+1] = c[0]*0;
591
+ for (size_t i=0; i<n; ++i)
592
+ { tmp[i+1]=c[i]; tmp[N-1-i]=-c[i]; }
593
+ auto res = fftplan.exec(tmp, buf+N, fct, true, nthreads);
594
+ for (size_t i=0; i<n; ++i)
595
+ c[i] = -res[2*i+2];
596
+ return c;
597
+ }
598
+ template<typename T> DUCC0_NOINLINE void exec_copyback(T c[], T buf[], T0 fct,
599
+ bool /*ortho*/, int /*type*/, bool /*cosine*/, size_t nthreads=1) const
600
+ {
601
+ exec(c, buf, fct, true, 1, false, nthreads);
602
+ }
603
+ template<typename T> DUCC0_NOINLINE void exec(T c[], T0 fct,
604
+ bool /*ortho*/, int /*type*/, bool /*cosine*/, size_t nthreads) const
605
+ {
606
+ aligned_array<T> buf(bufsize());
607
+ exec_copyback(c, buf.data(), fct, true, 1, false, nthreads);
608
+ }
609
+
610
+ size_t length() const { return fftplan.length()/2-1; }
611
+ size_t bufsize() const { return fftplan.length()+fftplan.bufsize(); }
612
+ };
613
+
614
+ template<typename T0> class T_dcst23
615
+ {
616
+ private:
617
+ pocketfft_r<T0> fftplan;
618
+ std::vector<T0> twiddle;
619
+
620
+ public:
621
+ DUCC0_NOINLINE T_dcst23(size_t length, bool /*vectorize*/=false)
622
+ : fftplan(length), twiddle(length)
623
+ {
624
+ UnityRoots<T0,Cmplx<T0>> tw(4*length);
625
+ for (size_t i=0; i<length; ++i)
626
+ twiddle[i] = tw[i+1].r;
627
+ }
628
+
629
+ template<typename T> DUCC0_NOINLINE T *exec(T c[], T buf[], T0 fct, bool ortho,
630
+ int type, bool cosine, size_t nthreads=1) const
631
+ {
632
+ constexpr T0 sqrt2=T0(1.414213562373095048801688724209698L);
633
+ size_t N=length();
634
+ size_t NS2 = (N+1)/2;
635
+ if (type==2)
636
+ {
637
+ c[0] *= 2;
638
+ if ((N&1)==0) c[N-1]*=2;
639
+ if (cosine)
640
+ for (size_t k=1; k<N-1; k+=2)
641
+ MPINPLACE(c[k+1], c[k]);
642
+ else
643
+ for (size_t k=1; k<N-1; k+=2)
644
+ PMINPLACE(c[k+1], c[k]);
645
+ if ((!cosine) && ((N&1)==0))
646
+ c[N-1] *= -1;
647
+ auto res = fftplan.exec(c, buf, fct, false, nthreads);
648
+ c[0] = res[0];
649
+ for (size_t k=1, kc=N-1; k<NS2; ++k, --kc)
650
+ {
651
+ T t1 = twiddle[k-1]*res[kc]+twiddle[kc-1]*res[k];
652
+ T t2 = twiddle[k-1]*res[k]-twiddle[kc-1]*res[kc];
653
+ c[k] = T0(0.5)*(t1+t2); c[kc]=T0(0.5)*(t1-t2);
654
+ }
655
+ if ((N&1)==0)
656
+ c[NS2] = res[NS2]*twiddle[NS2-1];
657
+ if (!cosine) // swap order completely
658
+ for (size_t k=0, kc=N-1; k<kc; ++k, --kc)
659
+ std::swap(c[k], c[kc]);
660
+ if (ortho)
661
+ cosine ? c[0]*=sqrt2*T0(0.5) : c[N-1]*=sqrt2*T0(0.5);
662
+ }
663
+ else
664
+ {
665
+ if (ortho)
666
+ cosine ? c[0]*=sqrt2 : c[N-1]*=sqrt2;
667
+ if (!cosine) // swap order completely
668
+ for (size_t k=0, kc=N-1; k<NS2; ++k, --kc)
669
+ std::swap(c[k], c[kc]);
670
+ for (size_t k=1, kc=N-1; k<NS2; ++k, --kc)
671
+ {
672
+ T t1=c[k]+c[kc], t2=c[k]-c[kc];
673
+ c[k] = twiddle[k-1]*t2+twiddle[kc-1]*t1;
674
+ c[kc]= twiddle[k-1]*t1-twiddle[kc-1]*t2;
675
+ }
676
+ if ((N&1)==0)
677
+ c[NS2] *= 2*twiddle[NS2-1];
678
+ auto res = fftplan.exec(c, buf, fct, true, nthreads);
679
+ if (res != c) // FIXME: not yet optimal
680
+ copy_n(res, N, c);
681
+ if ((!cosine) && ((N&1)==0))
682
+ c[N-1] *= -1;
683
+ if (cosine)
684
+ for (size_t k=1; k<N-1; k+=2)
685
+ MPINPLACE(c[k], c[k+1]);
686
+ else
687
+ for (size_t k=1; k<N-1; k+=2)
688
+ PMINPLACE(c[k+1], c[k]);
689
+ }
690
+ return c;
691
+ }
692
+ template<typename T> DUCC0_NOINLINE void exec_copyback(T c[], T buf[], T0 fct,
693
+ bool ortho, int type, bool cosine, size_t nthreads=1) const
694
+ {
695
+ exec(c, buf, fct, ortho, type, cosine, nthreads);
696
+ }
697
+ template<typename T> DUCC0_NOINLINE void exec(T c[], T0 fct, bool ortho,
698
+ int type, bool cosine, size_t nthreads=1) const
699
+ {
700
+ aligned_array<T> buf(bufsize());
701
+ exec(c, &buf[0], fct, ortho, type, cosine, nthreads);
702
+ }
703
+
704
+ size_t length() const { return fftplan.length(); }
705
+ size_t bufsize() const { return fftplan.bufsize(); }
706
+ };
707
+
708
+ template<typename T0> class T_dcst4
709
+ {
710
+ private:
711
+ size_t N;
712
+ std::unique_ptr<pocketfft_c<T0>> fft;
713
+ std::unique_ptr<pocketfft_r<T0>> rfft;
714
+ aligned_array<Cmplx<T0>> C2;
715
+ size_t bufsz;
716
+
717
+ public:
718
+ DUCC0_NOINLINE T_dcst4(size_t length, bool /*vectorize*/=false)
719
+ : N(length),
720
+ fft((N&1) ? nullptr : make_unique<pocketfft_c<T0>>(N/2)),
721
+ rfft((N&1)? make_unique<pocketfft_r<T0>>(N) : nullptr),
722
+ C2((N&1) ? 0 : N/2),
723
+ bufsz((N&1) ? (N+rfft->bufsize()) : (N+2*fft->bufsize()))
724
+ {
725
+ if ((N&1)==0)
726
+ {
727
+ UnityRoots<T0,Cmplx<T0>> tw(16*N);
728
+ for (size_t i=0; i<N/2; ++i)
729
+ C2[i] = tw[8*i+1].conj();
730
+ }
731
+ }
732
+
733
+ template<typename T> DUCC0_NOINLINE T *exec(T c[], T buf[], T0 fct,
734
+ bool /*ortho*/, int /*type*/, bool cosine, size_t nthreads) const
735
+ {
736
+ size_t n2 = N/2;
737
+ if (!cosine)
738
+ for (size_t k=0, kc=N-1; k<n2; ++k, --kc)
739
+ std::swap(c[k], c[kc]);
740
+ if (N&1)
741
+ {
742
+ // The following code is derived from the FFTW3 function apply_re11()
743
+ // and is released under the 3-clause BSD license with friendly
744
+ // permission of Matteo Frigo and Steven G. Johnson.
745
+
746
+ auto y = buf;
747
+ {
748
+ size_t i=0, m=n2;
749
+ for (; m<N; ++i, m+=4)
750
+ y[i] = c[m];
751
+ for (; m<2*N; ++i, m+=4)
752
+ y[i] = -c[2*N-m-1];
753
+ for (; m<3*N; ++i, m+=4)
754
+ y[i] = -c[m-2*N];
755
+ for (; m<4*N; ++i, m+=4)
756
+ y[i] = c[4*N-m-1];
757
+ for (; i<N; ++i, m+=4)
758
+ y[i] = c[m-4*N];
759
+ }
760
+
761
+ auto res = rfft->exec(y, y+N, fct, true, nthreads);
762
+ {
763
+ auto SGN = [](size_t i)
764
+ {
765
+ constexpr T0 sqrt2=T0(1.414213562373095048801688724209698L);
766
+ return (i&2) ? -sqrt2 : sqrt2;
767
+ };
768
+ c[n2] = res[0]*SGN(n2+1);
769
+ size_t i=0, i1=1, k=1;
770
+ for (; k<n2; ++i, ++i1, k+=2)
771
+ {
772
+ c[i ] = res[2*k-1]*SGN(i1) + res[2*k ]*SGN(i);
773
+ c[N -i1] = res[2*k-1]*SGN(N -i) - res[2*k ]*SGN(N -i1);
774
+ c[n2-i1] = res[2*k+1]*SGN(n2-i) - res[2*k+2]*SGN(n2-i1);
775
+ c[n2+i1] = res[2*k+1]*SGN(n2+i+2) + res[2*k+2]*SGN(n2+i1);
776
+ }
777
+ if (k == n2)
778
+ {
779
+ c[i ] = res[2*k-1]*SGN(i+1) + res[2*k]*SGN(i);
780
+ c[N-i1] = res[2*k-1]*SGN(i+2) + res[2*k]*SGN(i1);
781
+ }
782
+ }
783
+
784
+ // FFTW-derived code ends here
785
+ }
786
+ else
787
+ {
788
+ // even length algorithm from
789
+ // https://www.appletonaudio.com/blog/2013/derivation-of-fast-dct-4-algorithm-based-on-dft/
790
+ auto y2 = reinterpret_cast<Cmplx<T> *>(buf);
791
+ for(size_t i=0; i<n2; ++i)
792
+ {
793
+ y2[i].Set(c[2*i],c[N-1-2*i]);
794
+ y2[i] *= C2[i];
795
+ }
796
+
797
+ auto res = fft->exec(y2, y2+N/2, fct, true, nthreads);
798
+ for(size_t i=0, ic=n2-1; i<n2; ++i, --ic)
799
+ {
800
+ c[2*i ] = T0( 2)*(res[i ].r*C2[i ].r-res[i ].i*C2[i ].i);
801
+ c[2*i+1] = T0(-2)*(res[ic].i*C2[ic].r+res[ic].r*C2[ic].i);
802
+ }
803
+ }
804
+ if (!cosine)
805
+ for (size_t k=1; k<N; k+=2)
806
+ c[k] = -c[k];
807
+ return c;
808
+ }
809
+ template<typename T> DUCC0_NOINLINE void exec_copyback(T c[], T buf[], T0 fct,
810
+ bool /*ortho*/, int /*type*/, bool cosine, size_t nthreads=1) const
811
+ {
812
+ exec(c, buf, fct, true, 4, cosine, nthreads);
813
+ }
814
+ template<typename T> DUCC0_NOINLINE void exec(T c[], T0 fct,
815
+ bool /*ortho*/, int /*type*/, bool cosine, size_t nthreads=1) const
816
+ {
817
+ aligned_array<T> buf(bufsize());
818
+ exec(c, &buf[0], fct, true, 4, cosine, nthreads);
819
+ }
820
+
821
+ size_t length() const { return N; }
822
+ size_t bufsize() const { return bufsz; }
823
+ };
824
+
825
+ using shape_t=fmav_info::shape_t;
826
+ using stride_t=fmav_info::stride_t;
827
+
828
+ constexpr bool FORWARD = true,
829
+ BACKWARD = false;
830
+
831
+ /// Complex-to-complex Fast Fourier Transform
832
+ /** This executes a Fast Fourier Transform on \a in and stores the result in
833
+ * \a out.
834
+ *
835
+ * \a in and \a out must have identical shapes; they may point to the same
836
+ * memory; in this case their strides must also be identical.
837
+ *
838
+ * \a axes specifies the axes over which the transform is carried out.
839
+ *
840
+ * If \a forward is true, a minus sign will be used in the exponent.
841
+ *
842
+ * No normalization factors will be applied by default; if multiplication by
843
+ * a constant is desired, it can be supplied in \a fct.
844
+ *
845
+ * If the underlying array has more than one dimension, the computation will
846
+ * be distributed over \a nthreads threads.
847
+ */
848
+ template<typename T> DUCC0_NOINLINE void c2c(const cfmav<std::complex<T>> &in,
849
+ const vfmav<std::complex<T>> &out, const shape_t &axes, bool forward,
850
+ T fct, size_t nthreads=1);
851
+
852
+ /// Fast Discrete Cosine Transform
853
+ /** This executes a DCT on \a in and stores the result in \a out.
854
+ *
855
+ * \a in and \a out must have identical shapes; they may point to the same
856
+ * memory; in this case their strides must also be identical.
857
+ *
858
+ * \a axes specifies the axes over which the transform is carried out.
859
+ *
860
+ * If \a forward is true, a DCT is computed, otherwise an inverse DCT.
861
+ *
862
+ * \a type specifies the desired type (1-4) of the transform.
863
+ *
864
+ * No normalization factors will be applied by default; if multiplication by
865
+ * a constant is desired, it can be supplied in \a fct.
866
+ *
867
+ * If \a ortho is true, the first and last array entries are corrected (if
868
+ * necessary) to allow an orthonormalized transform.
869
+ *
870
+ * If the underlying array has more than one dimension, the computation will
871
+ * be distributed over \a nthreads threads.
872
+ */
873
+ template<typename T> DUCC0_NOINLINE void dct(const cfmav<T> &in, const vfmav<T> &out,
874
+ const shape_t &axes, int type, T fct, bool ortho, size_t nthreads=1);
875
+
876
+ /// Fast Discrete Sine Transform
877
+ /** This executes a DST on \a in and stores the result in \a out.
878
+ *
879
+ * \a in and \a out must have identical shapes; they may point to the same
880
+ * memory; in this case their strides must also be identical.
881
+ *
882
+ * \a axes specifies the axes over which the transform is carried out.
883
+ *
884
+ * If \a forward is true, a DST is computed, otherwise an inverse DST.
885
+ *
886
+ * \a type specifies the desired type (1-4) of the transform.
887
+ *
888
+ * No normalization factors will be applied by default; if multiplication by
889
+ * a constant is desired, it can be supplied in \a fct.
890
+ *
891
+ * If \a ortho is true, the first and last array entries are corrected (if
892
+ * necessary) to allow an orthonormalized transform.
893
+ *
894
+ * If the underlying array has more than one dimension, the computation will
895
+ * be distributed over \a nthreads threads.
896
+ */
897
+ template<typename T> DUCC0_NOINLINE void dst(const cfmav<T> &in, const vfmav<T> &out,
898
+ const shape_t &axes, int type, T fct, bool ortho, size_t nthreads=1);
899
+
900
+ template<typename T> DUCC0_NOINLINE void r2c(const cfmav<T> &in,
901
+ const vfmav<std::complex<T>> &out, size_t axis, bool forward, T fct,
902
+ size_t nthreads=1);
903
+
904
+ template<typename T> DUCC0_NOINLINE void r2c(const cfmav<T> &in,
905
+ const vfmav<std::complex<T>> &out, const shape_t &axes,
906
+ bool forward, T fct, size_t nthreads=1);
907
+
908
+ template<typename T> DUCC0_NOINLINE void c2r(const cfmav<std::complex<T>> &in,
909
+ const vfmav<T> &out, size_t axis, bool forward, T fct, size_t nthreads=1);
910
+
911
+ template<typename T> DUCC0_NOINLINE void c2r(const cfmav<std::complex<T>> &in,
912
+ const vfmav<T> &out, const shape_t &axes, bool forward, T fct,
913
+ size_t nthreads=1);
914
+
915
+ template<typename T> DUCC0_NOINLINE void c2r_mut(const vfmav<std::complex<T>> &in,
916
+ const vfmav<T> &out, const shape_t &axes, bool forward, T fct,
917
+ size_t nthreads=1);
918
+
919
+ template<typename T> DUCC0_NOINLINE void r2r_fftpack(const cfmav<T> &in,
920
+ const vfmav<T> &out, const shape_t &axes, bool real2hermitian, bool forward,
921
+ T fct, size_t nthreads=1);
922
+
923
+ template<typename T> DUCC0_NOINLINE void r2r_fftw(const cfmav<T> &in,
924
+ const vfmav<T> &out, const shape_t &axes, bool forward,
925
+ T fct, size_t nthreads=1);
926
+
927
+ template<typename T> DUCC0_NOINLINE void r2r_separable_hartley(const cfmav<T> &in,
928
+ const vfmav<T> &out, const shape_t &axes, T fct, size_t nthreads=1);
929
+
930
+ template<typename T> DUCC0_NOINLINE void r2r_separable_fht(const cfmav<T> &in,
931
+ const vfmav<T> &out, const shape_t &axes, T fct, size_t nthreads=1);
932
+
933
+ template<typename T> void r2r_genuine_hartley(const cfmav<T> &in,
934
+ const vfmav<T> &out, const shape_t &axes, T fct, size_t nthreads=1);
935
+
936
+ template<typename T> void r2r_genuine_fht(const cfmav<T> &in,
937
+ const vfmav<T> &out, const shape_t &axes, T fct, size_t nthreads=1);
938
+
939
+ /// Convolution and zero-padding/truncation along one axis
940
+ /** This performs a circular convolution with the kernel \a kernel on axis
941
+ * \a axis of \a in, applies the necessary zero-padding/truncation on this
942
+ * axis to give it the length \a out.shape(axis),and returns the result
943
+ * in \a out.
944
+ *
945
+ * The main purpose of this routine is efficiency: the combination of the above
946
+ * operations can be carried out more quickly than running the individual
947
+ * operations in succession.
948
+ *
949
+ * \a in and \a out must have identical shapes, with the possible exception
950
+ * of the axis \a axis; they may point to the same memory; in this case all
951
+ * of their strides must be identical.
952
+ *
953
+ * \a axis specifies the axis over which the operation is carried out.
954
+ *
955
+ * \a kernel must have the same length as \a in.shape(axis); it must be
956
+ * provided in the same domain as \a in (i.e. not pre-transformed).
957
+ *
958
+ * If \a in has more than one dimension, the computation will
959
+ * be distributed over \a nthreads threads.
960
+ */
961
+ template<typename T> DUCC0_NOINLINE void convolve_axis(const cfmav<T> &in,
962
+ const vfmav<T> &out, size_t axis, const cmav<T,1> &kernel, size_t nthreads=1);
963
+
964
+ template<typename T> DUCC0_NOINLINE void convolve_axis(const cfmav<complex<T>> &in,
965
+ const vfmav<complex<T>> &out, size_t axis, const cmav<complex<T>,1> &kernel,
966
+ size_t nthreads=1);
967
+ }
968
+
969
+ using detail_fft::pocketfft_c;
970
+ using detail_fft::pocketfft_r;
971
+ using detail_fft::pocketfft_hartley;
972
+ using detail_fft::pocketfft_fht;
973
+ using detail_fft::pocketfft_fftw;
974
+
975
+ using detail_fft::FORWARD;
976
+ using detail_fft::BACKWARD;
977
+ using detail_fft::c2c;
978
+ using detail_fft::c2r;
979
+ using detail_fft::c2r_mut;
980
+ using detail_fft::r2c;
981
+ using detail_fft::r2r_fftpack;
982
+ using detail_fft::r2r_fftw;
983
+ using detail_fft::r2r_separable_hartley;
984
+ using detail_fft::r2r_genuine_hartley;
985
+ using detail_fft::r2r_separable_fht;
986
+ using detail_fft::r2r_genuine_fht;
987
+ using detail_fft::dct;
988
+ using detail_fft::dst;
989
+ using detail_fft::convolve_axis;
990
+
991
+ inline size_t good_size_complex(size_t n)
992
+ { return detail_fft::util1d::good_size_cmplx(n); }
993
+ inline size_t good_size_real(size_t n)
994
+ { return detail_fft::util1d::good_size_real(n); }
995
+ inline size_t good_size_complex(size_t n, size_t required_factor)
996
+ { return detail_fft::util1d::good_size_cmplx(n, required_factor); }
997
+ inline size_t good_size_real(size_t n, size_t required_factor)
998
+ { return detail_fft::util1d::good_size_real(n, required_factor); }
999
+
1000
+ }
1001
+
1002
+ #endif
deps/exla/cache/xla_extension/include/_virtual_includes/fft/ducc/src/ducc0/fft/fft1d_impl.h ADDED
The diff for this file is too large to render. See raw diff
 
deps/exla/cache/xla_extension/include/_virtual_includes/fft/ducc/src/ducc0/fft/fftnd_impl.h ADDED
@@ -0,0 +1,1883 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ This file is part of the ducc FFT library.
3
+
4
+ Copyright (C) 2010-2024 Max-Planck-Society
5
+ Copyright (C) 2019 Peter Bell
6
+
7
+ Authors: Martin Reinecke, Peter Bell
8
+ */
9
+
10
+ /* SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0-or-later */
11
+
12
+ /*
13
+ All rights reserved.
14
+
15
+ Redistribution and use in source and binary forms, with or without modification,
16
+ are permitted provided that the following conditions are met:
17
+
18
+ * Redistributions of source code must retain the above copyright notice, this
19
+ list of conditions and the following disclaimer.
20
+ * Redistributions in binary form must reproduce the above copyright notice, this
21
+ list of conditions and the following disclaimer in the documentation and/or
22
+ other materials provided with the distribution.
23
+ * Neither the name of the copyright holder nor the names of its contributors may
24
+ be used to endorse or promote products derived from this software without
25
+ specific prior written permission.
26
+
27
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
28
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
29
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
30
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
31
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
32
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
33
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
34
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
36
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37
+ */
38
+
39
+ /*
40
+ * This code is free software; you can redistribute it and/or modify
41
+ * it under the terms of the GNU General Public License as published by
42
+ * the Free Software Foundation; either version 2 of the License, or
43
+ * (at your option) any later version.
44
+ *
45
+ * This code is distributed in the hope that it will be useful,
46
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
47
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
48
+ * GNU General Public License for more details.
49
+ *
50
+ * You should have received a copy of the GNU General Public License
51
+ * along with this code; if not, write to the Free Software
52
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
53
+ */
54
+
55
+ #ifndef DUCC0_FFTND_IMPL_H
56
+ #define DUCC0_FFTND_IMPL_H
57
+
58
+ #include <cmath>
59
+ #include <cstddef>
60
+ #include <cstdlib>
61
+ #include <numeric>
62
+ #include <stdexcept>
63
+ #include <memory>
64
+ #include <vector>
65
+ #include <complex>
66
+ #include <algorithm>
67
+ #include "ducc0/infra/useful_macros.h"
68
+ #include "ducc0/infra/error_handling.h"
69
+ #include "ducc0/infra/threading.h"
70
+ #include "ducc0/infra/misc_utils.h"
71
+ #include "ducc0/infra/simd.h"
72
+ #include "ducc0/infra/mav.h"
73
+ #include "ducc0/infra/aligned_array.h"
74
+ #include "ducc0/math/cmplx.h"
75
+ #include "ducc0/math/unity_roots.h"
76
+ #include "ducc0/fft/fft1d_impl.h"
77
+
78
+ /** \file fft.h
79
+ * Implementation of multi-dimensional Fast Fourier and related transforms
80
+ * \copyright Copyright (C) 2010-2021 Max-Planck-Society
81
+ * \copyright Copyright (C) 2019 Peter Bell
82
+ * \copyright
83
+ * \copyright For the odd-sized DCT-IV transforms:
84
+ * \copyright Copyright (C) 2003, 2007-14 Matteo Frigo
85
+ * \copyright Copyright (C) 2003, 2007-14 Massachusetts Institute of Technology
86
+ *
87
+ * \authors Martin Reinecke, Peter Bell
88
+ */
89
+
90
+ namespace ducc0 {
91
+
92
+ namespace detail_fft {
93
+
94
+ // the next line is necessary to address some sloppy name choices in AdaptiveCpp
95
+ using std::min, std::max;
96
+
97
+ template<typename T> constexpr inline size_t fft_simdlen
98
+ = min<size_t>(8, native_simd<T>::size());
99
+ template<> constexpr inline size_t fft_simdlen<double>
100
+ = min<size_t>(4, native_simd<double>::size());
101
+ template<> constexpr inline size_t fft_simdlen<float>
102
+ = min<size_t>(8, native_simd<float>::size());
103
+ template<typename T> using fft_simd = typename simd_select<T,fft_simdlen<T>>::type;
104
+ template<typename T> constexpr inline bool fft_simd_exists = (fft_simdlen<T> > 1);
105
+
106
+ struct util // hack to avoid duplicate symbols
107
+ {
108
+ static void sanity_check_axes(size_t ndim, const shape_t &axes)
109
+ {
110
+ if (ndim==1)
111
+ {
112
+ if ((axes.size()!=1) || (axes[0]!=0))
113
+ throw std::invalid_argument("bad axes");
114
+ return;
115
+ }
116
+ shape_t tmp(ndim,0);
117
+ if (axes.empty()) throw std::invalid_argument("no axes specified");
118
+ for (auto ax : axes)
119
+ {
120
+ if (ax>=ndim) throw std::invalid_argument("bad axis number");
121
+ if (++tmp[ax]>1) throw std::invalid_argument("axis specified repeatedly");
122
+ }
123
+ }
124
+
125
+ DUCC0_NOINLINE static void sanity_check_onetype(const fmav_info &a1,
126
+ const fmav_info &a2, bool inplace, const shape_t &axes)
127
+ {
128
+ sanity_check_axes(a1.ndim(), axes);
129
+ MR_assert(a1.conformable(a2), "array sizes are not conformable");
130
+ if (inplace) MR_assert(a1.stride()==a2.stride(), "stride mismatch");
131
+ }
132
+ DUCC0_NOINLINE static void sanity_check_cr(const fmav_info &ac,
133
+ const fmav_info &ar, const shape_t &axes)
134
+ {
135
+ sanity_check_axes(ac.ndim(), axes);
136
+ MR_assert(ac.ndim()==ar.ndim(), "dimension mismatch");
137
+ for (size_t i=0; i<ac.ndim(); ++i)
138
+ MR_assert(ac.shape(i) == ((i==axes.back()) ? (ar.shape(i)/2+1) : ar.shape(i)),
139
+ "axis length mismatch");
140
+ }
141
+ DUCC0_NOINLINE static void sanity_check_cr(const fmav_info &ac,
142
+ const fmav_info &ar, const size_t axis)
143
+ {
144
+ if (axis>=ac.ndim()) throw std::invalid_argument("bad axis number");
145
+ MR_assert(ac.ndim()==ar.ndim(), "dimension mismatch");
146
+ for (size_t i=0; i<ac.ndim(); ++i)
147
+ MR_assert(ac.shape(i) == ((i==axis) ? (ar.shape(i)/2+1) : ar.shape(i)),
148
+ "axis length mismatch");
149
+ }
150
+
151
+ static size_t thread_count (size_t nthreads, const fmav_info &info,
152
+ size_t axis, size_t /*vlen*/)
153
+ {
154
+ if (nthreads==1) return 1;
155
+ size_t size = info.size();
156
+ if (size<32768) return 1; // not worth opening a parallel region
157
+ size_t max_parallel = size / info.shape(axis);
158
+ size_t max_threads = ducc0::adjust_nthreads(nthreads);
159
+ return std::max(size_t(1), std::min(max_parallel, max_threads));
160
+ }
161
+ };
162
+
163
+ //
164
+ // multi-D infrastructure
165
+ //
166
+
167
+ template<typename T> std::shared_ptr<T> get_plan(size_t length, bool vectorize=false)
168
+ {
169
+ #ifdef DUCC0_NO_FFT_CACHE
170
+ return std::make_shared<T>(length, vectorize);
171
+ #else
172
+ constexpr size_t nmax=10;
173
+ struct entry { size_t n; bool vectorize; std::shared_ptr<T> ptr; };
174
+ static std::array<entry, nmax> cache{{{0,0,nullptr}}};
175
+ static std::array<size_t, nmax> last_access{{0}};
176
+ static size_t access_counter = 0;
177
+ static Mutex mut;
178
+
179
+ auto find_in_cache = [&]() -> std::shared_ptr<T>
180
+ {
181
+ for (size_t i=0; i<nmax; ++i)
182
+ if (cache[i].ptr && (cache[i].n==length) && (cache[i].vectorize==vectorize))
183
+ {
184
+ // no need to update if this is already the most recent entry
185
+ if (last_access[i]!=access_counter)
186
+ {
187
+ last_access[i] = ++access_counter;
188
+ // Guard against overflow
189
+ if (access_counter == 0)
190
+ last_access.fill(0);
191
+ }
192
+ return cache[i].ptr;
193
+ }
194
+
195
+ return nullptr;
196
+ };
197
+
198
+ {
199
+ LockGuard lock(mut);
200
+
201
+ auto p = find_in_cache();
202
+ if (p) return p;
203
+ }
204
+ auto plan = std::make_shared<T>(length, vectorize);
205
+ {
206
+ LockGuard lock(mut);
207
+
208
+ auto p = find_in_cache();
209
+ if (p) return p;
210
+
211
+ size_t lru = 0;
212
+ for (size_t i=1; i<nmax; ++i)
213
+ if (last_access[i] < last_access[lru])
214
+ lru = i;
215
+
216
+ cache[lru] = {length,vectorize, plan};
217
+ last_access[lru] = ++access_counter;
218
+ }
219
+ return plan;
220
+ #endif
221
+ }
222
+
223
+ template<size_t N> class multi_iter
224
+ {
225
+ private:
226
+ shape_t shp, pos;
227
+ stride_t str_i, str_o;
228
+ size_t cshp_i, cshp_o, rem;
229
+ ptrdiff_t cstr_i, cstr_o, sstr_i, sstr_o, p_ii, p_i[N], p_oi, p_o[N];
230
+ bool uni_i, uni_o;
231
+
232
+ void advance_i()
233
+ {
234
+ for (size_t i=0; i<pos.size(); ++i)
235
+ {
236
+ p_ii += str_i[i];
237
+ p_oi += str_o[i];
238
+ if (++pos[i] < shp[i])
239
+ return;
240
+ pos[i] = 0;
241
+ p_ii -= ptrdiff_t(shp[i])*str_i[i];
242
+ p_oi -= ptrdiff_t(shp[i])*str_o[i];
243
+ }
244
+ }
245
+
246
+ public:
247
+ multi_iter(const fmav_info &iarr, const fmav_info &oarr, size_t idim,
248
+ size_t nshares, size_t myshare)
249
+ : rem(iarr.size()/iarr.shape(idim)), sstr_i(0), sstr_o(0), p_ii(0), p_oi(0)
250
+ {
251
+ MR_assert(oarr.ndim()==iarr.ndim(), "dimension mismatch");
252
+ MR_assert(iarr.ndim()>=1, "not enough dimensions");
253
+ // Sort the extraneous dimensions in order of ascending output stride;
254
+ // this should improve overall cache re-use and avoid clashes between
255
+ // threads as much as possible.
256
+ shape_t idx(iarr.ndim());
257
+ std::iota(idx.begin(), idx.end(), 0);
258
+ sort(idx.begin(), idx.end(),
259
+ [&oarr](size_t i1, size_t i2) {return oarr.stride(i1) < oarr.stride(i2);});
260
+ for (auto i: idx)
261
+ if (i!=idim)
262
+ {
263
+ pos.push_back(0);
264
+ MR_assert(iarr.shape(i)==oarr.shape(i), "shape mismatch");
265
+ shp.push_back(iarr.shape(i));
266
+ str_i.push_back(iarr.stride(i));
267
+ str_o.push_back(oarr.stride(i));
268
+ }
269
+ MR_assert(idim<iarr.ndim(), "bad active dimension");
270
+ cstr_i = iarr.stride(idim);
271
+ cstr_o = oarr.stride(idim);
272
+ cshp_i = iarr.shape(idim);
273
+ cshp_o = oarr.shape(idim);
274
+
275
+ // collapse unneeded dimensions
276
+ bool done = false;
277
+ while(!done)
278
+ {
279
+ done=true;
280
+ for (size_t i=1; i<shp.size(); ++i)
281
+ if ((str_i[i] == str_i[i-1]*ptrdiff_t(shp[i-1]))
282
+ && (str_o[i] == str_o[i-1]*ptrdiff_t(shp[i-1])))
283
+ {
284
+ shp[i-1] *= shp[i];
285
+ str_i.erase(str_i.begin()+ptrdiff_t(i));
286
+ str_o.erase(str_o.begin()+ptrdiff_t(i));
287
+ shp.erase(shp.begin()+ptrdiff_t(i));
288
+ pos.pop_back();
289
+ done=false;
290
+ }
291
+ }
292
+ if (pos.size()>0)
293
+ {
294
+ sstr_i = str_i[0];
295
+ sstr_o = str_o[0];
296
+ }
297
+
298
+ if (nshares==1) return;
299
+ if (nshares==0) throw std::runtime_error("can't run with zero threads");
300
+ if (myshare>=nshares) throw std::runtime_error("impossible share requested");
301
+ auto [lo, hi] = calcShare(nshares, myshare, rem);
302
+ size_t todo = hi-lo;
303
+
304
+ // this shouldn't normally happen, but make sure we handle it properly
305
+ if (todo==0)
306
+ { rem=0; return; }
307
+
308
+ size_t chunk = rem;
309
+ for (size_t i2=0, i=pos.size()-1; i2<pos.size(); ++i2,--i)
310
+ {
311
+ chunk /= shp[i];
312
+ size_t n_advance = lo/chunk;
313
+ pos[i] += n_advance;
314
+ p_ii += ptrdiff_t(n_advance)*str_i[i];
315
+ p_oi += ptrdiff_t(n_advance)*str_o[i];
316
+ lo -= n_advance*chunk;
317
+ }
318
+ MR_assert(lo==0, "must not happen");
319
+ rem = todo;
320
+ }
321
+ void advance(size_t n)
322
+ {
323
+ if (rem<n) throw std::runtime_error("underrun");
324
+ for (size_t i=0; i<n; ++i)
325
+ {
326
+ p_i[i] = p_ii;
327
+ p_o[i] = p_oi;
328
+ advance_i();
329
+ }
330
+ uni_i = uni_o = true;
331
+ for (size_t i=1; i<n; ++i)
332
+ {
333
+ uni_i = uni_i && (p_i[i]-p_i[i-1] == sstr_i);
334
+ uni_o = uni_o && (p_o[i]-p_o[i-1] == sstr_o);
335
+ }
336
+ rem -= n;
337
+ }
338
+ ptrdiff_t iofs(size_t i) const { return p_i[0] + ptrdiff_t(i)*cstr_i; }
339
+ ptrdiff_t iofs(size_t j, size_t i) const { return p_i[j] + ptrdiff_t(i)*cstr_i; }
340
+ ptrdiff_t iofs_uni(size_t j, size_t i) const { return p_i[0] + ptrdiff_t(j)*sstr_i + ptrdiff_t(i)*cstr_i; }
341
+ ptrdiff_t oofs(size_t i) const { return p_o[0] + ptrdiff_t(i)*cstr_o; }
342
+ ptrdiff_t oofs(size_t j, size_t i) const { return p_o[j] + ptrdiff_t(i)*cstr_o; }
343
+ ptrdiff_t oofs_uni(size_t j, size_t i) const { return p_o[0] + ptrdiff_t(j)*sstr_o + ptrdiff_t(i)*cstr_o; }
344
+ bool uniform_i() const { return uni_i; }
345
+ ptrdiff_t unistride_i() const { return sstr_i; }
346
+ bool uniform_o() const { return uni_o; }
347
+ ptrdiff_t unistride_o() const { return sstr_o; }
348
+ size_t length_in() const { return cshp_i; }
349
+ size_t length_out() const { return cshp_o; }
350
+ ptrdiff_t stride_in() const { return cstr_i; }
351
+ ptrdiff_t stride_out() const { return cstr_o; }
352
+ size_t remaining() const { return rem; }
353
+ bool critical_stride_trans(size_t tsz) const
354
+ {
355
+ return ((abs<ptrdiff_t>(stride_in() *tsz)&4095)==0)
356
+ || ((abs<ptrdiff_t>(stride_out()*tsz)&4095)==0);
357
+ }
358
+ bool critical_stride_other(size_t tsz) const
359
+ {
360
+ if (unistride_i()==0) return false; // it's just one transform
361
+ return ((abs<ptrdiff_t>(unistride_i()*tsz)&4095)==0)
362
+ || ((abs<ptrdiff_t>(unistride_o()*tsz)&4095)==0);
363
+ }
364
+ };
365
+
366
+ template<typename T, typename T0> class TmpStorage
367
+ {
368
+ private:
369
+ aligned_array<T> d;
370
+ size_t dofs, dstride;
371
+
372
+ public:
373
+ TmpStorage(size_t n_trafo, size_t bufsize_data, size_t bufsize_trafo,
374
+ size_t n_simultaneous, bool inplace)
375
+ {
376
+ if (inplace)
377
+ {
378
+ d.resize(bufsize_trafo);
379
+ return;
380
+ }
381
+ constexpr auto vlen = fft_simdlen<T0>;
382
+ // FIXME: when switching to C++20, use bit_floor(othersize)
383
+ size_t buffct = std::min(vlen, n_trafo);
384
+ size_t datafct = std::min(vlen, n_trafo);
385
+ if (n_trafo>=n_simultaneous*vlen) datafct = n_simultaneous*vlen;
386
+ dstride = bufsize_data;
387
+ dofs = bufsize_trafo;
388
+ // critical stride avoidance
389
+ if ((dstride&256)==0) dstride+=16;
390
+ if ((dofs&256)==0) dofs += 16;
391
+ d.resize(buffct*dofs + datafct*dstride);
392
+ }
393
+
394
+ template<typename T2> T2 *transformBuf()
395
+ { return reinterpret_cast<T2 *>(d.data()); }
396
+ template<typename T2> T2 *dataBuf()
397
+ { return reinterpret_cast<T2 *>(d.data()) + dofs; }
398
+ size_t data_stride() const
399
+ { return dstride; }
400
+ };
401
+
402
+ template<typename T2, typename T, typename T0> class TmpStorage2
403
+ {
404
+ private:
405
+ TmpStorage<T, T0> &stg;
406
+
407
+ public:
408
+ using datatype = T2;
409
+ TmpStorage2(TmpStorage<T,T0> &stg_): stg(stg_) {}
410
+
411
+ T2 *transformBuf() { return stg.template transformBuf<T2>(); }
412
+ T2 *dataBuf() { return stg.template dataBuf<T2>(); }
413
+ size_t data_stride() const { return stg.data_stride(); }
414
+ };
415
+
416
+ template <typename Tsimd, typename Titer> DUCC0_NOINLINE void copy_input(const Titer &it,
417
+ const cfmav<Cmplx<typename Tsimd::value_type>> &src, Cmplx<Tsimd> *DUCC0_RESTRICT dst)
418
+ {
419
+ constexpr auto vlen=Tsimd::size();
420
+ const Cmplx<typename Tsimd::value_type> * DUCC0_RESTRICT ptr = src.data();
421
+ for (size_t i=0; i<it.length_in(); ++i)
422
+ {
423
+ Cmplx<Tsimd> tmp;
424
+ for (size_t j=0; j<vlen; ++j)
425
+ {
426
+ tmp.r[j] = ptr[it.iofs(j,i)].r;
427
+ tmp.i[j] = ptr[it.iofs(j,i)].i;
428
+ }
429
+ dst[i] = tmp;
430
+ }
431
+ }
432
+
433
+ template <typename Tsimd, typename Titer> DUCC0_NOINLINE void copy_input(const Titer &it,
434
+ const cfmav<typename Tsimd::value_type> &src, Tsimd *DUCC0_RESTRICT dst)
435
+ {
436
+ constexpr auto vlen=Tsimd::size();
437
+ const typename Tsimd::value_type * DUCC0_RESTRICT ptr = src.data();
438
+ for (size_t i=0; i<it.length_in(); ++i)
439
+ {
440
+ typename Tsimd::value_type tmp[vlen];
441
+ for (size_t j=0; j<vlen; ++j)
442
+ tmp[j] = ptr[it.iofs(j,i)];
443
+ dst[i] = Tsimd(&tmp[0], element_aligned_tag());
444
+ }
445
+ }
446
+
447
+ template <typename Titer, typename T> DUCC0_NOINLINE void copy_input(const Titer &it,
448
+ const cfmav<T> &src, T *DUCC0_RESTRICT dst)
449
+ {
450
+ const T * DUCC0_RESTRICT ptr = src.data();
451
+ if (dst == &src.raw(it.iofs(0))) return; // in-place
452
+ for (size_t i=0; i<it.length_in(); ++i)
453
+ dst[i] = ptr[it.iofs(i)];
454
+ }
455
+
456
+ template<typename Tsimd, typename Titer> DUCC0_NOINLINE void copy_output(const Titer &it,
457
+ const Cmplx<Tsimd> *DUCC0_RESTRICT src, const vfmav<Cmplx<typename Tsimd::value_type>> &dst)
458
+ {
459
+ constexpr auto vlen=Tsimd::size();
460
+ Cmplx<typename Tsimd::value_type> * DUCC0_RESTRICT ptr = dst.data();
461
+ for (size_t i=0; i<it.length_out(); ++i)
462
+ {
463
+ Cmplx<Tsimd> tmp(src[i]);
464
+ for (size_t j=0; j<vlen; ++j)
465
+ ptr[it.oofs(j,i)].Set(tmp.r[j],tmp.i[j]);
466
+ }
467
+ }
468
+
469
+ template<typename Tsimd, typename Titer> DUCC0_NOINLINE void copy_output(const Titer &it,
470
+ const Tsimd *DUCC0_RESTRICT src, const vfmav<typename Tsimd::value_type> &dst)
471
+ {
472
+ constexpr auto vlen=Tsimd::size();
473
+ typename Tsimd::value_type * DUCC0_RESTRICT ptr = dst.data();
474
+ for (size_t i=0; i<it.length_out(); ++i)
475
+ {
476
+ Tsimd tmp = src[i];
477
+ for (size_t j=0; j<vlen; ++j)
478
+ ptr[it.oofs(j,i)] = tmp[j];
479
+ }
480
+ }
481
+
482
+ template<typename T, typename Titer> DUCC0_NOINLINE void copy_output(const Titer &it,
483
+ const T *DUCC0_RESTRICT src, const vfmav<T> &dst)
484
+ {
485
+ T * DUCC0_RESTRICT ptr=dst.data();
486
+ if (src == &dst.raw(it.oofs(0))) return; // in-place
487
+ for (size_t i=0; i<it.length_out(); ++i)
488
+ ptr[it.oofs(i)] = src[i];
489
+ }
490
+ template <typename Tsimd, typename Titer> DUCC0_NOINLINE void copy_input(const Titer &it,
491
+ const cfmav<Cmplx<typename Tsimd::value_type>> &src, Cmplx<Tsimd> * DUCC0_RESTRICT dst, size_t nvec, size_t vstr)
492
+ {
493
+ constexpr auto vlen=Tsimd::size();
494
+ const Cmplx<typename Tsimd::value_type> * DUCC0_RESTRICT ptr = src.data();
495
+ for (size_t i=0; i<it.length_in(); ++i)
496
+ for (size_t j0=0; j0<nvec; ++j0)
497
+ {
498
+ typename Tsimd::value_type tmp[2*vlen];
499
+ for (size_t j1=0; j1<vlen; ++j1)
500
+ {
501
+ tmp[j1] = ptr[it.iofs(j0*vlen+j1,i)].r;
502
+ tmp[j1+vlen] = ptr[it.iofs(j0*vlen+j1,i)].i;
503
+ }
504
+
505
+ dst[j0*vstr+i].r = Tsimd(&tmp[0], element_aligned_tag());
506
+ dst[j0*vstr+i].i = Tsimd(&tmp[vlen], element_aligned_tag());
507
+ }
508
+ }
509
+ template <typename T, typename Titer> DUCC0_NOINLINE void copy_input(const Titer &it,
510
+ const cfmav<Cmplx<T>> &src, Cmplx<T> * DUCC0_RESTRICT dst, size_t nvec, size_t vstr)
511
+ {
512
+ const Cmplx<T> * DUCC0_RESTRICT ptr = src.data();
513
+ for (size_t i=0; i<it.length_in(); ++i)
514
+ for (size_t j0=0; j0<nvec; ++j0)
515
+ dst[j0*vstr+i] = ptr[it.iofs(j0,i)];
516
+ }
517
+
518
+ template <typename Tsimd, typename Titer> DUCC0_NOINLINE void copy_input(const Titer &it,
519
+ const cfmav<typename Tsimd::value_type> &src, Tsimd * DUCC0_RESTRICT dst, size_t nvec, size_t vstr)
520
+ {
521
+ constexpr auto vlen=Tsimd::size();
522
+ const typename Tsimd::value_type * DUCC0_RESTRICT ptr = src.data();
523
+ for (size_t i=0; i<it.length_in(); ++i)
524
+ for (size_t j0=0; j0<nvec; ++j0)
525
+ {
526
+ typename Tsimd::value_type tmp[vlen];
527
+ for (size_t j1=0; j1<vlen; ++j1)
528
+ tmp[j1] = ptr[it.iofs(j0*vlen+j1,i)];
529
+ dst[j0*vstr+i] = Tsimd(&tmp[0],element_aligned_tag());
530
+ }
531
+ }
532
+
533
+ template <typename T, typename Titer> DUCC0_NOINLINE void copy_input(const Titer &it,
534
+ const cfmav<T> &src, T * DUCC0_RESTRICT dst, size_t nvec, size_t vstr)
535
+ {
536
+ const T * DUCC0_RESTRICT ptr = src.data();
537
+ for (size_t i=0; i<it.length_in(); ++i)
538
+ for (size_t j0=0; j0<nvec; ++j0)
539
+ dst[j0*vstr+i] = ptr[it.iofs(j0,i)];
540
+ }
541
+
542
+ template<typename Tsimd, typename Titer> DUCC0_NOINLINE void copy_output(const Titer &it,
543
+ const Cmplx<Tsimd> * DUCC0_RESTRICT src, const vfmav<Cmplx<typename Tsimd::value_type>> &dst, size_t nvec, size_t vstr)
544
+ {
545
+ constexpr auto vlen=Tsimd::size();
546
+ Cmplx<typename Tsimd::value_type> * DUCC0_RESTRICT ptr = dst.data();
547
+ for (size_t i=0; i<it.length_out(); ++i)
548
+ for (size_t j0=0; j0<nvec; ++j0)
549
+ {
550
+ Cmplx<Tsimd> tmp(src[j0*vstr+i]);
551
+ for (size_t j1=0; j1<vlen; ++j1)
552
+ ptr[it.oofs(j0*vlen+j1,i)].Set(tmp.r[j1],tmp.i[j1]);
553
+ }
554
+ }
555
+ template<typename T, typename Titer> DUCC0_NOINLINE void copy_output(const Titer &it,
556
+ const Cmplx<T> * DUCC0_RESTRICT src, const vfmav<Cmplx<T>> &dst, size_t nvec, size_t vstr)
557
+ {
558
+ Cmplx<T> * DUCC0_RESTRICT ptr = dst.data();
559
+ for (size_t i=0; i<it.length_out(); ++i)
560
+ for (size_t j0=0; j0<nvec; ++j0)
561
+ ptr[it.oofs(j0,i)] = src[j0*vstr+i];
562
+ }
563
+ template<typename Tsimd, typename Titer> DUCC0_NOINLINE void copy_output(const Titer &it,
564
+ const Tsimd * DUCC0_RESTRICT src, const vfmav<typename Tsimd::value_type> &dst, size_t nvec, size_t vstr)
565
+ {
566
+ constexpr auto vlen=Tsimd::size();
567
+ typename Tsimd::value_type * DUCC0_RESTRICT ptr = dst.data();
568
+ for (size_t i=0; i<it.length_out(); ++i)
569
+ for (size_t j0=0; j0<nvec; ++j0)
570
+ {
571
+ Tsimd tmp(src[j0*vstr+i]);
572
+ for (size_t j1=0; j1<vlen; ++j1)
573
+ ptr[it.oofs(j0*vlen+j1,i)] = tmp[j1];
574
+ }
575
+ }
576
+ template<typename T, typename Titer> DUCC0_NOINLINE void copy_output(const Titer &it,
577
+ const T * DUCC0_RESTRICT src, const vfmav<T> &dst, size_t nvec, size_t vstr)
578
+ {
579
+ T * DUCC0_RESTRICT ptr = dst.data();
580
+ for (size_t i=0; i<it.length_out(); ++i)
581
+ for (size_t j0=0; j0<nvec; ++j0)
582
+ ptr[it.oofs(j0,i)] = src[j0*vstr+i];
583
+ }
584
+
585
+
586
+ template <typename T, size_t vlen> struct add_vec
587
+ { using type = typename simd_select<T, vlen>::type; };
588
+ template <typename T, size_t vlen> struct add_vec<Cmplx<T>, vlen>
589
+ { using type = Cmplx<typename simd_select<T, vlen>::type>; };
590
+ template <typename T, size_t vlen> using add_vec_t = typename add_vec<T, vlen>::type;
591
+
592
+ template<typename Tplan, typename T, typename T0, typename Exec>
593
+ DUCC0_NOINLINE void general_nd(const cfmav<T> &in, const vfmav<T> &out,
594
+ const shape_t &axes, T0 fct, size_t nthreads, const Exec &exec,
595
+ const bool /*allow_inplace*/=true)
596
+ {
597
+ if ((in.ndim()==1)&&(in.stride(0)==1)&&(out.stride(0)==1))
598
+ {
599
+ auto plan = get_plan<Tplan>(in.shape(0), true);
600
+ exec.exec_simple(in.data(), out.data(), *plan, fct, nthreads);
601
+ return;
602
+ }
603
+ std::shared_ptr<Tplan> plan, vplan;
604
+ size_t nth1d = (in.ndim()==1) ? nthreads : 1;
605
+
606
+ for (size_t iax=0; iax<axes.size(); ++iax)
607
+ {
608
+ size_t len=in.shape(axes[iax]);
609
+ if ((!plan) || (len!=plan->length()))
610
+ {
611
+ plan = get_plan<Tplan>(len, in.ndim()==1);
612
+ vplan = ((in.ndim()==1)||(len<300)||((len&3)!=0)) ?
613
+ plan : get_plan<Tplan>(len, true);
614
+ }
615
+
616
+ execParallel(util::thread_count(nthreads, in, axes[iax], fft_simdlen<T0>),
617
+ [&](Scheduler &sched)
618
+ {
619
+ constexpr auto vlen = fft_simdlen<T0>;
620
+ constexpr size_t nmax = 16;
621
+ const auto &tin(iax==0? in : out);
622
+ multi_iter<nmax> it(tin, out, axes[iax], sched.num_threads(), sched.thread_num());
623
+
624
+ // n_simul: vector size
625
+ // n_bunch: total size of bunch (multiple of n_simul)
626
+ size_t n_simul=1, n_bunch=1;
627
+ bool critstride = (((in.stride(axes[iax])*sizeof(T))&4095)==0)
628
+ || (((out.stride(axes[iax])*sizeof(T))&4095)==0);
629
+ bool nostride = (in.stride(axes[iax])==1) && (out.stride(axes[iax])==1);
630
+
631
+ constexpr size_t l2cache=262144*2;
632
+ constexpr size_t cacheline=64;
633
+
634
+ // working set size
635
+ auto wss = [&](size_t vl) { return sizeof(T)*(2*len*vl + plan->bufsize()); };
636
+ // is the FFT small enough to fit into L2 vectorized?
637
+ if (wss(1)>l2cache) // "long" FFT, don't execute more than one at the same time
638
+ {
639
+ n_simul=1;
640
+ if (critstride) // make bunch large to reduce overall copy cost
641
+ {
642
+ n_bunch=n_simul;
643
+ while ((n_bunch<nmax) && (sizeof(T)*n_bunch<2*cacheline)) n_bunch*=2;
644
+ }
645
+ else if (nostride) // simple scalar "in-place" transform
646
+ n_bunch=n_simul;
647
+ else // we have some strides, use a medium-sized bunch
648
+ {
649
+ n_bunch=n_simul;
650
+ while ((n_bunch<nmax) && (sizeof(T)*n_bunch<cacheline)) n_bunch*=2;
651
+ }
652
+ }
653
+ else // fairly small individual FFT, vectorizing probably beneficial
654
+ {
655
+ // if no stride, only vectorize if vectorized FFT fits into cache
656
+ // if strided, always vectorize (TBC)
657
+ n_simul = nostride ? ((wss(vlen)<=l2cache) ? vlen:1) : vlen;
658
+ if (critstride) // make bunch large to reduce overall copy cost
659
+ {
660
+ n_bunch=n_simul;
661
+ while ((n_bunch<nmax) /*&& (sizeof(T)*n_bunch<2*cacheline)*/) n_bunch*=2;
662
+ }
663
+ else if (nostride)
664
+ n_bunch=n_simul;
665
+ else
666
+ {
667
+ n_bunch=n_simul;
668
+ if (n_simul==1)
669
+ while ((n_bunch<nmax) && (sizeof(T)*n_bunch<cacheline)) n_bunch*=2;
670
+ }
671
+ }
672
+
673
+ bool inplace = (in.stride(axes[iax])==1) && (out.stride(axes[iax])==1) && (n_bunch==1);
674
+ MR_assert(n_bunch<=nmax, "must not happen");
675
+ TmpStorage<T,T0> storage(in.size()/len, len, max(plan->bufsize(),vplan->bufsize()), (n_bunch+vlen-1)/vlen, inplace);
676
+
677
+ // first, do all possible steps of size n_bunch, then n_simul
678
+ if (n_bunch>1)
679
+ {
680
+ #ifndef DUCC0_NO_SIMD
681
+ if constexpr (vlen>1)
682
+ {
683
+ constexpr size_t lvlen = vlen;
684
+ if (n_simul>=lvlen)
685
+ {
686
+ if ((n_bunch>n_simul) && (it.remaining()>=n_bunch))
687
+ {
688
+ TmpStorage2<add_vec_t<T, lvlen>,T,T0> storage2(storage);
689
+ while (it.remaining()>=n_bunch)
690
+ {
691
+ it.advance(n_bunch);
692
+ exec.exec_n(it, tin, out, storage2, *plan, fct, n_bunch/lvlen, nth1d);
693
+ }
694
+ }
695
+ }
696
+ if (n_simul==lvlen)
697
+ {
698
+ if (it.remaining()>=lvlen)
699
+ {
700
+ TmpStorage2<add_vec_t<T, lvlen>,T,T0> storage2(storage);
701
+ while (it.remaining()>=lvlen)
702
+ {
703
+ it.advance(lvlen);
704
+ exec(it, tin, out, storage2, *plan, fct, nth1d);
705
+ }
706
+ }
707
+ }
708
+ }
709
+ if constexpr ((vlen>2) && (simd_exists<T0,vlen/2>))
710
+ {
711
+ constexpr size_t lvlen = vlen/2;
712
+ if (n_simul>=lvlen)
713
+ {
714
+ if ((n_bunch>n_simul) && (it.remaining()>=n_bunch))
715
+ {
716
+ TmpStorage2<add_vec_t<T, lvlen>,T,T0> storage2(storage);
717
+ while (it.remaining()>=n_bunch)
718
+ {
719
+ it.advance(n_bunch);
720
+ exec.exec_n(it, tin, out, storage2, *plan, fct, n_bunch/lvlen, nth1d);
721
+ }
722
+ }
723
+ }
724
+ if (n_simul==lvlen)
725
+ {
726
+ if (it.remaining()>=lvlen)
727
+ {
728
+ TmpStorage2<add_vec_t<T, lvlen>,T,T0> storage2(storage);
729
+ while (it.remaining()>=lvlen)
730
+ {
731
+ it.advance(lvlen);
732
+ exec(it, tin, out, storage2, *plan, fct, nth1d);
733
+ }
734
+ }
735
+ }
736
+ }
737
+ if constexpr ((vlen>4) && (simd_exists<T0,vlen/4>))
738
+ {
739
+ constexpr size_t lvlen = vlen/4;
740
+ if (n_simul>=lvlen)
741
+ {
742
+ if ((n_bunch>n_simul) && (it.remaining()>=n_bunch))
743
+ {
744
+ TmpStorage2<add_vec_t<T, lvlen>,T,T0> storage2(storage);
745
+ while (it.remaining()>=n_bunch)
746
+ {
747
+ it.advance(n_bunch);
748
+ exec.exec_n(it, tin, out, storage2, *plan, fct, n_bunch/lvlen, nth1d);
749
+ }
750
+ }
751
+ }
752
+ if (n_simul==lvlen)
753
+ {
754
+ if (it.remaining()>=lvlen)
755
+ {
756
+ TmpStorage2<add_vec_t<T, lvlen>,T,T0> storage2(storage);
757
+ while (it.remaining()>=lvlen)
758
+ {
759
+ it.advance(lvlen);
760
+ exec(it, tin, out, storage2, *plan, fct, nth1d);
761
+ }
762
+ }
763
+ }
764
+ }
765
+ #endif
766
+ {
767
+ TmpStorage2<T,T,T0> storage2(storage);
768
+ while ((n_bunch>n_simul) && (it.remaining()>=n_bunch))
769
+ {
770
+ it.advance(n_bunch);
771
+ exec.exec_n(it, tin, out, storage2, *vplan, fct, n_bunch, nth1d);
772
+ }
773
+ }
774
+ }
775
+ {
776
+ TmpStorage2<T,T,T0> storage2(storage);
777
+ while (it.remaining()>0)
778
+ {
779
+ it.advance(1);
780
+ exec(it, tin, out, storage2, *vplan, fct, nth1d, inplace);
781
+ }
782
+ }
783
+ }); // end of parallel region
784
+ fct = T0(1); // factor has been applied, use 1 for remaining axes
785
+ }
786
+ }
787
+
788
+ struct ExecC2C
789
+ {
790
+ bool forward;
791
+
792
+ template <typename T0, typename Tstorage, typename Titer> DUCC0_NOINLINE void operator() (
793
+ const Titer &it, const cfmav<Cmplx<T0>> &in,
794
+ const vfmav<Cmplx<T0>> &out, Tstorage &storage, const pocketfft_c<T0> &plan, T0 fct,
795
+ size_t nthreads, bool inplace=false) const
796
+ {
797
+ using T = typename Tstorage::datatype;
798
+ if constexpr(is_same<Cmplx<T0>, T>::value)
799
+ if (inplace)
800
+ {
801
+ if (in.data()!=out.data())
802
+ copy_input(it, in, out.data()+it.oofs(0));
803
+ plan.exec_copyback(out.data()+it.oofs(0), storage.transformBuf(), fct, forward, nthreads);
804
+ return;
805
+ }
806
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
807
+ copy_input(it, in, buf2);
808
+ auto res = plan.exec(buf2, buf1, fct, forward, nthreads);
809
+ copy_output(it, res, out);
810
+ }
811
+ template <typename T0, typename Tstorage, typename Titer> DUCC0_NOINLINE void exec_n (
812
+ const Titer &it, const cfmav<Cmplx<T0>> &in,
813
+ const vfmav<Cmplx<T0>> &out, Tstorage &storage, const pocketfft_c<T0> &plan, T0 fct, size_t nvec,
814
+ size_t nthreads) const
815
+ {
816
+ using T = typename Tstorage::datatype;
817
+ size_t dstr = storage.data_stride();
818
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
819
+ copy_input(it, in, buf2, nvec, dstr);
820
+ for (size_t i=0; i<nvec; ++i)
821
+ plan.exec_copyback(buf2+i*dstr, buf1, fct, forward, nthreads);
822
+ copy_output(it, buf2, out, nvec, dstr);
823
+ }
824
+ template <typename T0> DUCC0_NOINLINE void exec_simple (
825
+ const Cmplx<T0> *in, Cmplx<T0> *out, const pocketfft_c<T0> &plan, T0 fct,
826
+ size_t nthreads) const
827
+ {
828
+ if (in!=out) copy_n(in, plan.length(), out);
829
+ plan.exec(out, fct, forward, nthreads);
830
+ }
831
+ };
832
+
833
+ struct ExecHartley
834
+ {
835
+ template <typename T0, typename Tstorage, typename Titer> DUCC0_NOINLINE void operator() (
836
+ const Titer &it, const cfmav<T0> &in, const vfmav<T0> &out,
837
+ Tstorage &storage, const pocketfft_hartley<T0> &plan, T0 fct, size_t nthreads,
838
+ bool inplace=false) const
839
+ {
840
+ using T = typename Tstorage::datatype;
841
+ if constexpr(is_same<T0, T>::value)
842
+ if (inplace)
843
+ {
844
+ if (in.data()!=out.data())
845
+ copy_input(it, in, out.data()+it.oofs(0));
846
+ plan.exec_copyback(out.data()+it.oofs(0), storage.transformBuf(), fct, nthreads);
847
+ return;
848
+ }
849
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
850
+ copy_input(it, in, buf2);
851
+ auto res = plan.exec(buf2, buf1, fct, nthreads);
852
+ copy_output(it, res, out);
853
+ }
854
+ template <typename T0, typename Tstorage, typename Titer> DUCC0_NOINLINE void exec_n (
855
+ const Titer &it, const cfmav<T0> &in,
856
+ const vfmav<T0> &out, Tstorage &storage, const pocketfft_hartley<T0> &plan, T0 fct, size_t nvec,
857
+ size_t nthreads) const
858
+ {
859
+ using T = typename Tstorage::datatype;
860
+ size_t dstr = storage.data_stride();
861
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
862
+ copy_input(it, in, buf2, nvec, dstr);
863
+ for (size_t i=0; i<nvec; ++i)
864
+ plan.exec_copyback(buf2+i*dstr, buf1, fct, nthreads);
865
+ copy_output(it, buf2, out, nvec, dstr);
866
+ }
867
+ template <typename T0> DUCC0_NOINLINE void exec_simple (
868
+ const T0 *in, T0 *out, const pocketfft_hartley<T0> &plan, T0 fct,
869
+ size_t nthreads) const
870
+ {
871
+ if (in!=out) copy_n(in, plan.length(), out);
872
+ plan.exec(out, fct, nthreads);
873
+ }
874
+ };
875
+
876
+ struct ExecFHT
877
+ {
878
+ template <typename T0, typename Tstorage, typename Titer> DUCC0_NOINLINE void operator() (
879
+ const Titer &it, const cfmav<T0> &in, const vfmav<T0> &out,
880
+ Tstorage &storage, const pocketfft_fht<T0> &plan, T0 fct, size_t nthreads,
881
+ bool inplace=false) const
882
+ {
883
+ using T = typename Tstorage::datatype;
884
+ if constexpr(is_same<T0, T>::value)
885
+ if (inplace)
886
+ {
887
+ if (in.data()!=out.data())
888
+ copy_input(it, in, out.data()+it.oofs(0));
889
+ plan.exec_copyback(out.data()+it.oofs(0), storage.transformBuf(), fct, nthreads);
890
+ return;
891
+ }
892
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
893
+ copy_input(it, in, buf2);
894
+ auto res = plan.exec(buf2, buf1, fct, nthreads);
895
+ copy_output(it, res, out);
896
+ }
897
+ template <typename T0, typename Tstorage, typename Titer> DUCC0_NOINLINE void exec_n (
898
+ const Titer &it, const cfmav<T0> &in,
899
+ const vfmav<T0> &out, Tstorage &storage, const pocketfft_fht<T0> &plan, T0 fct, size_t nvec,
900
+ size_t nthreads) const
901
+ {
902
+ using T = typename Tstorage::datatype;
903
+ size_t dstr = storage.data_stride();
904
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
905
+ copy_input(it, in, buf2, nvec, dstr);
906
+ for (size_t i=0; i<nvec; ++i)
907
+ plan.exec_copyback(buf2+i*dstr, buf1, fct, nthreads);
908
+ copy_output(it, buf2, out, nvec, dstr);
909
+ }
910
+ template <typename T0> DUCC0_NOINLINE void exec_simple (
911
+ const T0 *in, T0 *out, const pocketfft_fht<T0> &plan, T0 fct,
912
+ size_t nthreads) const
913
+ {
914
+ if (in!=out) copy_n(in, plan.length(), out);
915
+ plan.exec(out, fct, nthreads);
916
+ }
917
+ };
918
+
919
+ struct ExecFFTW
920
+ {
921
+ bool forward;
922
+
923
+ template <typename T0, typename Tstorage, typename Titer> DUCC0_NOINLINE void operator() (
924
+ const Titer &it, const cfmav<T0> &in, const vfmav<T0> &out,
925
+ Tstorage &storage, const pocketfft_fftw<T0> &plan, T0 fct, size_t nthreads,
926
+ bool inplace=false) const
927
+ {
928
+ using T = typename Tstorage::datatype;
929
+ if constexpr(is_same<T0, T>::value)
930
+ if (inplace)
931
+ {
932
+ if (in.data()!=out.data())
933
+ copy_input(it, in, out.data()+it.oofs(0));
934
+ plan.exec_copyback(out.data()+it.oofs(0), storage.transformBuf(), fct, forward, nthreads);
935
+ return;
936
+ }
937
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
938
+ copy_input(it, in, buf2);
939
+ auto res = plan.exec(buf2, buf1, fct, forward, nthreads);
940
+ copy_output(it, res, out);
941
+ }
942
+ template <typename T0, typename Tstorage, typename Titer> DUCC0_NOINLINE void exec_n (
943
+ const Titer &it, const cfmav<T0> &in,
944
+ const vfmav<T0> &out, Tstorage &storage, const pocketfft_fftw<T0> &plan, T0 fct, size_t nvec,
945
+ size_t nthreads) const
946
+ {
947
+ using T = typename Tstorage::datatype;
948
+ size_t dstr = storage.data_stride();
949
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
950
+ copy_input(it, in, buf2, nvec, dstr);
951
+ for (size_t i=0; i<nvec; ++i)
952
+ plan.exec_copyback(buf2+i*dstr, buf1, fct, forward, nthreads);
953
+ copy_output(it, buf2, out, nvec, dstr);
954
+ }
955
+ template <typename T0> DUCC0_NOINLINE void exec_simple (
956
+ const T0 *in, T0 *out, const pocketfft_fftw<T0> &plan, T0 fct,
957
+ size_t nthreads) const
958
+ {
959
+ if (in!=out) copy_n(in, plan.length(), out);
960
+ plan.exec(out, fct, forward, nthreads);
961
+ }
962
+ };
963
+
964
+ struct ExecDcst
965
+ {
966
+ bool ortho;
967
+ int type;
968
+ bool cosine;
969
+
970
+ template <typename T0, typename Tstorage, typename Tplan, typename Titer>
971
+ DUCC0_NOINLINE void operator() (const Titer &it, const cfmav<T0> &in,
972
+ const vfmav <T0> &out, Tstorage &storage, const Tplan &plan, T0 fct, size_t nthreads,
973
+ bool inplace=false) const
974
+ {
975
+ using T = typename Tstorage::datatype;
976
+ if constexpr(is_same<T0, T>::value)
977
+ if (inplace)
978
+ {
979
+ if (in.data()!=out.data())
980
+ copy_input(it, in, out.data()+it.oofs(0));
981
+ plan.exec_copyback(out.data()+it.oofs(0), storage.transformBuf(), fct, ortho, type, cosine, nthreads);
982
+ return;
983
+ }
984
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
985
+ copy_input(it, in, buf2);
986
+ auto res = plan.exec(buf2, buf1, fct, ortho, type, cosine, nthreads);
987
+ copy_output(it, res, out);
988
+ }
989
+ template <typename T0, typename Tstorage, typename Tplan, typename Titer> DUCC0_NOINLINE void exec_n (
990
+ const Titer &it, const cfmav<T0> &in,
991
+ const vfmav<T0> &out, Tstorage &storage, const Tplan &plan, T0 fct, size_t nvec,
992
+ size_t nthreads) const
993
+ {
994
+ using T = typename Tstorage::datatype;
995
+ size_t dstr = storage.data_stride();
996
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
997
+ copy_input(it, in, buf2, nvec, dstr);
998
+ for (size_t i=0; i<nvec; ++i)
999
+ plan.exec_copyback(buf2+i*dstr, buf1, fct, ortho, type, cosine, nthreads);
1000
+ copy_output(it, buf2, out, nvec, dstr);
1001
+ }
1002
+ template <typename T0, typename Tplan> DUCC0_NOINLINE void exec_simple (
1003
+ const T0 *in, T0 *out, const Tplan &plan, T0 fct,
1004
+ size_t nthreads) const
1005
+ {
1006
+ if (in!=out) copy_n(in, plan.length(), out);
1007
+ plan.exec(out, fct, ortho, type, cosine, nthreads);
1008
+ }
1009
+ };
1010
+
1011
+ template<typename T> DUCC0_NOINLINE void general_r2c(
1012
+ const cfmav<T> &in, const vfmav<Cmplx<T>> &out, size_t axis, bool forward, T fct,
1013
+ size_t nthreads)
1014
+ {
1015
+ size_t nth1d = (in.ndim()==1) ? nthreads : 1;
1016
+ auto plan = std::make_unique<pocketfft_r<T>>(in.shape(axis));
1017
+ size_t len=in.shape(axis);
1018
+ execParallel(
1019
+ util::thread_count(nthreads, in, axis, fft_simdlen<T>),
1020
+ [&](Scheduler &sched) {
1021
+ constexpr auto vlen = fft_simdlen<T>;
1022
+ TmpStorage<T,T> storage(in.size()/len, len, plan->bufsize(), 1, false);
1023
+ multi_iter<vlen> it(in, out, axis, sched.num_threads(), sched.thread_num());
1024
+ #ifndef DUCC0_NO_SIMD
1025
+ if constexpr (vlen>1)
1026
+ {
1027
+ TmpStorage2<add_vec_t<T, vlen>,T,T> storage2(storage);
1028
+ auto dbuf = storage2.dataBuf();
1029
+ auto tbuf = storage2.transformBuf();
1030
+ while (it.remaining()>=vlen)
1031
+ {
1032
+ it.advance(vlen);
1033
+ copy_input(it, in, dbuf);
1034
+ auto res = plan->exec(dbuf, tbuf, fct, true, nth1d);
1035
+ auto vout = out.data();
1036
+ for (size_t j=0; j<vlen; ++j)
1037
+ vout[it.oofs(j,0)].Set(res[0][j]);
1038
+ size_t i=1, ii=1;
1039
+ if (forward)
1040
+ for (; i<len-1; i+=2, ++ii)
1041
+ for (size_t j=0; j<vlen; ++j)
1042
+ vout[it.oofs(j,ii)].Set(res[i][j], res[i+1][j]);
1043
+ else
1044
+ for (; i<len-1; i+=2, ++ii)
1045
+ for (size_t j=0; j<vlen; ++j)
1046
+ vout[it.oofs(j,ii)].Set(res[i][j], -res[i+1][j]);
1047
+ if (i<len)
1048
+ for (size_t j=0; j<vlen; ++j)
1049
+ vout[it.oofs(j,ii)].Set(res[i][j]);
1050
+ }
1051
+ }
1052
+ if constexpr (vlen>2)
1053
+ if constexpr (simd_exists<T,vlen/2>)
1054
+ if (it.remaining()>=vlen/2)
1055
+ {
1056
+ TmpStorage2<add_vec_t<T, vlen/2>,T,T> storage2(storage);
1057
+ auto dbuf = storage2.dataBuf();
1058
+ auto tbuf = storage2.transformBuf();
1059
+ it.advance(vlen/2);
1060
+ copy_input(it, in, dbuf);
1061
+ auto res = plan->exec(dbuf, tbuf, fct, true, nth1d);
1062
+ auto vout = out.data();
1063
+ for (size_t j=0; j<vlen/2; ++j)
1064
+ vout[it.oofs(j,0)].Set(res[0][j]);
1065
+ size_t i=1, ii=1;
1066
+ if (forward)
1067
+ for (; i<len-1; i+=2, ++ii)
1068
+ for (size_t j=0; j<vlen/2; ++j)
1069
+ vout[it.oofs(j,ii)].Set(res[i][j], res[i+1][j]);
1070
+ else
1071
+ for (; i<len-1; i+=2, ++ii)
1072
+ for (size_t j=0; j<vlen/2; ++j)
1073
+ vout[it.oofs(j,ii)].Set(res[i][j], -res[i+1][j]);
1074
+ if (i<len)
1075
+ for (size_t j=0; j<vlen/2; ++j)
1076
+ vout[it.oofs(j,ii)].Set(res[i][j]);
1077
+ }
1078
+ if constexpr (vlen>4)
1079
+ if constexpr( simd_exists<T,vlen/4>)
1080
+ if (it.remaining()>=vlen/4)
1081
+ {
1082
+ TmpStorage2<add_vec_t<T, vlen/4>,T,T> storage2(storage);
1083
+ auto dbuf = storage2.dataBuf();
1084
+ auto tbuf = storage2.transformBuf();
1085
+ it.advance(vlen/4);
1086
+ copy_input(it, in, dbuf);
1087
+ auto res = plan->exec(dbuf, tbuf, fct, true, nth1d);
1088
+ auto vout = out.data();
1089
+ for (size_t j=0; j<vlen/4; ++j)
1090
+ vout[it.oofs(j,0)].Set(res[0][j]);
1091
+ size_t i=1, ii=1;
1092
+ if (forward)
1093
+ for (; i<len-1; i+=2, ++ii)
1094
+ for (size_t j=0; j<vlen/4; ++j)
1095
+ vout[it.oofs(j,ii)].Set(res[i][j], res[i+1][j]);
1096
+ else
1097
+ for (; i<len-1; i+=2, ++ii)
1098
+ for (size_t j=0; j<vlen/4; ++j)
1099
+ vout[it.oofs(j,ii)].Set(res[i][j], -res[i+1][j]);
1100
+ if (i<len)
1101
+ for (size_t j=0; j<vlen/4; ++j)
1102
+ vout[it.oofs(j,ii)].Set(res[i][j]);
1103
+ }
1104
+ #endif
1105
+ {
1106
+ TmpStorage2<T,T,T> storage2(storage);
1107
+ auto dbuf = storage2.dataBuf();
1108
+ auto tbuf = storage2.transformBuf();
1109
+ while (it.remaining()>0)
1110
+ {
1111
+ it.advance(1);
1112
+ copy_input(it, in, dbuf);
1113
+ auto res = plan->exec(dbuf, tbuf, fct, true, nth1d);
1114
+ auto vout = out.data();
1115
+ vout[it.oofs(0)].Set(res[0]);
1116
+ size_t i=1, ii=1;
1117
+ if (forward)
1118
+ for (; i<len-1; i+=2, ++ii)
1119
+ vout[it.oofs(ii)].Set(res[i], res[i+1]);
1120
+ else
1121
+ for (; i<len-1; i+=2, ++ii)
1122
+ vout[it.oofs(ii)].Set(res[i], -res[i+1]);
1123
+ if (i<len)
1124
+ vout[it.oofs(ii)].Set(res[i]);
1125
+ }
1126
+ }
1127
+ }); // end of parallel region
1128
+ }
1129
+ template<typename T> DUCC0_NOINLINE void general_c2r(
1130
+ const cfmav<Cmplx<T>> &in, const vfmav<T> &out, size_t axis, bool forward, T fct,
1131
+ size_t nthreads)
1132
+ {
1133
+ size_t nth1d = (in.ndim()==1) ? nthreads : 1;
1134
+ auto plan = std::make_unique<pocketfft_r<T>>(out.shape(axis));
1135
+ size_t len=out.shape(axis);
1136
+ execParallel(
1137
+ util::thread_count(nthreads, in, axis, fft_simdlen<T>),
1138
+ [&](Scheduler &sched) {
1139
+ constexpr auto vlen = fft_simdlen<T>;
1140
+ TmpStorage<T,T> storage(out.size()/len, len, plan->bufsize(), 1, false);
1141
+ multi_iter<vlen> it(in, out, axis, sched.num_threads(), sched.thread_num());
1142
+ #ifndef DUCC0_NO_SIMD
1143
+ if constexpr (vlen>1)
1144
+ {
1145
+ TmpStorage2<add_vec_t<T, vlen>,T,T> storage2(storage);
1146
+ auto dbuf = storage2.dataBuf();
1147
+ auto tbuf = storage2.transformBuf();
1148
+ while (it.remaining()>=vlen)
1149
+ {
1150
+ it.advance(vlen);
1151
+ for (size_t j=0; j<vlen; ++j)
1152
+ dbuf[0][j]=in.raw(it.iofs(j,0)).r;
1153
+ {
1154
+ size_t i=1, ii=1;
1155
+ if (forward)
1156
+ for (; i<len-1; i+=2, ++ii)
1157
+ for (size_t j=0; j<vlen; ++j)
1158
+ {
1159
+ dbuf[i ][j] = in.raw(it.iofs(j,ii)).r;
1160
+ dbuf[i+1][j] = -in.raw(it.iofs(j,ii)).i;
1161
+ }
1162
+ else
1163
+ for (; i<len-1; i+=2, ++ii)
1164
+ for (size_t j=0; j<vlen; ++j)
1165
+ {
1166
+ dbuf[i ][j] = in.raw(it.iofs(j,ii)).r;
1167
+ dbuf[i+1][j] = in.raw(it.iofs(j,ii)).i;
1168
+ }
1169
+ if (i<len)
1170
+ for (size_t j=0; j<vlen; ++j)
1171
+ dbuf[i][j] = in.raw(it.iofs(j,ii)).r;
1172
+ }
1173
+ auto res = plan->exec(dbuf, tbuf, fct, false, nth1d);
1174
+ copy_output(it, res, out);
1175
+ }
1176
+ }
1177
+ if constexpr (vlen>2)
1178
+ if constexpr (simd_exists<T,vlen/2>)
1179
+ if (it.remaining()>=vlen/2)
1180
+ {
1181
+ TmpStorage2<add_vec_t<T, vlen/2>,T,T> storage2(storage);
1182
+ auto dbuf = storage2.dataBuf();
1183
+ auto tbuf = storage2.transformBuf();
1184
+ it.advance(vlen/2);
1185
+ for (size_t j=0; j<vlen/2; ++j)
1186
+ dbuf[0][j]=in.raw(it.iofs(j,0)).r;
1187
+ {
1188
+ size_t i=1, ii=1;
1189
+ if (forward)
1190
+ for (; i<len-1; i+=2, ++ii)
1191
+ for (size_t j=0; j<vlen/2; ++j)
1192
+ {
1193
+ dbuf[i ][j] = in.raw(it.iofs(j,ii)).r;
1194
+ dbuf[i+1][j] = -in.raw(it.iofs(j,ii)).i;
1195
+ }
1196
+ else
1197
+ for (; i<len-1; i+=2, ++ii)
1198
+ for (size_t j=0; j<vlen/2; ++j)
1199
+ {
1200
+ dbuf[i ][j] = in.raw(it.iofs(j,ii)).r;
1201
+ dbuf[i+1][j] = in.raw(it.iofs(j,ii)).i;
1202
+ }
1203
+ if (i<len)
1204
+ for (size_t j=0; j<vlen/2; ++j)
1205
+ dbuf[i][j] = in.raw(it.iofs(j,ii)).r;
1206
+ }
1207
+ auto res = plan->exec(dbuf, tbuf, fct, false, nth1d);
1208
+ copy_output(it, res, out);
1209
+ }
1210
+ if constexpr (vlen>4)
1211
+ if constexpr(simd_exists<T,vlen/4>)
1212
+ if (it.remaining()>=vlen/4)
1213
+ {
1214
+ TmpStorage2<add_vec_t<T, vlen/4>,T,T> storage2(storage);
1215
+ auto dbuf = storage2.dataBuf();
1216
+ auto tbuf = storage2.transformBuf();
1217
+ it.advance(vlen/4);
1218
+ for (size_t j=0; j<vlen/4; ++j)
1219
+ dbuf[0][j]=in.raw(it.iofs(j,0)).r;
1220
+ {
1221
+ size_t i=1, ii=1;
1222
+ if (forward)
1223
+ for (; i<len-1; i+=2, ++ii)
1224
+ for (size_t j=0; j<vlen/4; ++j)
1225
+ {
1226
+ dbuf[i ][j] = in.raw(it.iofs(j,ii)).r;
1227
+ dbuf[i+1][j] = -in.raw(it.iofs(j,ii)).i;
1228
+ }
1229
+ else
1230
+ for (; i<len-1; i+=2, ++ii)
1231
+ for (size_t j=0; j<vlen/4; ++j)
1232
+ {
1233
+ dbuf[i ][j] = in.raw(it.iofs(j,ii)).r;
1234
+ dbuf[i+1][j] = in.raw(it.iofs(j,ii)).i;
1235
+ }
1236
+ if (i<len)
1237
+ for (size_t j=0; j<vlen/4; ++j)
1238
+ dbuf[i][j] = in.raw(it.iofs(j,ii)).r;
1239
+ }
1240
+ auto res = plan->exec(dbuf, tbuf, fct, false, nth1d);
1241
+ copy_output(it, res, out);
1242
+ }
1243
+ #endif
1244
+ {
1245
+ TmpStorage2<T,T,T> storage2(storage);
1246
+ auto dbuf = storage2.dataBuf();
1247
+ auto tbuf = storage2.transformBuf();
1248
+ while (it.remaining()>0)
1249
+ {
1250
+ it.advance(1);
1251
+ dbuf[0]=in.raw(it.iofs(0)).r;
1252
+ {
1253
+ size_t i=1, ii=1;
1254
+ if (forward)
1255
+ for (; i<len-1; i+=2, ++ii)
1256
+ {
1257
+ dbuf[i ] = in.raw(it.iofs(ii)).r;
1258
+ dbuf[i+1] = -in.raw(it.iofs(ii)).i;
1259
+ }
1260
+ else
1261
+ for (; i<len-1; i+=2, ++ii)
1262
+ {
1263
+ dbuf[i ] = in.raw(it.iofs(ii)).r;
1264
+ dbuf[i+1] = in.raw(it.iofs(ii)).i;
1265
+ }
1266
+ if (i<len)
1267
+ dbuf[i] = in.raw(it.iofs(ii)).r;
1268
+ }
1269
+ auto res = plan->exec(dbuf, tbuf, fct, false, nth1d);
1270
+ copy_output(it, res, out);
1271
+ }
1272
+ }
1273
+ }); // end of parallel region
1274
+ }
1275
+
1276
+ struct ExecR2R
1277
+ {
1278
+ bool r2c, forward;
1279
+
1280
+ template <typename T0, typename Tstorage, typename Titer> DUCC0_NOINLINE void operator() (
1281
+ const Titer &it, const cfmav<T0> &in, const vfmav<T0> &out, Tstorage &storage,
1282
+ const pocketfft_r<T0> &plan, T0 fct, size_t nthreads,
1283
+ bool inplace=false) const
1284
+ {
1285
+ using T = typename Tstorage::datatype;
1286
+ if constexpr(is_same<T0, T>::value)
1287
+ if (inplace)
1288
+ {
1289
+ T *buf1=storage.transformBuf(), *buf2=out.data()+it.oofs(0);
1290
+ if (in.data()!=buf2)
1291
+ copy_input(it, in, buf2);
1292
+ if ((!r2c) && forward)
1293
+ for (size_t i=2; i<it.length_out(); i+=2)
1294
+ buf2[i] = -buf2[i];
1295
+ plan.exec_copyback(buf2, buf1, fct, r2c, nthreads);
1296
+ if (r2c && (!forward))
1297
+ for (size_t i=2; i<it.length_out(); i+=2)
1298
+ buf2[i] = -buf2[i];
1299
+ return;
1300
+ }
1301
+
1302
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
1303
+ copy_input(it, in, buf2);
1304
+ if ((!r2c) && forward)
1305
+ for (size_t i=2; i<it.length_out(); i+=2)
1306
+ buf2[i] = -buf2[i];
1307
+ auto res = plan.exec(buf2, buf1, fct, r2c, nthreads);
1308
+ if (r2c && (!forward))
1309
+ for (size_t i=2; i<it.length_out(); i+=2)
1310
+ res[i] = -res[i];
1311
+ copy_output(it, res, out);
1312
+ }
1313
+ template <typename T0, typename Tstorage, typename Titer> DUCC0_NOINLINE void exec_n (
1314
+ const Titer &it, const cfmav<T0> &in,
1315
+ const vfmav<T0> &out, Tstorage &storage, const pocketfft_r<T0> &plan, T0 fct, size_t nvec,
1316
+ size_t nthreads) const
1317
+ {
1318
+ using T = typename Tstorage::datatype;
1319
+ size_t dstr = storage.data_stride();
1320
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
1321
+ copy_input(it, in, buf2, nvec, dstr);
1322
+ if ((!r2c) && forward)
1323
+ for (size_t k=0; k<nvec; ++k)
1324
+ for (size_t i=2; i<it.length_out(); i+=2)
1325
+ buf2[i+k*dstr] = -buf2[i+k*dstr];
1326
+ for (size_t i=0; i<nvec; ++i)
1327
+ plan.exec_copyback(buf2+i*dstr, buf1, fct, r2c, nthreads);
1328
+ if (r2c && (!forward))
1329
+ for (size_t k=0; k<nvec; ++k)
1330
+ for (size_t i=2; i<it.length_out(); i+=2)
1331
+ buf2[i+k*dstr] = -buf2[i+k*dstr];
1332
+ copy_output(it, buf2, out, nvec, dstr);
1333
+ }
1334
+ template <typename T0> DUCC0_NOINLINE void exec_simple (
1335
+ const T0 *in, T0 *out, const pocketfft_r<T0> &plan, T0 fct,
1336
+ size_t nthreads) const
1337
+ {
1338
+ if (in!=out) copy_n(in, plan.length(), out);
1339
+ if ((!r2c) && forward)
1340
+ for (size_t i=2; i<plan.length(); i+=2)
1341
+ out[i] = -out[i];
1342
+ plan.exec(out, fct, r2c, nthreads);
1343
+ if (r2c && (!forward))
1344
+ for (size_t i=2; i<plan.length(); i+=2)
1345
+ out[i] = -out[i];
1346
+ }
1347
+ };
1348
+
1349
+ template<typename T> class Long1dPlan: public UnityRoots<T,complex<T>>
1350
+ {
1351
+ public:
1352
+ Long1dPlan(size_t length, bool)
1353
+ : UnityRoots<T,complex<T>>(length) {}
1354
+ };
1355
+
1356
+ template<typename T> DUCC0_NOINLINE void c2c(const cfmav<std::complex<T>> &in,
1357
+ const vfmav<std::complex<T>> &out, const shape_t &axes, bool forward,
1358
+ T fct, size_t nthreads)
1359
+ {
1360
+ util::sanity_check_onetype(in, out, in.data()==out.data(), axes);
1361
+ if (in.size()==0) return;
1362
+
1363
+ // special treatment for long 1D transforms (Bailey's algorithm)
1364
+ // TODO:
1365
+ // - if not in-place and out has no critical stride, the "tmp" array can be avoided
1366
+ if ((in.ndim()==1) && (in.shape(0)>=65536*2))
1367
+ {
1368
+ size_t ip = in.shape(0);
1369
+ auto factors = util1d::prime_factors(ip);
1370
+ sort(factors.begin(), factors.end(), std::greater<size_t>());
1371
+ size_t f1=1, f2=1;
1372
+ for (auto fct: factors)
1373
+ (f2>f1) ? f1*=fct : f2*=fct;
1374
+ if (f1>f2) swap(f1,f2);
1375
+ if (f1>=16) // 2D algorithm makes sense
1376
+ {
1377
+ auto istr=in.stride(0);
1378
+ auto ostr=out.stride(0);
1379
+ cmav<std::complex<T>,2> in2 (in.data(), {f1,f2}, {ptrdiff_t(f2)*istr, istr});
1380
+ auto tmp (vmav<std::complex<T>,2>::build_noncritical({f1,f2}));
1381
+ vmav<std::complex<T>,2> out2 (out.data(), {f1,f2}, {ostr, ptrdiff_t(f1)*ostr});
1382
+ auto fin2(in2.to_fmav());
1383
+ auto ftmp(tmp.to_fmav());
1384
+ auto fout2(out2.to_fmav());
1385
+ c2c(fin2, ftmp, {0}, forward, T(1), nthreads);
1386
+ auto roots_p = get_plan<Long1dPlan<T>>(ip);
1387
+ const auto &roots(*roots_p);
1388
+ if (forward)
1389
+ execStatic(f1, nthreads, 0, [&](Scheduler &sched) {
1390
+ while (auto rng=sched.getNext())
1391
+ for (auto i=rng.lo; i<rng.hi; ++i)
1392
+ for (size_t j=0; j<f2; ++j)
1393
+ tmp(i,j) *= conj(roots[i*j]);
1394
+ });
1395
+ else
1396
+ execStatic(f1, nthreads, 0, [&](Scheduler &sched) {
1397
+ while (auto rng=sched.getNext())
1398
+ for (auto i=rng.lo; i<rng.hi; ++i)
1399
+ for (size_t j=0; j<f2; ++j)
1400
+ tmp(i,j) *= roots[i*j];
1401
+ });
1402
+ c2c(ftmp, fout2, {1}, forward, fct, nthreads);
1403
+ return;
1404
+ }
1405
+ }
1406
+
1407
+ const auto &in2(reinterpret_cast<const cfmav<Cmplx<T> >&>(in));
1408
+ const auto &out2(reinterpret_cast<const vfmav<Cmplx<T> >&>(out));
1409
+ if ((axes.size()>1) && (in.data()!=out.data())) // optimize axis order
1410
+ {
1411
+ if ((in.stride(axes[0])!=1)&&(out.stride(axes[0])==1))
1412
+ {
1413
+ shape_t axes2(axes);
1414
+ swap(axes2[0],axes2.back());
1415
+ general_nd<pocketfft_c<T>>(in2, out2, axes2, fct, nthreads, ExecC2C{forward});
1416
+ return;
1417
+ }
1418
+ for (size_t i=1; i<axes.size(); ++i)
1419
+ if (in.stride(axes[i])==1)
1420
+ {
1421
+ shape_t axes2(axes);
1422
+ swap(axes2[0],axes2[i]);
1423
+ general_nd<pocketfft_c<T>>(in2, out2, axes2, fct, nthreads, ExecC2C{forward});
1424
+ return;
1425
+ }
1426
+ }
1427
+ general_nd<pocketfft_c<T>>(in2, out2, axes, fct, nthreads, ExecC2C{forward});
1428
+ }
1429
+
1430
+ template<typename T> DUCC0_NOINLINE void dct(const cfmav<T> &in, const vfmav<T> &out,
1431
+ const shape_t &axes, int type, T fct, bool ortho, size_t nthreads)
1432
+ {
1433
+ if ((type<1) || (type>4)) throw std::invalid_argument("invalid DCT type");
1434
+ util::sanity_check_onetype(in, out, in.data()==out.data(), axes);
1435
+ if (in.size()==0) return;
1436
+ const ExecDcst exec{ortho, type, true};
1437
+ if (type==1)
1438
+ general_nd<T_dct1<T>>(in, out, axes, fct, nthreads, exec);
1439
+ else if (type==4)
1440
+ general_nd<T_dcst4<T>>(in, out, axes, fct, nthreads, exec);
1441
+ else
1442
+ general_nd<T_dcst23<T>>(in, out, axes, fct, nthreads, exec);
1443
+ }
1444
+
1445
+ template<typename T> DUCC0_NOINLINE void dst(const cfmav<T> &in, const vfmav<T> &out,
1446
+ const shape_t &axes, int type, T fct, bool ortho, size_t nthreads)
1447
+ {
1448
+ if ((type<1) || (type>4)) throw std::invalid_argument("invalid DST type");
1449
+ util::sanity_check_onetype(in, out, in.data()==out.data(), axes);
1450
+ if (in.size()==0) return;
1451
+ const ExecDcst exec{ortho, type, false};
1452
+ if (type==1)
1453
+ general_nd<T_dst1<T>>(in, out, axes, fct, nthreads, exec);
1454
+ else if (type==4)
1455
+ general_nd<T_dcst4<T>>(in, out, axes, fct, nthreads, exec);
1456
+ else
1457
+ general_nd<T_dcst23<T>>(in, out, axes, fct, nthreads, exec);
1458
+ }
1459
+
1460
+ template<typename T> DUCC0_NOINLINE void r2c(const cfmav<T> &in,
1461
+ const vfmav<std::complex<T>> &out, size_t axis, bool forward, T fct,
1462
+ size_t nthreads)
1463
+ {
1464
+ util::sanity_check_cr(out, in, axis);
1465
+ if (in.size()==0) return;
1466
+ const auto &out2(reinterpret_cast<const vfmav<Cmplx<T>>&>(out));
1467
+ general_r2c(in, out2, axis, forward, fct, nthreads);
1468
+ }
1469
+
1470
+ template<typename T> DUCC0_NOINLINE void r2c(const cfmav<T> &in,
1471
+ const vfmav<std::complex<T>> &out, const shape_t &axes,
1472
+ bool forward, T fct, size_t nthreads)
1473
+ {
1474
+ util::sanity_check_cr(out, in, axes);
1475
+ if (in.size()==0) return;
1476
+ r2c(in, out, axes.back(), forward, fct, nthreads);
1477
+ if (axes.size()==1) return;
1478
+
1479
+ auto newaxes = shape_t{axes.begin(), --axes.end()};
1480
+ c2c(out, out, newaxes, forward, T(1), nthreads);
1481
+ }
1482
+
1483
+ template<typename T> DUCC0_NOINLINE void c2r(const cfmav<std::complex<T>> &in,
1484
+ const vfmav<T> &out, size_t axis, bool forward, T fct, size_t nthreads)
1485
+ {
1486
+ util::sanity_check_cr(in, out, axis);
1487
+ if (in.size()==0) return;
1488
+ const auto &in2(reinterpret_cast<const cfmav<Cmplx<T>>&>(in));
1489
+ general_c2r(in2, out, axis, forward, fct, nthreads);
1490
+ }
1491
+
1492
+ template<typename T> DUCC0_NOINLINE void c2r(const cfmav<std::complex<T>> &in,
1493
+ const vfmav<T> &out, const shape_t &axes, bool forward, T fct,
1494
+ size_t nthreads)
1495
+ {
1496
+ if (axes.size()==1)
1497
+ return c2r(in, out, axes[0], forward, fct, nthreads);
1498
+ util::sanity_check_cr(in, out, axes);
1499
+ if (in.size()==0) return;
1500
+ auto atmp(vfmav<std::complex<T>>::build_noncritical(in.shape(), UNINITIALIZED));
1501
+ auto newaxes = shape_t{axes.begin(), --axes.end()};
1502
+ c2c(in, atmp, newaxes, forward, T(1), nthreads);
1503
+ c2r(atmp, out, axes.back(), forward, fct, nthreads);
1504
+ }
1505
+
1506
+ template<typename T> DUCC0_NOINLINE void c2r_mut(const vfmav<std::complex<T>> &in,
1507
+ const vfmav<T> &out, const shape_t &axes, bool forward, T fct,
1508
+ size_t nthreads)
1509
+ {
1510
+ if (axes.size()==1)
1511
+ return c2r(in, out, axes[0], forward, fct, nthreads);
1512
+ util::sanity_check_cr(in, out, axes);
1513
+ if (in.size()==0) return;
1514
+ auto newaxes = shape_t{axes.begin(), --axes.end()};
1515
+ c2c(in, in, newaxes, forward, T(1), nthreads);
1516
+ c2r(in, out, axes.back(), forward, fct, nthreads);
1517
+ }
1518
+
1519
+ template<typename T> DUCC0_NOINLINE void r2r_fftpack(const cfmav<T> &in,
1520
+ const vfmav<T> &out, const shape_t &axes, bool real2hermitian, bool forward,
1521
+ T fct, size_t nthreads)
1522
+ {
1523
+ util::sanity_check_onetype(in, out, in.data()==out.data(), axes);
1524
+ if (in.size()==0) return;
1525
+ general_nd<pocketfft_r<T>>(in, out, axes, fct, nthreads,
1526
+ ExecR2R{real2hermitian, forward});
1527
+ }
1528
+
1529
+ template<typename T> DUCC0_NOINLINE void r2r_fftw(const cfmav<T> &in,
1530
+ const vfmav<T> &out, const shape_t &axes, bool forward,
1531
+ T fct, size_t nthreads)
1532
+ {
1533
+ util::sanity_check_onetype(in, out, in.data()==out.data(), axes);
1534
+ if (in.size()==0) return;
1535
+ general_nd<pocketfft_fftw<T>>(in, out, axes, fct, nthreads,
1536
+ ExecFFTW{forward});
1537
+ }
1538
+
1539
+ template<typename T> DUCC0_NOINLINE void r2r_separable_hartley(const cfmav<T> &in,
1540
+ const vfmav<T> &out, const shape_t &axes, T fct, size_t nthreads)
1541
+ {
1542
+ util::sanity_check_onetype(in, out, in.data()==out.data(), axes);
1543
+ if (in.size()==0) return;
1544
+ general_nd<pocketfft_hartley<T>>(in, out, axes, fct, nthreads,
1545
+ ExecHartley{}, false);
1546
+ }
1547
+
1548
+ template<typename T> DUCC0_NOINLINE void r2r_separable_fht(const cfmav<T> &in,
1549
+ const vfmav<T> &out, const shape_t &axes, T fct, size_t nthreads)
1550
+ {
1551
+ util::sanity_check_onetype(in, out, in.data()==out.data(), axes);
1552
+ if (in.size()==0) return;
1553
+ general_nd<pocketfft_fht<T>>(in, out, axes, fct, nthreads,
1554
+ ExecFHT{}, false);
1555
+ }
1556
+
1557
+ template<typename T0, typename T1, typename Func> void hermiteHelper(size_t idim, ptrdiff_t iin,
1558
+ ptrdiff_t iout0, ptrdiff_t iout1, const cfmav<T0> &c,
1559
+ const vfmav<T1> &r, const shape_t &axes, Func func, size_t nthreads)
1560
+ {
1561
+ auto cstr=c.stride(idim), str=r.stride(idim);
1562
+ auto len=r.shape(idim);
1563
+
1564
+ if (idim+1==c.ndim()) // last dimension, not much gain in parallelizing
1565
+ {
1566
+ if (idim==axes.back()) // halfcomplex axis
1567
+ for (size_t i=0,ic=0; i<len/2+1; ++i,ic=len-i)
1568
+ func (c.raw(iin+i*cstr), r.raw(iout0+i*str), r.raw(iout1+ic*str));
1569
+ else if (find(axes.begin(), axes.end(), idim) != axes.end()) // FFT axis
1570
+ for (size_t i=0,ic=0; i<len; ++i,ic=len-i)
1571
+ func (c.raw(iin+i*cstr), r.raw(iout0+i*str), r.raw(iout1+ic*str));
1572
+ else // non-FFT axis
1573
+ for (size_t i=0; i<len; ++i)
1574
+ func (c.raw(iin+i*cstr), r.raw(iout0+i*str), r.raw(iout1+i*str));
1575
+ }
1576
+ else
1577
+ {
1578
+ if (idim==axes.back())
1579
+ {
1580
+ if (nthreads==1)
1581
+ for (size_t i=0,ic=0; i<len/2+1; ++i,ic=len-i)
1582
+ hermiteHelper(idim+1, iin+i*cstr, iout0+i*str, iout1+ic*str, c, r, axes, func, 1);
1583
+ else
1584
+ execParallel(0, len/2+1, nthreads, [&](size_t lo, size_t hi)
1585
+ {
1586
+ for (size_t i=lo,ic=(i==0?0:len-i); i<hi; ++i,ic=len-i)
1587
+ hermiteHelper(idim+1, iin+i*cstr, iout0+i*str, iout1+ic*str, c, r, axes, func, 1);
1588
+ });
1589
+ }
1590
+ else if (find(axes.begin(), axes.end(), idim) != axes.end())
1591
+ {
1592
+ if (nthreads==1)
1593
+ for (size_t i=0,ic=0; i<len; ++i,ic=len-i)
1594
+ hermiteHelper(idim+1, iin+i*cstr, iout0+i*str, iout1+ic*str, c, r, axes, func, 1);
1595
+ else
1596
+ execParallel(0, len/2+1, nthreads, [&](size_t lo, size_t hi)
1597
+ {
1598
+ for (size_t i=lo,ic=(i==0?0:len-i); i<hi; ++i,ic=len-i)
1599
+ {
1600
+ size_t io0=iout0+i*str, io1=iout1+ic*str;
1601
+ hermiteHelper(idim+1, iin+i*cstr, io0, io1, c, r, axes, func, 1);
1602
+ if (i!=ic)
1603
+ hermiteHelper(idim+1, iin+ic*cstr, io1, io0, c, r, axes, func, 1);
1604
+ }
1605
+ });
1606
+ }
1607
+ else
1608
+ {
1609
+ if (nthreads==1)
1610
+ for (size_t i=0; i<len; ++i)
1611
+ hermiteHelper(idim+1, iin+i*cstr, iout0+i*str, iout1+i*str, c, r, axes, func, 1);
1612
+ else
1613
+ execParallel(0, len, nthreads, [&](size_t lo, size_t hi)
1614
+ {
1615
+ for (size_t i=lo; i<hi; ++i)
1616
+ hermiteHelper(idim+1, iin+i*cstr, iout0+i*str, iout1+i*str, c, r, axes, func, 1);
1617
+ });
1618
+ }
1619
+ }
1620
+ }
1621
+
1622
+ template<typename T> void oscarize(const vfmav<T> &data, size_t ax0, size_t ax1,
1623
+ size_t nthreads)
1624
+ {
1625
+ auto nu=data.shape(ax0), nv=data.shape(ax1);
1626
+ if ((nu<3)||(nv<3)) return;
1627
+ vector<slice> slc(data.ndim());
1628
+ slc[ax0] = slice(1,(nu+1)/2);
1629
+ slc[ax1] = slice(1,(nv+1)/2);
1630
+ auto all = subarray(data, slc);
1631
+ slc[ax0] = slice(nu-1,nu/2,-1);
1632
+ auto ahl = subarray(data, slc);
1633
+ slc[ax1] = slice(nv-1,nv/2,-1);
1634
+ auto ahh = subarray(data, slc);
1635
+ slc[ax0] = slice(1,(nu+1)/2);
1636
+ auto alh = subarray(data, slc);
1637
+ mav_apply([](T &ll, T &hl, T &hh, T &lh)
1638
+ {
1639
+ T tll=ll, thl=hl, tlh=lh, thh=hh;
1640
+ T v = T(0.5)*(tll+tlh+thl+thh);
1641
+ ll = v-thh;
1642
+ hl = v-tlh;
1643
+ lh = v-thl;
1644
+ hh = v-tll;
1645
+ }, nthreads, all, ahl, ahh, alh);
1646
+ }
1647
+
1648
+ template<typename T> void r2r_genuine_hartley(const cfmav<T> &in,
1649
+ const vfmav<T> &out, const shape_t &axes, T fct, size_t nthreads)
1650
+ {
1651
+ if (axes.size()==1)
1652
+ return r2r_separable_hartley(in, out, axes, fct, nthreads);
1653
+ if (axes.size()==2)
1654
+ {
1655
+ r2r_separable_hartley(in, out, axes, fct, nthreads);
1656
+ oscarize(out, axes[0], axes[1], nthreads);
1657
+ return;
1658
+ }
1659
+ util::sanity_check_onetype(in, out, in.data()==out.data(), axes);
1660
+ if (in.size()==0) return;
1661
+ shape_t tshp(in.shape());
1662
+ tshp[axes.back()] = tshp[axes.back()]/2+1;
1663
+ auto atmp(vfmav<std::complex<T>>::build_noncritical(tshp, UNINITIALIZED));
1664
+ r2c(in, atmp, axes, true, fct, nthreads);
1665
+ hermiteHelper(0, 0, 0, 0, atmp, out, axes, [](const std::complex<T> &c, T &r0, T &r1)
1666
+ {
1667
+ auto ccopy = c;
1668
+ r0 = ccopy.real()+ccopy.imag();
1669
+ r1 = ccopy.real()-ccopy.imag();
1670
+ }, nthreads);
1671
+ }
1672
+
1673
+ template<typename T> void r2r_genuine_fht(const cfmav<T> &in,
1674
+ const vfmav<T> &out, const shape_t &axes, T fct, size_t nthreads)
1675
+ {
1676
+ if (axes.size()==1)
1677
+ return r2r_separable_fht(in, out, axes, fct, nthreads);
1678
+ if (axes.size()==2)
1679
+ {
1680
+ r2r_separable_fht(in, out, axes, fct, nthreads);
1681
+ oscarize(out, axes[0], axes[1], nthreads);
1682
+ return;
1683
+ }
1684
+ util::sanity_check_onetype(in, out, in.data()==out.data(), axes);
1685
+ if (in.size()==0) return;
1686
+ shape_t tshp(in.shape());
1687
+ tshp[axes.back()] = tshp[axes.back()]/2+1;
1688
+ auto atmp(vfmav<std::complex<T>>::build_noncritical(tshp, UNINITIALIZED));
1689
+ r2c(in, atmp, axes, true, fct, nthreads);
1690
+ hermiteHelper(0, 0, 0, 0, atmp, out, axes, [](const std::complex<T> &c, T &r0, T &r1)
1691
+ {
1692
+ auto ccopy = c;
1693
+ r0 = ccopy.real()-ccopy.imag();
1694
+ r1 = ccopy.real()+ccopy.imag();
1695
+ }, nthreads);
1696
+ }
1697
+
1698
+ template<typename Tplan, typename T0, typename T, typename Exec>
1699
+ DUCC0_NOINLINE void general_convolve_axis(const cfmav<T> &in, const vfmav<T> &out,
1700
+ const size_t axis, const cmav<T,1> &kernel, size_t nthreads,
1701
+ const Exec &exec)
1702
+ {
1703
+ std::unique_ptr<Tplan> plan1, plan2;
1704
+
1705
+ size_t l_in=in.shape(axis), l_out=out.shape(axis);
1706
+ MR_assert(kernel.size()==l_in, "bad kernel size");
1707
+ plan1 = std::make_unique<Tplan>(l_in);
1708
+ plan2 = std::make_unique<Tplan>(l_out);
1709
+ size_t bufsz = max(plan1->bufsize(), plan2->bufsize());
1710
+
1711
+ vmav<T,1> fkernel({kernel.shape(0)}, UNINITIALIZED);
1712
+ for (size_t i=0; i<kernel.shape(0); ++i)
1713
+ fkernel(i) = kernel(i);
1714
+ plan1->exec(fkernel.data(), T0(1)/T0(l_in), true, nthreads);
1715
+
1716
+ execParallel(
1717
+ util::thread_count(nthreads, in, axis, fft_simdlen<T0>),
1718
+ [&](Scheduler &sched) {
1719
+ constexpr auto vlen = fft_simdlen<T0>;
1720
+ TmpStorage<T,T0> storage(in.size()/l_in, l_in+l_out, bufsz, 1, false);
1721
+ multi_iter<vlen> it(in, out, axis, sched.num_threads(), sched.thread_num());
1722
+ #ifndef DUCC0_NO_SIMD
1723
+ if constexpr (vlen>1)
1724
+ {
1725
+ TmpStorage2<add_vec_t<T, vlen>,T,T0> storage2(storage);
1726
+ while (it.remaining()>=vlen)
1727
+ {
1728
+ it.advance(vlen);
1729
+ exec(it, in, out, storage2, *plan1, *plan2, fkernel);
1730
+ }
1731
+ }
1732
+ if constexpr (vlen>2)
1733
+ if constexpr (simd_exists<T,vlen/2>)
1734
+ if (it.remaining()>=vlen/2)
1735
+ {
1736
+ TmpStorage2<add_vec_t<T, vlen/2>,T,T0> storage2(storage);
1737
+ it.advance(vlen/2);
1738
+ exec(it, in, out, storage2, *plan1, *plan2, fkernel);
1739
+ }
1740
+ if constexpr (vlen>4)
1741
+ if constexpr (simd_exists<T,vlen/4>)
1742
+ if (it.remaining()>=vlen/4)
1743
+ {
1744
+ TmpStorage2<add_vec_t<T, vlen/4>,T,T0> storage2(storage);
1745
+ it.advance(vlen/4);
1746
+ exec(it, in, out, storage2, *plan1, *plan2, fkernel);
1747
+ }
1748
+ #endif
1749
+ {
1750
+ TmpStorage2<T,T,T0> storage2(storage);
1751
+ while (it.remaining()>0)
1752
+ {
1753
+ it.advance(1);
1754
+ exec(it, in, out, storage2, *plan1, *plan2, fkernel);
1755
+ }
1756
+ }
1757
+ }); // end of parallel region
1758
+ }
1759
+
1760
+ struct ExecConv1R
1761
+ {
1762
+ template <typename T0, typename Tstorage, typename Titer> void operator() (
1763
+ const Titer &it, const cfmav<T0> &in, const vfmav<T0> &out,
1764
+ Tstorage &storage, const pocketfft_r<T0> &plan1, const pocketfft_r<T0> &plan2,
1765
+ const cmav<T0,1> &fkernel) const
1766
+ {
1767
+ using T = typename Tstorage::datatype;
1768
+ size_t l_in = plan1.length(),
1769
+ l_out = plan2.length(),
1770
+ l_min = std::min(l_in, l_out);
1771
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
1772
+ copy_input(it, in, buf2);
1773
+ plan1.exec_copyback(buf2, buf1, T0(1), true);
1774
+ auto res = buf2;
1775
+ {
1776
+ res[0] *= fkernel(0);
1777
+ size_t i;
1778
+ for (i=1; 2*i<l_min; ++i)
1779
+ {
1780
+ Cmplx<T> t1(res[2*i-1], res[2*i]);
1781
+ Cmplx<T0> t2(fkernel(2*i-1), fkernel(2*i));
1782
+ auto t3 = t1*t2;
1783
+ res[2*i-1] = t3.r;
1784
+ res[2*i] = t3.i;
1785
+ }
1786
+ if (2*i==l_min)
1787
+ {
1788
+ if (l_min<l_out) // padding
1789
+ res[2*i-1] *= fkernel(2*i-1)*T0(0.5);
1790
+ else if (l_min<l_in) // truncation
1791
+ {
1792
+ Cmplx<T> t1(res[2*i-1], res[2*i]);
1793
+ Cmplx<T0> t2(fkernel(2*i-1), fkernel(2*i));
1794
+ res[2*i-1] = (t1*t2).r*T0(2);
1795
+ }
1796
+ else
1797
+ res[2*i-1] *= fkernel(2*i-1);
1798
+ }
1799
+ }
1800
+ for (size_t i=l_in; i<l_out; ++i) res[i] = T(0);
1801
+ res = plan2.exec(res, buf1, T0(1), false);
1802
+ copy_output(it, res, out);
1803
+ }
1804
+ };
1805
+ struct ExecConv1C
1806
+ {
1807
+ template <typename T0, typename Tstorage, typename Titer> void operator() (
1808
+ const Titer &it, const cfmav<Cmplx<T0>> &in, const vfmav<Cmplx<T0>> &out,
1809
+ Tstorage &storage, const pocketfft_c<T0> &plan1, const pocketfft_c<T0> &plan2,
1810
+ const cmav<Cmplx<T0>,1> &fkernel) const
1811
+ {
1812
+ using T = typename Tstorage::datatype;
1813
+ size_t l_in = plan1.length(),
1814
+ l_out = plan2.length(),
1815
+ l_min = std::min(l_in, l_out);
1816
+ T *buf1=storage.transformBuf(), *buf2=storage.dataBuf();
1817
+ copy_input(it, in, buf2);
1818
+ auto res = plan1.exec(buf2, buf1, T0(1), true);
1819
+ auto res2 = buf2+l_in;
1820
+ {
1821
+ res2[0] = res[0]*fkernel(0);
1822
+ size_t i;
1823
+ for (i=1; 2*i<l_min; ++i)
1824
+ {
1825
+ res2[i] = res[i]*fkernel(i);
1826
+ res2[l_out-i] = res[l_in-i]*fkernel(l_in-i);
1827
+ }
1828
+ if (2*i==l_min)
1829
+ {
1830
+ if (l_min<l_out) // padding
1831
+ res2[l_out-i] = res2[i] = res[i]*fkernel(i)*T0(.5);
1832
+ else if (l_min<l_in) // truncation
1833
+ res2[i] = res[i]*fkernel(i) + res[l_in-i]*fkernel(l_in-i);
1834
+ else
1835
+ res2[i] = res[i]*fkernel(i);
1836
+ ++i;
1837
+ }
1838
+ for (; 2*i<=l_out; ++i)
1839
+ res2[i] = res2[l_out-i] = T(0,0);
1840
+ }
1841
+ res = plan2.exec(res2, buf1, T0(1), false);
1842
+ copy_output(it, res, out);
1843
+ }
1844
+ };
1845
+
1846
+ template<typename T> DUCC0_NOINLINE void convolve_axis(const cfmav<T> &in,
1847
+ const vfmav<T> &out, size_t axis, const cmav<T,1> &kernel, size_t nthreads)
1848
+ {
1849
+ MR_assert(axis<in.ndim(), "bad axis number");
1850
+ MR_assert(in.ndim()==out.ndim(), "dimensionality mismatch");
1851
+ if (in.data()==out.data())
1852
+ MR_assert(in.stride()==out.stride(), "strides mismatch");
1853
+ for (size_t i=0; i<in.ndim(); ++i)
1854
+ if (i!=axis)
1855
+ MR_assert(in.shape(i)==out.shape(i), "shape mismatch");
1856
+ if (in.size()==0) return;
1857
+ general_convolve_axis<pocketfft_r<T>, T>(in, out, axis, kernel, nthreads,
1858
+ ExecConv1R());
1859
+ }
1860
+ template<typename T> DUCC0_NOINLINE void convolve_axis(const cfmav<complex<T>> &in,
1861
+ const vfmav<complex<T>> &out, size_t axis, const cmav<complex<T>,1> &kernel,
1862
+ size_t nthreads)
1863
+ {
1864
+ MR_assert(axis<in.ndim(), "bad axis number");
1865
+ MR_assert(in.ndim()==out.ndim(), "dimensionality mismatch");
1866
+ if (in.data()==out.data())
1867
+ MR_assert(in.stride()==out.stride(), "strides mismatch");
1868
+ for (size_t i=0; i<in.ndim(); ++i)
1869
+ if (i!=axis)
1870
+ MR_assert(in.shape(i)==out.shape(i), "shape mismatch");
1871
+ if (in.size()==0) return;
1872
+ const auto &in2(reinterpret_cast<const cfmav<Cmplx<T>>&>(in));
1873
+ const auto &out2(reinterpret_cast<const vfmav<Cmplx<T>>&>(out));
1874
+ const auto &kernel2(reinterpret_cast<const cmav<Cmplx<T>,1>&>(kernel));
1875
+ general_convolve_axis<pocketfft_c<T>, T>(in2, out2, axis, kernel2, nthreads,
1876
+ ExecConv1C());
1877
+ }
1878
+
1879
+ } // namespace detail_fft
1880
+
1881
+ } // namespace ducc0
1882
+
1883
+ #endif // POCKETFFT_HDRONLY_H
deps/exla/cache/xla_extension/include/_virtual_includes/fft/ducc/src/ducc0/infra/mav.h ADDED
@@ -0,0 +1,1354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*! \file ducc0/infra/mav.h
2
+ * Classes for dealing with multidimensional arrays
3
+ *
4
+ * \copyright Copyright (C) 2019-2024 Max-Planck-Society
5
+ * \author Martin Reinecke
6
+ * */
7
+
8
+ /* SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0-or-later */
9
+
10
+ /*
11
+ All rights reserved.
12
+
13
+ Redistribution and use in source and binary forms, with or without modification,
14
+ are permitted provided that the following conditions are met:
15
+
16
+ * Redistributions of source code must retain the above copyright notice, this
17
+ list of conditions and the following disclaimer.
18
+ * Redistributions in binary form must reproduce the above copyright notice, this
19
+ list of conditions and the following disclaimer in the documentation and/or
20
+ other materials provided with the distribution.
21
+ * Neither the name of the copyright holder nor the names of its contributors may
22
+ be used to endorse or promote products derived from this software without
23
+ specific prior written permission.
24
+
25
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
26
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
27
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
29
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
32
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
+ */
36
+
37
+ /*
38
+ * This code is free software; you can redistribute it and/or modify
39
+ * it under the terms of the GNU General Public License as published by
40
+ * the Free Software Foundation; either version 2 of the License, or
41
+ * (at your option) any later version.
42
+ *
43
+ * This code is distributed in the hope that it will be useful,
44
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
45
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46
+ * GNU General Public License for more details.
47
+ *
48
+ * You should have received a copy of the GNU General Public License
49
+ * along with this code; if not, write to the Free Software
50
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
51
+ */
52
+
53
+ #ifndef DUCC0_MAV_H
54
+ #define DUCC0_MAV_H
55
+
56
+ #include <array>
57
+ #include <vector>
58
+ #include <memory>
59
+ #include <numeric>
60
+ #include <cstddef>
61
+ #include <functional>
62
+ #include <tuple>
63
+ #include "ducc0/infra/error_handling.h"
64
+ #include "ducc0/infra/aligned_array.h"
65
+ #include "ducc0/infra/misc_utils.h"
66
+ #include "ducc0/infra/threading.h"
67
+
68
+ namespace ducc0 {
69
+
70
+ namespace detail_mav {
71
+
72
+ using namespace std;
73
+
74
+ // the next line is necessary to address some sloppy name choices in AdaptiveCpp
75
+ using std::min, std::max;
76
+
77
+ struct uninitialized_dummy {};
78
+ constexpr uninitialized_dummy UNINITIALIZED;
79
+
80
+ template<typename T> class cmembuf
81
+ {
82
+ protected:
83
+ shared_ptr<vector<T>> ptr;
84
+ shared_ptr<quick_array<T>> rawptr;
85
+ const T *d;
86
+
87
+ cmembuf(const T *d_, const cmembuf &other)
88
+ : ptr(other.ptr), rawptr(other.rawptr), d(d_) {}
89
+
90
+ // externally owned data pointer
91
+ cmembuf(const T *d_)
92
+ : d(d_) {}
93
+ // share another memory buffer, but read-only
94
+ cmembuf(const cmembuf &other)
95
+ : ptr(other.ptr), rawptr(other.rawptr), d(other.d) {}
96
+ cmembuf(size_t sz)
97
+ : ptr(make_shared<vector<T>>(sz)), d(ptr->data()) {}
98
+ #if 1
99
+ cmembuf(size_t sz, uninitialized_dummy)
100
+ : rawptr(make_shared<quick_array<T>>(sz)), d(rawptr->data()) {}
101
+ # else // "poison" the array with a fixed value; use for debugging
102
+ cmembuf(size_t sz, uninitialized_dummy)
103
+ : rawptr(make_shared<quick_array<T>>(sz)), d(rawptr->data())
104
+ { for (size_t i=0; i<sz; ++i) (*rawptr)[i]=T(42000000); }
105
+ #endif
106
+ // take over another memory buffer
107
+ cmembuf(cmembuf &&other) = default;
108
+
109
+ public:
110
+ cmembuf(): d(nullptr) {}
111
+ void assign(const cmembuf &other)
112
+ {
113
+ ptr = other.ptr;
114
+ rawptr = other.rawptr;
115
+ d = other.d;
116
+ }
117
+ // read access to element #i
118
+ template<typename I> const T &raw(I i) const
119
+ { return d[i]; }
120
+ // read access to data area
121
+ const T *data() const
122
+ { return d; }
123
+ };
124
+
125
+ constexpr size_t MAXIDX=~(size_t(0));
126
+
127
+ struct slice
128
+ {
129
+ size_t beg, end;
130
+ ptrdiff_t step;
131
+ slice() : beg(0), end(MAXIDX), step(1) {}
132
+ slice(size_t idx) : beg(idx), end(idx), step(1) {}
133
+ slice(size_t beg_, size_t end_, ptrdiff_t step_=1)
134
+ : beg(beg_), end(end_), step(step_)
135
+ {
136
+ // FIXME: add sanity checks here
137
+ }
138
+
139
+ size_t size(size_t shp) const
140
+ {
141
+ if (beg==end) return 0;
142
+ if (step>0) return (min(shp,end)-beg+step-1)/step;
143
+ // negative step
144
+ if (end==MAXIDX)
145
+ return (beg-step)/(-step);
146
+ return (beg-end-step-1)/(-step);
147
+ }
148
+ };
149
+
150
+ /// Helper class containing shape and stride information of an `fmav` object
151
+ class fmav_info
152
+ {
153
+ public:
154
+ /// vector of nonnegative integers for storing the array shape
155
+ using shape_t = vector<size_t>;
156
+ /// vector of integers for storing the array strides
157
+ using stride_t = vector<ptrdiff_t>;
158
+
159
+ protected:
160
+ shape_t shp;
161
+ stride_t str;
162
+ size_t sz;
163
+
164
+ static stride_t shape2stride(const shape_t &shp)
165
+ {
166
+ auto ndim = shp.size();
167
+ // MR using the static_cast just to avoid a GCC warning.
168
+ // stride_t res(ndim);
169
+ stride_t res(static_cast<int>(ndim));
170
+ if (ndim==0) return res;
171
+ res[ndim-1]=1;
172
+ for (size_t i=2; i<=ndim; ++i)
173
+ res[ndim-i] = res[ndim-i+1]*ptrdiff_t(shp[ndim-i+1]);
174
+ return res;
175
+ }
176
+ template<typename... Ns> ptrdiff_t getIdx(size_t dim, size_t n, Ns... ns) const
177
+ { return str[dim]*ptrdiff_t(n) + getIdx(dim+1, ns...); }
178
+ ptrdiff_t getIdx(size_t dim, size_t n) const
179
+ { return str[dim]*ptrdiff_t(n); }
180
+ ptrdiff_t getIdx(size_t /*dim*/) const
181
+ { return 0; }
182
+
183
+ public:
184
+ /// Constructs a 1D object with all extents and strides set to zero.
185
+ fmav_info() : shp(1,0), str(1,0), sz(0) {}
186
+ /// Constructs an object with the given shape and stride.
187
+ fmav_info(const shape_t &shape_, const stride_t &stride_)
188
+ : shp(shape_), str(stride_),
189
+ sz(accumulate(shp.begin(),shp.end(),size_t(1),multiplies<>()))
190
+ {
191
+ MR_assert(shp.size()==str.size(), "dimensions mismatch");
192
+ }
193
+ /// Constructs an object with the given shape and computes the strides
194
+ /// automatically, assuming a C-contiguous memory layout.
195
+ fmav_info(const shape_t &shape_)
196
+ : fmav_info(shape_, shape2stride(shape_)) {}
197
+ void assign(const fmav_info &other)
198
+ {
199
+ shp = other.shp;
200
+ str = other.str;
201
+ sz = other.sz;
202
+ }
203
+ /// Returns the dimensionality of the object.
204
+ size_t ndim() const { return shp.size(); }
205
+ /// Returns the total number of entries in the object.
206
+ size_t size() const { return sz; }
207
+ /// Returns the shape of the object.
208
+ const shape_t &shape() const { return shp; }
209
+ /// Returns the length along dimension \a i.
210
+ size_t shape(size_t i) const { return shp[i]; }
211
+ /// Returns the strides of the object.
212
+ const stride_t &stride() const { return str; }
213
+ /// Returns the stride along dimension \a i.
214
+ const ptrdiff_t &stride(size_t i) const { return str[i]; }
215
+ /// Returns true iff the last dimension has stride 1.
216
+ /** Typically used for optimization purposes. */
217
+ bool last_contiguous() const
218
+ { return ((ndim()==0) || (str.back()==1)); }
219
+ /** Returns true iff the object is C-contiguous, i.e. if the stride of the
220
+ * last dimension is 1, the stride for the next-to-last dimension is the
221
+ * shape of the last dimension etc. */
222
+ bool contiguous() const
223
+ {
224
+ auto ndim = shp.size();
225
+ ptrdiff_t stride=1;
226
+ for (size_t i=0; i<ndim; ++i)
227
+ {
228
+ if ((shp[ndim-1-i]!=1) && (str[ndim-1-i]!=stride))
229
+ return false;
230
+ stride *= ptrdiff_t(shp[ndim-1-i]);
231
+ }
232
+ return true;
233
+ }
234
+ /// Returns true iff this->shape and \a other.shape match.
235
+ bool conformable(const fmav_info &other) const
236
+ { return shp==other.shp; }
237
+ /// Returns the one-dimensional index of an entry from the given
238
+ /// multi-dimensional index tuple, taking strides into account.
239
+ template<typename... Ns> ptrdiff_t idx(Ns... ns) const
240
+ {
241
+ MR_assert(ndim()==sizeof...(ns), "incorrect number of indices");
242
+ return getIdx(0, ns...);
243
+ }
244
+ ptrdiff_t idx(const shape_t &ns) const
245
+ {
246
+ MR_assert(ndim()==ns.size(), "incorrect number of indices");
247
+ size_t res = 0;
248
+ for (size_t i=0; i<ndim(); ++i) res += str[i]*ns[i];
249
+ return res;
250
+ }
251
+ template<typename RAiter> ptrdiff_t idxval(RAiter beg, RAiter end) const
252
+ {
253
+ MR_assert(ndim()==size_t(end-beg), "incorrect number of indices");
254
+ size_t res = 0;
255
+ for (size_t i=0; i<ndim(); ++i, ++beg) res += str[i]* (*beg);
256
+ return res;
257
+ }
258
+ /// Returns the common broadcast shape of *this and \a shp2
259
+ shape_t bcast_shape(const shape_t &shp2) const
260
+ {
261
+ shape_t res(max(shp.size(), shp2.size()), 1);
262
+ for (size_t i=0; i<shp.size(); ++i)
263
+ res[i+res.size()-shp.size()] = shp[i];
264
+ for (size_t i=0; i<shp2.size(); ++i)
265
+ {
266
+ size_t i2 = i+res.size()-shp2.size();
267
+ if (res[i2]==1)
268
+ res[i2] = shp2[i];
269
+ else
270
+ MR_assert((res[i2]==shp2[i])||(shp2[i]==1),
271
+ "arrays cannot be broadcast together");
272
+ }
273
+ return res;
274
+ }
275
+ void bcast_to_shape(const shape_t &shp2)
276
+ {
277
+ MR_assert(shp2.size()>=shp.size(), "cannot reduce dimensionality");
278
+ stride_t newstr(shp2.size(), 0);
279
+ for (size_t i=0; i<shp.size(); ++i)
280
+ {
281
+ size_t i2 = i+shp2.size()-shp.size();
282
+ if (shp[i]!=1)
283
+ {
284
+ MR_assert(shp[i]==shp2[i2], "arrays cannot be broadcast together");
285
+ newstr[i2] = str[i];
286
+ }
287
+ }
288
+ shp = shp2;
289
+ str = newstr;
290
+ }
291
+
292
+ void swap_axes(size_t ax0, size_t ax1)
293
+ {
294
+ MR_assert(ax0<=ndim() && ax1<=ndim(), "bad axes");
295
+ if (ax0==ax1) return;
296
+ swap(shp[ax0], shp[ax1]);
297
+ swap(str[ax0], str[ax1]);
298
+ }
299
+
300
+ fmav_info extend_and_broadcast(const shape_t &new_shape,
301
+ const shape_t &axpos) const
302
+ {
303
+ MR_assert(new_shape.size()>=ndim(),
304
+ "new shape smaller than original one");
305
+ MR_assert(axpos.size()==ndim(), "bad axpos size");
306
+ stride_t new_stride(new_shape.size(), 0);
307
+ vector<uint8_t> used(new_shape.size(),0);
308
+ for (size_t i=0; i<ndim(); ++i)
309
+ {
310
+ MR_assert(axpos[i]<new_shape.size(), "bad axis number");
311
+ MR_assert(shp[i]==new_shape[axpos[i]], "axis length nismatch");
312
+ MR_assert(used[axpos[i]]==0, "repeated axis position");
313
+ used[axpos[i]]=1;
314
+ new_stride[axpos[i]] = str[i];
315
+ }
316
+ return fmav_info(new_shape, new_stride);
317
+ }
318
+ fmav_info extend_and_broadcast(const shape_t &new_shape,
319
+ size_t firstaxis) const
320
+ {
321
+ shape_t axpos(ndim());
322
+ std::iota(axpos.begin(), axpos.end(), firstaxis);
323
+ return extend_and_broadcast(new_shape, axpos);
324
+ }
325
+ fmav_info transpose() const
326
+ {
327
+ return fmav_info({shp.crend(), shp.crbegin()}, {str.crbegin(), str.crend()});
328
+ }
329
+ protected:
330
+ auto subdata(const vector<slice> &slices) const
331
+ {
332
+ auto ndim = shp.size();
333
+ shape_t nshp(ndim);
334
+ stride_t nstr(ndim);
335
+ MR_assert(slices.size()==ndim, "incorrect number of slices");
336
+ size_t n0=0;
337
+ for (auto x:slices) if (x.beg==x.end) ++n0;
338
+ ptrdiff_t nofs=0;
339
+ nshp.resize(ndim-n0);
340
+ nstr.resize(ndim-n0);
341
+ for (size_t i=0, i2=0; i<ndim; ++i)
342
+ {
343
+ MR_assert(slices[i].beg<shp[i], "bad subset");
344
+ nofs+=slices[i].beg*str[i];
345
+ if (slices[i].beg!=slices[i].end)
346
+ {
347
+ auto ext = slices[i].size(shp[i]);
348
+ MR_assert(slices[i].beg+(ext-1)*slices[i].step<shp[i], "bad subset");
349
+ nshp[i2]=ext; nstr[i2]=slices[i].step*str[i];
350
+ ++i2;
351
+ }
352
+ }
353
+ return make_tuple(fmav_info(nshp, nstr), nofs);
354
+ }
355
+ };
356
+
357
+ /// Helper class containing shape and stride information of a `mav` object
358
+ template<size_t ndim> class mav_info
359
+ {
360
+ public:
361
+ /// Fixed-size array of nonnegative integers for storing the array shape
362
+ using shape_t = array<size_t, ndim>;
363
+ /// Fixed-size array of integers for storing the array strides
364
+ using stride_t = array<ptrdiff_t, ndim>;
365
+
366
+ protected:
367
+ shape_t shp;
368
+ stride_t str;
369
+ size_t sz;
370
+
371
+ static stride_t shape2stride(const shape_t &shp)
372
+ {
373
+ stride_t res;
374
+ if (ndim==0) return res;
375
+ res[ndim-1]=1;
376
+ for (size_t i=2; i<=ndim; ++i)
377
+ res[ndim-i] = res[ndim-i+1]*ptrdiff_t(shp[ndim-i+1]);
378
+ return res;
379
+ }
380
+ template<typename... Ns> ptrdiff_t getIdx(size_t dim, size_t n, Ns... ns) const
381
+ { return str[dim]*n + getIdx(dim+1, ns...); }
382
+ ptrdiff_t getIdx(size_t dim, size_t n) const
383
+ { return str[dim]*n; }
384
+ ptrdiff_t getIdx(size_t /*dim*/) const
385
+ { return 0; }
386
+
387
+ public:
388
+ /// Constructs an object with all extents and strides set to zero.
389
+ mav_info() : sz(0)
390
+ {
391
+ for (size_t i=0; i<ndim; ++i)
392
+ { shp[i]=0; str[i]=0; }
393
+ }
394
+ /// Constructs an object with the given shape and stride.
395
+ mav_info(const shape_t &shape_, const stride_t &stride_)
396
+ : shp(shape_), str(stride_),
397
+ sz(accumulate(shp.begin(),shp.end(),size_t(1),multiplies<>())) {}
398
+ /// Constructs an object with the given shape and computes the strides
399
+ /// automatically, assuming a C-contiguous memory layout.
400
+ mav_info(const shape_t &shape_)
401
+ : mav_info(shape_, shape2stride(shape_)) {}
402
+ mav_info(const fmav_info &inp)
403
+ {
404
+ MR_assert(inp.ndim()==ndim, "dimensionality mismatch");
405
+ sz=1;
406
+ for (size_t i=0; i<ndim; ++i)
407
+ {
408
+ shp[i] = inp.shape(i);
409
+ sz *= shp[i];
410
+ str[i] = inp.stride(i);
411
+ }
412
+ }
413
+ void assign(const mav_info &other)
414
+ {
415
+ shp = other.shp;
416
+ str = other.str;
417
+ sz = other.sz;
418
+ }
419
+ /// Returns the total number of entries in the object.
420
+ size_t size() const { return sz; }
421
+ /// Returns the shape of the object.
422
+ const shape_t &shape() const { return shp; }
423
+ /// Returns the length along dimension \a i.
424
+ size_t shape(size_t i) const { return shp[i]; }
425
+ /// Returns the strides of the object.
426
+ const stride_t &stride() const { return str; }
427
+ /// Returns the stride along dimension \a i.
428
+ const ptrdiff_t &stride(size_t i) const { return str[i]; }
429
+ /// Returns true iff the last dimension has stride 1.
430
+ /** Typically used for optimization purposes. */
431
+ bool last_contiguous() const
432
+ { return ((ndim==0) || (str.back()==1)); }
433
+ /** Returns true iff the object is C-contiguous, i.e. if the stride of the
434
+ * last dimension is 1, the stride for the next-to-last dimension is the
435
+ * shape of the last dimension etc. */
436
+ bool contiguous() const
437
+ {
438
+ ptrdiff_t stride=1;
439
+ for (size_t i=0; i<ndim; ++i)
440
+ {
441
+ if ((shp[ndim-1-i]!=1) && (str[ndim-1-i]!=stride))
442
+ return false;
443
+ stride *= ptrdiff_t(shp[ndim-1-i]);
444
+ }
445
+ return true;
446
+ }
447
+ /// Returns true iff this->shape and \a other.shape match.
448
+ bool conformable(const mav_info &other) const
449
+ { return shp==other.shp; }
450
+ /// Returns true iff this->shape and \a other match.
451
+ bool conformable(const shape_t &other) const
452
+ { return shp==other; }
453
+ /// Returns the one-dimensional index of an entry from the given
454
+ /// multi-dimensional index tuple, taking strides into account.
455
+ template<typename... Ns> ptrdiff_t idx(Ns... ns) const
456
+ {
457
+ static_assert(ndim==sizeof...(ns), "incorrect number of indices");
458
+ return getIdx(0, ns...);
459
+ }
460
+ mav_info transpose() const
461
+ {
462
+ shape_t shp2;
463
+ stride_t str2;
464
+ for (size_t i=0; i<ndim; ++i)
465
+ {
466
+ shp2[i] = shp[ndim-1-i];
467
+ str2[i] = str[ndim-1-i];
468
+ }
469
+ return mav_info(shp2, str2);
470
+ }
471
+ mav_info<ndim+1> prepend_1() const
472
+ {
473
+ typename mav_info<ndim+1>::shape_t newshp;
474
+ typename mav_info<ndim+1>::stride_t newstr;
475
+ newshp[0] = 1;
476
+ newstr[0] = 0;
477
+ for (size_t i=0; i<ndim; ++i)
478
+ {
479
+ newshp[i+1] = shp[i];
480
+ newstr[i+1] = str[i];
481
+ }
482
+ return mav_info<ndim+1>(newshp, newstr);
483
+ }
484
+
485
+ protected:
486
+ template<size_t nd2> auto subdata(const vector<slice> &slices) const
487
+ {
488
+ MR_assert(slices.size()==ndim, "bad number of slices");
489
+ array<size_t, nd2> nshp;
490
+ array<ptrdiff_t, nd2> nstr;
491
+
492
+ // unnecessary, but gcc warns otherwise
493
+ for (size_t i=0; i<nd2; ++i) nshp[i]=nstr[i]=0;
494
+
495
+ size_t n0=0;
496
+ for (auto x:slices) if (x.beg==x.end) ++n0;
497
+ MR_assert(n0+nd2==ndim, "bad extent");
498
+ ptrdiff_t nofs=0;
499
+ for (size_t i=0, i2=0; i<ndim; ++i)
500
+ {
501
+ MR_assert(slices[i].beg<shp[i], "bad subset");
502
+ nofs+=slices[i].beg*str[i];
503
+ if (slices[i].beg!=slices[i].end)
504
+ {
505
+ auto ext = slices[i].size(shp[i]);
506
+ MR_assert(slices[i].beg+(ext-1)*slices[i].step<shp[i], "bad subset");
507
+ nshp[i2]=ext; nstr[i2]=slices[i].step*str[i];
508
+ ++i2;
509
+ }
510
+ }
511
+ return make_tuple(mav_info<nd2>(nshp, nstr), nofs);
512
+ }
513
+ };
514
+
515
+ template<typename T> class cfmav: public fmav_info, public cmembuf<T>
516
+ {
517
+ protected:
518
+ using tbuf = cmembuf<T>;
519
+ using tinfo = fmav_info;
520
+ using fmav_info::idx;
521
+
522
+ public:
523
+ using typename tinfo::shape_t;
524
+ using typename tinfo::stride_t;
525
+ using tbuf::raw, tbuf::data;
526
+
527
+
528
+ protected:
529
+ cfmav(const shape_t &shp_)
530
+ : tinfo(shp_), tbuf(size()) {}
531
+ cfmav(const shape_t &shp_, uninitialized_dummy)
532
+ : tinfo(shp_), tbuf(size(), UNINITIALIZED) {}
533
+ cfmav(const shape_t &shp_, const stride_t &str_, uninitialized_dummy)
534
+ : tinfo(shp_, str_), tbuf(size(), UNINITIALIZED)
535
+ {
536
+ ptrdiff_t ofs=0;
537
+ for (size_t i=0; i<ndim(); ++i)
538
+ ofs += (ptrdiff_t(shp[i])-1)*str[i];
539
+ MR_assert(ofs+1==ptrdiff_t(size()), "array is not compact");
540
+ }
541
+ cfmav(const fmav_info &info, const tbuf &buf)
542
+ : tinfo(info), tbuf(buf) {}
543
+ cfmav(const fmav_info &info, const T *d_, const tbuf &buf)
544
+ : tinfo(info), tbuf(d_, buf) {}
545
+
546
+ public:
547
+ cfmav() {}
548
+ cfmav(const T *d_, const shape_t &shp_, const stride_t &str_)
549
+ : tinfo(shp_, str_), tbuf(d_) {}
550
+ cfmav(const T *d_, const shape_t &shp_)
551
+ : tinfo(shp_), tbuf(d_) {}
552
+ cfmav(const T* d_, const tinfo &info)
553
+ : tinfo(info), tbuf(d_) {}
554
+
555
+ cfmav(const tbuf &buf, const shape_t &shp_, const stride_t &str_)
556
+ : tinfo(shp_, str_), tbuf(buf) {}
557
+
558
+ // no-op. Needed for template tricks.
559
+ cfmav to_fmav() const { return *this; }
560
+
561
+ void assign(const cfmav &other)
562
+ {
563
+ tinfo::assign(other);
564
+ tbuf::assign(other);
565
+ }
566
+
567
+ /// Returns the data entry at the given set of indices.
568
+ template<typename... Ns> const T &operator()(Ns... ns) const
569
+ { return raw(idx(ns...)); }
570
+ const T &operator()(const shape_t &ns) const
571
+ { return raw(idx(ns)); }
572
+ template<typename RAiter> const T& val(RAiter beg, RAiter end) const
573
+ { return raw(idxval(beg, end)); }
574
+
575
+ cfmav subarray(const vector<slice> &slices) const
576
+ {
577
+ auto [ninfo, nofs] = subdata(slices);
578
+ return cfmav(ninfo, tbuf::d+nofs, *this);
579
+ }
580
+ cfmav extend_and_broadcast(const shape_t &new_shape, const shape_t &axpos) const
581
+ {
582
+ return cfmav(fmav_info::extend_and_broadcast(new_shape, axpos), *this);
583
+ }
584
+ cfmav extend_and_broadcast(const shape_t &new_shape, size_t firstaxis) const
585
+ {
586
+ return cfmav(fmav_info::extend_and_broadcast(new_shape, firstaxis), *this);
587
+ }
588
+ cfmav transpose() const
589
+ {
590
+ return cfmav(static_cast<const tinfo *>(this)->transpose(), *static_cast<const tbuf *>(this));
591
+ }
592
+ };
593
+
594
+ template<typename T> cfmav<T> subarray
595
+ (const cfmav<T> &arr, const vector<slice> &slices)
596
+ { return arr.subarray(slices); }
597
+
598
+ template<typename T> class vfmav: public cfmav<T>
599
+ {
600
+ protected:
601
+ using tbuf = cmembuf<T>;
602
+ using tinfo = fmav_info;
603
+ using tinfo::shp, tinfo::str;
604
+ using fmav_info::idx;
605
+
606
+ public:
607
+ using typename tinfo::shape_t;
608
+ using typename tinfo::stride_t;
609
+ using tinfo::size, tinfo::shape, tinfo::stride;
610
+
611
+ protected:
612
+ vfmav(const fmav_info &info, const tbuf &buf)
613
+ : cfmav<T>(info, buf) {}
614
+ vfmav(const fmav_info &info, T *d_, const tbuf &buf)
615
+ : cfmav<T>(info, d_, buf) {}
616
+
617
+ public:
618
+ using tbuf::raw, tbuf::data, tinfo::ndim;
619
+ vfmav() {}
620
+ vfmav(T *d_, const fmav_info &info)
621
+ : cfmav<T>(d_, info) {}
622
+ vfmav(T *d_, const shape_t &shp_, const stride_t &str_)
623
+ : cfmav<T>(d_, shp_, str_) {}
624
+ vfmav(T *d_, const shape_t &shp_)
625
+ : cfmav<T>(d_, shp_) {}
626
+ vfmav(const shape_t &shp_)
627
+ : cfmav<T>(shp_) {}
628
+ vfmav(const shape_t &shp_, uninitialized_dummy)
629
+ : cfmav<T>(shp_, UNINITIALIZED) {}
630
+ vfmav(const shape_t &shp_, const stride_t &str_, uninitialized_dummy)
631
+ : cfmav<T>(shp_, str_, UNINITIALIZED)
632
+ {
633
+ ptrdiff_t ofs=0;
634
+ for (size_t i=0; i<ndim(); ++i)
635
+ ofs += (ptrdiff_t(shp[i])-1)*str[i];
636
+ MR_assert(ofs+1==ptrdiff_t(size()), "array is not compact");
637
+ }
638
+ vfmav(tbuf &buf, const shape_t &shp_, const stride_t &str_)
639
+ : cfmav<T>(buf, shp_, str_) {}
640
+
641
+ T *data() const
642
+ { return const_cast<T *>(tbuf::d); }
643
+ template<typename I> T &raw(I i) const
644
+ { return data()[i]; }
645
+
646
+ // no-op. Needed for template tricks.
647
+ using cfmav<T>::to_fmav;
648
+ vfmav to_fmav() const { return *this; }
649
+
650
+ void assign(const vfmav &other)
651
+ {
652
+ fmav_info::assign(other);
653
+ cmembuf<T>::assign(other);
654
+ }
655
+
656
+ using cfmav<T>::operator();
657
+ template<typename... Ns> T &operator()(Ns... ns) const
658
+ { return raw(idx(ns...)); }
659
+ T &operator()(const shape_t &ns) const
660
+ { return raw(idx(ns)); }
661
+ using cfmav<T>::val;
662
+ template<typename RAiter> T& val(RAiter beg, RAiter end) const
663
+ { return raw(idxval(beg, end)); }
664
+
665
+ vfmav subarray(const vector<slice> &slices) const
666
+ {
667
+ auto [ninfo, nofs] = tinfo::subdata(slices);
668
+ return vfmav(ninfo, data()+nofs, *this);
669
+ }
670
+ /** Returns a writable fmav with the specified shape.
671
+ * The strides are chosen in such a way that critical strides (multiples
672
+ * of 4096 bytes) along any dimension are avoided, by enlarging the
673
+ * allocated memory slightly if necessary.
674
+ * The array data is default-initialized. */
675
+ static vfmav build_noncritical(const shape_t &shape)
676
+ {
677
+ auto ndim = shape.size();
678
+ auto shape2 = noncritical_shape(shape, sizeof(T));
679
+ vfmav tmp(shape2);
680
+ vector<slice> slc(ndim);
681
+ for (size_t i=0; i<ndim; ++i) slc[i] = slice(0, shape[i]);
682
+ return tmp.subarray(slc);
683
+ }
684
+ /** Returns a writable fmav with the specified shape.
685
+ * The strides are chosen in such a way that critical strides (multiples
686
+ * of 4096 bytes) along any dimension are avoided, by enlarging the
687
+ * allocated memory slightly if necessary.
688
+ * The array data is not initialized. */
689
+ static vfmav build_noncritical(const shape_t &shape, uninitialized_dummy)
690
+ {
691
+ auto ndim = shape.size();
692
+ if (ndim<=1) return vfmav(shape, UNINITIALIZED);
693
+ auto shape2 = noncritical_shape(shape, sizeof(T));
694
+ vfmav tmp(shape2, UNINITIALIZED);
695
+ vector<slice> slc(ndim);
696
+ for (size_t i=0; i<ndim; ++i) slc[i] = slice(0, shape[i]);
697
+ return tmp.subarray(slc);
698
+ }
699
+ vfmav extend_and_broadcast(const shape_t &new_shape, const shape_t &axpos) const
700
+ {
701
+ return vfmav(fmav_info::extend_and_broadcast(new_shape, axpos), *this);
702
+ }
703
+ vfmav extend_and_broadcast(const shape_t &new_shape, size_t firstaxis) const
704
+ {
705
+ return vfmav(fmav_info::extend_and_broadcast(new_shape, firstaxis), *this);
706
+ }
707
+ vfmav transpose() const
708
+ {
709
+ return vfmav(static_cast<const tinfo *>(this)->transpose(), *static_cast<const tbuf *>(this));
710
+ }
711
+ };
712
+
713
+ template<typename T> vfmav<T> subarray
714
+ (const vfmav<T> &arr, const vector<slice> &slices)
715
+ { return arr.subarray(slices); }
716
+
717
+ template<typename T, size_t ndim> class cmav: public mav_info<ndim>, public cmembuf<T>
718
+ {
719
+ protected:
720
+ template<typename T2, size_t nd2> friend class cmav;
721
+ template<typename T2, size_t nd2> friend class vmav;
722
+
723
+ using tinfo = mav_info<ndim>;
724
+ using tbuf = cmembuf<T>;
725
+ using tinfo::shp, tinfo::str;
726
+
727
+ public:
728
+ using typename tinfo::shape_t;
729
+ using typename tinfo::stride_t;
730
+ using tbuf::raw, tbuf::data;
731
+ using tinfo::contiguous, tinfo::size, tinfo::idx, tinfo::conformable;
732
+
733
+ protected:
734
+ cmav() {}
735
+ cmav(const shape_t &shp_, uninitialized_dummy)
736
+ : tinfo(shp_), tbuf(size(), UNINITIALIZED) {}
737
+ cmav(const shape_t &shp_)
738
+ : tinfo(shp_), tbuf(size()) {}
739
+ cmav(const tbuf &buf, const shape_t &shp_, const stride_t &str_)
740
+ : tinfo(shp_, str_), tbuf(buf) {}
741
+ cmav(const tinfo &info, const T *d_, const tbuf &buf)
742
+ : tinfo(info), tbuf(d_, buf) {}
743
+ cmav(const tinfo &info, const tbuf &buf)
744
+ : tinfo(info), tbuf(buf) {}
745
+
746
+ public:
747
+ cmav(const T *d_, const shape_t &shp_, const stride_t &str_)
748
+ : tinfo(shp_, str_), tbuf(d_) {}
749
+ cmav(const T *d_, const shape_t &shp_)
750
+ : tinfo(shp_), tbuf(d_) {}
751
+ cmav(const cfmav<T> &inp)
752
+ : tinfo(inp), tbuf(inp) {}
753
+ void assign(const cmav &other)
754
+ {
755
+ mav_info<ndim>::assign(other);
756
+ cmembuf<T>::assign(other);
757
+ }
758
+ operator cfmav<T>() const
759
+ {
760
+ return cfmav<T>(*this, {shp.begin(), shp.end()}, {str.begin(), str.end()});
761
+ }
762
+ // Needed for template tricks.
763
+ cfmav<T> to_fmav() const { return operator cfmav<T>(); }
764
+
765
+ template<typename... Ns> const T &operator()(Ns... ns) const
766
+ { return raw(idx(ns...)); }
767
+ template<size_t nd2> cmav<T,nd2> subarray(const vector<slice> &slices) const
768
+ {
769
+ auto [ninfo, nofs] = tinfo::template subdata<nd2> (slices);
770
+ return cmav<T,nd2> (ninfo, tbuf::d+nofs, *this);
771
+ }
772
+
773
+ static cmav build_uniform(const shape_t &shape, const T &value)
774
+ {
775
+ // Don't do this at home!
776
+ shape_t tshp;
777
+ tshp.fill(1);
778
+ cmav tmp(tshp);
779
+ const_cast<T &>(tmp.raw(0)) = value;
780
+ stride_t nstr;
781
+ nstr.fill(0);
782
+ return cmav(tmp, shape, nstr);
783
+ }
784
+ cmav transpose() const
785
+ {
786
+ return cmav(static_cast<const tinfo *>(this)->transpose(), *static_cast<const tbuf *>(this));
787
+ }
788
+ cmav<T, ndim+1> prepend_1() const
789
+ {
790
+ return cmav<T, ndim+1>(static_cast<const tinfo *>(this)->prepend_1(), *static_cast<const tbuf *>(this));
791
+ }
792
+ template<size_t ndim2> cmav<T, ndim2> reinterpret
793
+ (const typename cmav<T, ndim2>::shape_t &newshp,
794
+ const typename cmav<T, ndim2>::stride_t &newstr) const
795
+ {
796
+ return cmav<T, ndim2>(*static_cast<const tbuf *>(this), newshp, newstr);
797
+ }
798
+ };
799
+ template<size_t nd2, typename T, size_t ndim> cmav<T,nd2> subarray
800
+ (const cmav<T, ndim> &arr, const vector<slice> &slices)
801
+ { return arr.template subarray<nd2>(slices); }
802
+
803
+ template<typename T, size_t ndim> class vmav: public cmav<T, ndim>
804
+ {
805
+ protected:
806
+ template<typename T2, size_t nd2> friend class vmav;
807
+
808
+ using parent = cmav<T, ndim>;
809
+ using tinfo = mav_info<ndim>;
810
+ using tbuf = cmembuf<T>;
811
+ using tinfo::shp, tinfo::str;
812
+
813
+ public:
814
+ using typename tinfo::shape_t;
815
+ using typename tinfo::stride_t;
816
+ using tbuf::raw, tbuf::data;
817
+ using tinfo::contiguous, tinfo::size, tinfo::idx, tinfo::conformable;
818
+
819
+ protected:
820
+ vmav(const tinfo &info, T *d_, const tbuf &buf)
821
+ : parent(info, d_, buf) {}
822
+ vmav(const tinfo &info, const tbuf &buf)
823
+ : parent(info, buf) {}
824
+ vmav(const tbuf &buf, const shape_t &shp_, const stride_t &str_)
825
+ : parent(buf, shp_, str_){}
826
+
827
+ public:
828
+ vmav() {}
829
+ vmav(T *d_, const shape_t &shp_, const stride_t &str_)
830
+ : parent(d_, shp_, str_) {}
831
+ vmav(T *d_, const shape_t &shp_)
832
+ : parent(d_, shp_) {}
833
+ vmav(const shape_t &shp_)
834
+ : parent(shp_) {}
835
+ vmav(const shape_t &shp_, uninitialized_dummy)
836
+ : parent(shp_, UNINITIALIZED) {}
837
+ vmav(const vfmav<T> &inp)
838
+ : parent(inp) {}
839
+
840
+ void assign(vmav &other)
841
+ { parent::assign(other); }
842
+ void dealloc()
843
+ {
844
+ vmav empty;
845
+ assign(empty);
846
+ }
847
+ operator vfmav<T>() const
848
+ {
849
+ return vfmav<T>(*const_cast<tbuf *>(static_cast<const tbuf *>(this)), {shp.begin(), shp.end()}, {str.begin(), str.end()});
850
+ }
851
+ // Needed for template tricks.
852
+ using cmav<T, ndim>::to_fmav;
853
+ vfmav<T> to_fmav() const { return operator vfmav<T>(); }
854
+
855
+ using parent::operator();
856
+ template<typename... Ns> T &operator()(Ns... ns) const
857
+ { return const_cast<T &>(parent::operator()(ns...)); }
858
+
859
+ template<size_t nd2> vmav<T,nd2> subarray(const vector<slice> &slices) const
860
+ {
861
+ auto [ninfo, nofs] = tinfo::template subdata<nd2> (slices);
862
+ return vmav<T,nd2> (ninfo, data()+nofs, *this);
863
+ }
864
+
865
+ T *data() const
866
+ { return const_cast<T *>(tbuf::d); }
867
+ // read access to element #i
868
+ template<typename I> T &raw(I i) const
869
+ { return data()[i]; }
870
+
871
+ static vmav build_empty()
872
+ {
873
+ shape_t nshp;
874
+ nshp.fill(0);
875
+ return vmav(static_cast<T *>(nullptr), nshp);
876
+ }
877
+
878
+ static vmav build_noncritical(const shape_t &shape)
879
+ {
880
+ auto shape2 = noncritical_shape(shape, sizeof(T));
881
+ vmav tmp(shape2);
882
+ vector<slice> slc(ndim);
883
+ for (size_t i=0; i<ndim; ++i) slc[i] = slice(0, shape[i]);
884
+ return tmp.subarray<ndim>(slc);
885
+ }
886
+ static vmav build_noncritical(const shape_t &shape, uninitialized_dummy)
887
+ {
888
+ if (ndim<=1) return vmav(shape, UNINITIALIZED);
889
+ auto shape2 = noncritical_shape(shape, sizeof(T));
890
+ vmav tmp(shape2, UNINITIALIZED);
891
+ vector<slice> slc(ndim);
892
+ for (size_t i=0; i<ndim; ++i) slc[i] = slice(0, shape[i]);
893
+ return tmp.subarray<ndim>(slc);
894
+ }
895
+ vmav transpose() const
896
+ {
897
+ return vmav(static_cast<const tinfo *>(this)->transpose(), *static_cast<const tbuf *>(this));
898
+ }
899
+ vmav<T, ndim+1> prepend_1() const
900
+ {
901
+ return vmav<T, ndim+1>(static_cast<const tinfo *>(this)->prepend_1(), *static_cast<const tbuf *>(this));
902
+ }
903
+ template<size_t ndim2> vmav<T, ndim2> reinterpret
904
+ (const typename vmav<T, ndim2>::shape_t &newshp,
905
+ const typename vmav<T, ndim2>::stride_t &newstr) const
906
+ {
907
+ return vmav<T, ndim2>(*static_cast<const tbuf *>(this), newshp, newstr);
908
+ }
909
+ };
910
+
911
+ template<size_t nd2, typename T, size_t ndim> vmav<T,nd2> subarray
912
+ (const vmav<T, ndim> &arr, const vector<slice> &slices)
913
+ { return arr.template subarray<nd2>(slices); }
914
+
915
+ // various operations involving fmav objects of the same shape -- experimental
916
+
917
+ DUCC0_NOINLINE tuple<fmav_info::shape_t, vector<fmav_info::stride_t>, size_t, size_t>
918
+ multiprep(const vector<fmav_info> &info, const vector<size_t> &tsizes);
919
+ DUCC0_NOINLINE tuple<fmav_info::shape_t, vector<fmav_info::stride_t>>
920
+ multiprep(const vector<fmav_info> &info);
921
+
922
+ template<typename Ttuple> constexpr inline size_t tuplelike_size()
923
+ { return tuple_size_v<remove_reference_t<Ttuple>>; }
924
+
925
+ template <typename Func, typename Ttuple, size_t... I>
926
+ inline void call_with_tuple_impl(Func &&func, const Ttuple& tuple,
927
+ index_sequence<I...>)
928
+ { func(std::forward<typename tuple_element<I, Ttuple>::type>(get<I>(tuple))...); }
929
+ template<typename Func, typename Ttuple> inline void call_with_tuple
930
+ (Func &&func, Ttuple &&tuple)
931
+ {
932
+ call_with_tuple_impl(std::forward<Func>(func), tuple,
933
+ make_index_sequence<tuplelike_size<Ttuple>()>());
934
+ }
935
+ template <typename Func, typename Ttuple, size_t... I>
936
+ inline void call_with_tuple2_impl(Func &&func, const Ttuple& tuple,
937
+ index_sequence<I...>)
938
+ { func(get<I>(tuple)...); }
939
+ template<typename Func, typename Ttuple> inline void call_with_tuple2
940
+ (Func &&func, Ttuple &&tuple)
941
+ {
942
+ call_with_tuple2_impl(std::forward<Func>(func), tuple,
943
+ make_index_sequence<tuplelike_size<Ttuple>()>());
944
+ }
945
+
946
+ template<typename...Ts, typename Func, size_t... Is>
947
+ inline auto tuple_transform_impl(tuple<Ts...> const& inputs, Func &&func,
948
+ index_sequence<Is...>)
949
+ { return tuple<invoke_result_t<Func,Ts>...>{func(get<Is>(inputs))...}; }
950
+ template<typename... Ts, typename Func>
951
+ inline auto tuple_transform(tuple<Ts...> const& inputs, Func &&func)
952
+ {
953
+ return tuple_transform_impl(inputs, std::forward<Func>(func),
954
+ make_index_sequence<sizeof...(Ts)>{});
955
+ }
956
+ template<typename...Ts, typename Func, size_t... Is>
957
+ inline void tuple_for_each_impl(tuple<Ts...> &tpl, Func &&func,
958
+ index_sequence<Is...>)
959
+ { (func(get<Is>(tpl)), ...); }
960
+ template<typename... Ts, typename Func>
961
+ inline void tuple_for_each(tuple<Ts...> &tpl, Func &&func)
962
+ {
963
+ tuple_for_each_impl(tpl, std::forward<Func>(func), make_index_sequence<sizeof...(Ts)>{});
964
+ }
965
+ template<typename...Ts, typename Func, size_t... Is>
966
+ inline void tuple_for_each_impl(const tuple<Ts...> &tpl, Func &&func,
967
+ index_sequence<Is...>)
968
+ { (func(get<Is>(tpl)), ...); }
969
+ template<typename... Ts, typename Func>
970
+ inline void tuple_for_each(const tuple<Ts...> &tpl, Func &&func)
971
+ {
972
+ tuple_for_each_impl(tpl, std::forward<Func>(func), make_index_sequence<sizeof...(Ts)>{});
973
+ }
974
+
975
+ template<typename...Ts, typename Func, size_t... Is>
976
+ inline auto tuple_transform_idx_impl(const tuple<Ts...> &inputs,
977
+ Func &&func, index_sequence<Is...>)
978
+ {
979
+ return tuple<invoke_result_t<Func, Ts, int>...>
980
+ {func(get<Is>(inputs), Is)...};
981
+ }
982
+
983
+ template<typename... Ts, typename Func>
984
+ inline auto tuple_transform_idx(const tuple<Ts...> &inputs, Func &&func)
985
+ {
986
+ return tuple_transform_idx_impl(inputs, std::forward<Func>(func),
987
+ make_index_sequence<sizeof...(Ts)>{});
988
+ }
989
+ template<typename...Ts, typename Func, size_t... Is>
990
+ inline void tuple_for_each_idx_impl(tuple<Ts...> &tpl, Func &&func,
991
+ index_sequence<Is...>)
992
+ { (func(get<Is>(tpl), Is), ...); }
993
+ template<typename... Ts, typename Func>
994
+ inline void tuple_for_each_idx(tuple<Ts...> &tpl, Func &&func)
995
+ {
996
+ tuple_for_each_idx_impl(tpl, std::forward<Func>(func), make_index_sequence<sizeof...(Ts)>{});
997
+ }
998
+
999
+ template<typename Ttuple> inline auto to_ref (const Ttuple &tuple)
1000
+ {
1001
+ return tuple_transform(tuple,[](auto &&ptr) -> typename std::add_lvalue_reference_t<decltype(*ptr)>{ return *ptr; });
1002
+ }
1003
+
1004
+ template<typename Ttuple> inline Ttuple update_pointers (const Ttuple &ptrs,
1005
+ const vector<vector<ptrdiff_t>> &str, size_t idim, size_t i)
1006
+ {
1007
+ return tuple_transform_idx(ptrs, [i,idim,&str](auto &&ptr, size_t idx)
1008
+ { return ptr + i*str[idx][idim]; });
1009
+ }
1010
+
1011
+ template<typename Ttuple> inline Ttuple update_pointers_contiguous (const Ttuple &ptrs,
1012
+ size_t i)
1013
+ {
1014
+ return tuple_transform(ptrs, [i](auto &&ptr) { return ptr+i; });
1015
+ }
1016
+ template<typename Ttuple> inline void advance_contiguous (Ttuple &ptrs)
1017
+ { tuple_for_each(ptrs, [](auto &&ptr) { ++ptr; }); }
1018
+ template<typename Ttuple> inline void advance (Ttuple &ptrs,
1019
+ const vector<vector<ptrdiff_t>> &str, size_t idim)
1020
+ {
1021
+ tuple_for_each_idx(ptrs, [idim,&str](auto &&ptr, size_t idx)
1022
+ { ptr += str[idx][idim]; });
1023
+ }
1024
+ template<typename Ttuple> inline void advance_by_n (Ttuple &ptrs,
1025
+ const vector<vector<ptrdiff_t>> &str, size_t idim, size_t n)
1026
+ {
1027
+ tuple_for_each_idx(ptrs, [idim,n,&str](auto &&ptr, size_t idx)
1028
+ { ptr += n*str[idx][idim]; });
1029
+ }
1030
+
1031
+ template<typename Ttuple, typename Func>
1032
+ DUCC0_NOINLINE void applyHelper_block(size_t idim, const vector<size_t> &shp,
1033
+ const vector<vector<ptrdiff_t>> &str, size_t bsi, size_t bsj,
1034
+ const Ttuple &ptrs, Func &&func)
1035
+ {
1036
+ auto leni=shp[idim], lenj=shp[idim+1];
1037
+ size_t nbi = (leni+bsi-1)/bsi;
1038
+ size_t nbj = (lenj+bsj-1)/bsj;
1039
+ for (size_t bi=0; bi<nbi; ++bi)
1040
+ for (size_t bj=0; bj<nbj; ++bj)
1041
+ {
1042
+ auto locptrs(ptrs);
1043
+ advance_by_n(locptrs, str, idim, bi*bsi);
1044
+ advance_by_n(locptrs, str, idim+1, bj*bsj);
1045
+ for (size_t i=bi*bsi; i<min(leni, (bi+1)*bsi); ++i, advance(locptrs, str, idim))
1046
+ {
1047
+ auto locptrs2(locptrs);
1048
+ for (size_t j=bj*bsj; j<min(lenj, (bj+1)*bsj); ++j, advance(locptrs2, str, idim+1))
1049
+ call_with_tuple(func, to_ref(locptrs2));
1050
+ }
1051
+ }
1052
+ }
1053
+
1054
+ template<typename Ttuple, typename Func>
1055
+ DUCC0_NOINLINE void applyHelper(size_t idim, const vector<size_t> &shp,
1056
+ const vector<vector<ptrdiff_t>> &str, size_t block0, size_t block1,
1057
+ const Ttuple &ptrs, Func &&func, bool last_contiguous)
1058
+ {
1059
+ auto len = shp[idim];
1060
+ if ((idim+2==shp.size()) && (block0!=0)) // we should do blocking
1061
+ applyHelper_block(idim, shp, str, block0, block1, ptrs, func);
1062
+ else if (idim+1<shp.size())
1063
+ for (size_t i=0; i<len; ++i)
1064
+ applyHelper(idim+1, shp, str, block0, block1, update_pointers(ptrs, str, idim, i),
1065
+ func, last_contiguous);
1066
+ else
1067
+ {
1068
+ auto locptrs(ptrs);
1069
+ if (last_contiguous)
1070
+ for (size_t i=0; i<len; ++i, advance_contiguous(locptrs))
1071
+ call_with_tuple(func, to_ref(locptrs));
1072
+ else
1073
+ for (size_t i=0; i<len; ++i, advance(locptrs, str, idim))
1074
+ call_with_tuple(func, to_ref(locptrs));
1075
+ }
1076
+ }
1077
+ template<typename Func, typename Ttuple>
1078
+ inline void applyHelper(const vector<size_t> &shp,
1079
+ const vector<vector<ptrdiff_t>> &str, size_t block0, size_t block1,
1080
+ const Ttuple &ptrs, Func &&func, size_t nthreads, bool last_contiguous)
1081
+ {
1082
+ if (shp.size()==0)
1083
+ call_with_tuple(std::forward<Func>(func), to_ref(ptrs));
1084
+ else if (nthreads==1)
1085
+ applyHelper(0, shp, str, block0, block1, ptrs, std::forward<Func>(func), last_contiguous);
1086
+ else
1087
+ execParallel(shp[0], nthreads, [&](size_t lo, size_t hi)
1088
+ {
1089
+ auto locptrs = update_pointers(ptrs, str, 0, lo);
1090
+ auto locshp(shp);
1091
+ locshp[0] = hi-lo;
1092
+ applyHelper(0, locshp, str, block0, block1, locptrs, func, last_contiguous);
1093
+ });
1094
+ }
1095
+
1096
+ template<typename Func, typename... Targs>
1097
+ void mav_apply(Func &&func, int nthreads, Targs... args)
1098
+ {
1099
+ vector<fmav_info> infos;
1100
+ (infos.push_back(args), ...);
1101
+ vector<size_t> tsizes;
1102
+ (tsizes.push_back(sizeof(args.data()[0])), ...);
1103
+ auto [shp, str, block0, block1] = multiprep(infos, tsizes);
1104
+ bool last_contiguous = true;
1105
+ if (shp.size()>0)
1106
+ for (const auto &s:str)
1107
+ last_contiguous &= (s.back()==1);
1108
+
1109
+ auto ptrs = tuple_transform(forward_as_tuple(args...),
1110
+ [](auto &&arg){return arg.data();});
1111
+ applyHelper(shp, str, block0, block1, ptrs, std::forward<Func>(func), nthreads, last_contiguous);
1112
+ }
1113
+
1114
+ DUCC0_NOINLINE tuple<fmav_info::shape_t, vector<fmav_info::stride_t>>
1115
+ multiprep_noopt(const vector<fmav_info> &info);
1116
+
1117
+ template <typename Func, typename Arg, typename Ttuple, size_t... I>
1118
+ inline void call_with_tuple_arg_impl(Func &&func, Arg &&arg, const Ttuple& tuple,
1119
+ index_sequence<I...>)
1120
+ { func(std::forward<typename tuple_element<I, Ttuple>::type>(get<I>(tuple))..., arg); }
1121
+ template<typename Func, typename Arg, typename Ttuple> inline void call_with_tuple_arg
1122
+ (Func &&func, Arg &&arg, Ttuple &&tuple)
1123
+ {
1124
+ call_with_tuple_arg_impl(std::forward<Func>(func), arg, tuple,
1125
+ make_index_sequence<tuplelike_size<Ttuple>()>());
1126
+ }
1127
+ template<typename Ttuple, typename Func>
1128
+ DUCC0_NOINLINE void applyHelper_with_index(size_t idim, const vector<size_t> &shp,
1129
+ const vector<vector<ptrdiff_t>> &str, const Ttuple &ptrs, Func &&func,
1130
+ vector<size_t> &index)
1131
+ {
1132
+ auto len = shp[idim];
1133
+ if (idim+1<shp.size())
1134
+ {
1135
+ auto idxbak = index[idim];
1136
+ for (size_t i=0; i<len; ++i, ++index[idim])
1137
+ applyHelper_with_index(idim+1, shp, str, update_pointers(ptrs, str, idim, i),
1138
+ func, index);
1139
+ index[idim] = idxbak;
1140
+ }
1141
+ else
1142
+ {
1143
+ auto locptrs(ptrs);
1144
+ auto idxbak = index[idim];
1145
+ for (size_t i=0; i<len; ++i, ++index[idim], advance(locptrs, str, idim))
1146
+ call_with_tuple_arg(func, const_cast<const vector<size_t> &>(index), to_ref(locptrs));
1147
+ index[idim] = idxbak;
1148
+ }
1149
+ }
1150
+ template<typename Func, typename Ttuple>
1151
+ inline void applyHelper_with_index(const vector<size_t> &shp,
1152
+ const vector<vector<ptrdiff_t>> &str, const Ttuple &ptrs, Func &&func,
1153
+ size_t nthreads, vector<size_t> &index)
1154
+ {
1155
+ if (shp.size()==0)
1156
+ call_with_tuple_arg(std::forward<Func>(func), const_cast<const vector<size_t> &>(index), to_ref(ptrs));
1157
+ else if (nthreads==1)
1158
+ applyHelper_with_index(0, shp, str, ptrs, std::forward<Func>(func), index);
1159
+ else
1160
+ execParallel(shp[0], nthreads, [&](size_t lo, size_t hi)
1161
+ {
1162
+ auto locptrs = update_pointers(ptrs, str, 0, lo);
1163
+ auto locshp(shp);
1164
+ locshp[0] = hi-lo;
1165
+ auto locidx(index);
1166
+ locidx[0]=lo;
1167
+ applyHelper_with_index(0, locshp, str, locptrs, func, locidx);
1168
+ });
1169
+ }
1170
+ template<typename Func, typename... Targs>
1171
+ void mav_apply_with_index(Func &&func, int nthreads, Targs... args)
1172
+ {
1173
+ vector<fmav_info> infos;
1174
+ (infos.push_back(args), ...);
1175
+ auto [shp, str] = multiprep_noopt(infos);
1176
+ vector<size_t> index(shp.size(), 0);
1177
+
1178
+ auto ptrs = tuple_transform(forward_as_tuple(args...),
1179
+ [](auto &&arg){return arg.data();});
1180
+ applyHelper_with_index(shp, str, ptrs, std::forward<Func>(func), nthreads, index);
1181
+ }
1182
+
1183
+
1184
+ template<typename T, size_t ndim> class mavref
1185
+ {
1186
+ private:
1187
+ const mav_info<ndim> &info;
1188
+ T *d;
1189
+
1190
+ public:
1191
+ using shape_t = typename mav_info<ndim>::shape_t;
1192
+ using stride_t = typename mav_info<ndim>::stride_t;
1193
+ mavref(const mav_info<ndim> &info_, T *d_) : info(info_), d(d_) {}
1194
+ template<typename... Ns> T &operator()(Ns... ns) const
1195
+ { return d[info.idx(ns...)]; }
1196
+ /// Returns the total number of entries in the object.
1197
+ size_t size() const { return info.size(); }
1198
+ /// Returns the shape of the object.
1199
+ const shape_t &shape() const { return info.shape(); }
1200
+ /// Returns the length along dimension \a i.
1201
+ size_t shape(size_t i) const { return info.shape(i); }
1202
+ /// Returns the strides of the object.
1203
+ const stride_t &stride() const { return info.stride(); }
1204
+ /// Returns the stride along dimension \a i.
1205
+ const ptrdiff_t &stride(size_t i) const { return info.stride(i); }
1206
+ /// Returns true iff the last dimension has stride 1.
1207
+ /** Typically used for optimization purposes. */
1208
+ bool last_contiguous() const
1209
+ { return info.last_contiguous(); }
1210
+ /** Returns true iff the object is C-contiguous, i.e. if the stride of the
1211
+ * last dimension is 1, the stride for the next-to-last dimension is the
1212
+ * shape of the last dimension etc. */
1213
+ bool contiguous() const
1214
+ { return info.contiguous(); }
1215
+ /// Returns true iff this->shape and \a other.shape match.
1216
+ bool conformable(const mavref &other) const
1217
+ { return shape()==other.shape(); }
1218
+ };
1219
+
1220
+ template<typename T, size_t ndim>
1221
+ mavref<T, ndim> make_mavref(const mav_info<ndim> &info_, T *d_)
1222
+ { return mavref<T, ndim>(info_, d_); }
1223
+
1224
+ template<typename...Ts, typename ...Qs, typename Func, size_t... Is>
1225
+ inline auto tuple_transform2_impl(const tuple<Ts...> &i1, const tuple<Qs...> &i2,
1226
+ Func &&func, index_sequence<Is...>)
1227
+ { return tuple<invoke_result_t<Func, Ts, Qs>...>{func(get<Is>(i1),get<Is>(i2))...}; }
1228
+ template<typename... Ts, typename ...Qs, typename Func>
1229
+ inline auto tuple_transform2(const tuple<Ts...> &i1, const tuple<Qs...> &i2,
1230
+ Func &&func)
1231
+ {
1232
+ return tuple_transform2_impl(i1, i2, std::forward<Func>(func),
1233
+ make_index_sequence<sizeof...(Ts)>{});
1234
+ }
1235
+ template<typename Tptrs, typename Tinfos>
1236
+ auto make_mavrefs(const Tptrs &ptrs, const Tinfos &infos)
1237
+ {
1238
+ return tuple_transform2(ptrs, infos, [](auto &&ptr, auto &&info)
1239
+ { return make_mavref(info, ptr); });
1240
+ }
1241
+
1242
+ template<size_t ndim> auto make_infos(const fmav_info &info)
1243
+ {
1244
+ if constexpr(ndim>0)
1245
+ MR_assert(ndim<=info.ndim(), "bad dimensionality");
1246
+ auto iterdim = info.ndim()-ndim;
1247
+ fmav_info fout({info.shape().begin(),info.shape().begin()+iterdim},
1248
+ {info.stride().begin(),info.stride().begin()+iterdim});
1249
+
1250
+ typename mav_info<ndim>::shape_t shp;
1251
+ typename mav_info<ndim>::stride_t str;
1252
+ if constexpr (ndim>0) // just to silence compiler warnings
1253
+ for (size_t i=0; i<ndim; ++i)
1254
+ {
1255
+ shp[i] = info.shape(iterdim+i);
1256
+ str[i] = info.stride(iterdim+i);
1257
+ }
1258
+ mav_info<ndim> iout(shp, str);
1259
+ return make_tuple(fout, iout);
1260
+ }
1261
+
1262
+ template<typename Tptrs, typename Tinfos, typename Func>
1263
+ DUCC0_NOINLINE void flexible_mav_applyHelper(size_t idim, const vector<size_t> &shp,
1264
+ const vector<vector<ptrdiff_t>> &str, const Tptrs &ptrs,
1265
+ const Tinfos &infos, Func &&func)
1266
+ {
1267
+ auto len = shp[idim];
1268
+ auto locptrs(ptrs);
1269
+ if (idim+1<shp.size())
1270
+ for (size_t i=0; i<len; ++i, advance(locptrs, str, idim))
1271
+ flexible_mav_applyHelper(idim+1, shp, str, locptrs, infos, func);
1272
+ else
1273
+ for (size_t i=0; i<len; ++i, advance(locptrs, str, idim))
1274
+ call_with_tuple2(func, make_mavrefs(locptrs, infos));
1275
+ }
1276
+ template<typename Tptrs, typename Tinfos, typename Func>
1277
+ DUCC0_NOINLINE void flexible_mav_applyHelper(const vector<size_t> &shp,
1278
+ const vector<vector<ptrdiff_t>> &str, const Tptrs &ptrs,
1279
+ const Tinfos &infos, Func &&func, size_t nthreads)
1280
+ {
1281
+ if (shp.size()==0)
1282
+ call_with_tuple2(func, make_mavrefs(ptrs, infos));
1283
+ else if (nthreads==1)
1284
+ flexible_mav_applyHelper(0, shp, str, ptrs, infos, std::forward<Func>(func));
1285
+ else
1286
+ execParallel(shp[0], nthreads, [&](size_t lo, size_t hi)
1287
+ {
1288
+ auto locptrs = update_pointers(ptrs, str, 0, lo);
1289
+ auto locshp(shp);
1290
+ locshp[0] = hi-lo;
1291
+ flexible_mav_applyHelper(0, locshp, str, locptrs, infos, func);
1292
+ });
1293
+ }
1294
+
1295
+ template<size_t ndim> struct Xdim { static constexpr size_t dim=ndim; };
1296
+
1297
+ template<typename Ttuple, typename Tdim, typename Func>
1298
+ void xflexible_mav_apply(const Ttuple &tuple, const Tdim &dim, Func &&func, size_t nthreads)
1299
+ {
1300
+ auto fullinfos = tuple_transform2(tuple, dim, [](const auto &arg, const auto &dim)
1301
+ { return make_infos<remove_reference_t<decltype(dim)>::dim>(fmav_info(arg)); });
1302
+ vector<fmav_info> iter_infos;
1303
+ tuple_for_each(fullinfos,[&iter_infos](const auto &entry){iter_infos.push_back(get<0>(entry));});
1304
+ auto [shp, str] = multiprep(iter_infos);
1305
+
1306
+ auto infos2 = tuple_transform(fullinfos, [](const auto &arg)
1307
+ { return get<1>(arg); });
1308
+ auto ptrs = tuple_transform(tuple, [](auto &&arg){return arg.data();});
1309
+ flexible_mav_applyHelper(shp, str, ptrs, infos2, std::forward<Func>(func), nthreads);
1310
+ }
1311
+
1312
+ template<size_t nd0, typename T0, typename Func>
1313
+ void flexible_mav_apply(Func &&func, size_t nthreads, T0 &&m0)
1314
+ {
1315
+ xflexible_mav_apply(forward_as_tuple(m0),
1316
+ forward_as_tuple(Xdim<nd0>()),
1317
+ std::forward<Func>(func), nthreads);
1318
+ }
1319
+
1320
+ template<size_t nd0, size_t nd1, typename T0, typename T1, typename Func>
1321
+ void flexible_mav_apply(Func &&func, size_t nthreads, T0 &&m0, T1 &&m1)
1322
+ {
1323
+ xflexible_mav_apply(forward_as_tuple(m0, m1),
1324
+ forward_as_tuple(Xdim<nd0>(), Xdim<nd1>()),
1325
+ std::forward<Func>(func), nthreads);
1326
+ }
1327
+
1328
+ template<size_t nd0, size_t nd1, size_t nd2,
1329
+ typename T0, typename T1, typename T2, typename Func>
1330
+ void flexible_mav_apply(Func &&func, size_t nthreads, T0 &&m0, T1 &&m1, T2 &&m2)
1331
+ {
1332
+ xflexible_mav_apply(forward_as_tuple(m0, m1, m2),
1333
+ forward_as_tuple(Xdim<nd0>(), Xdim<nd1>(), Xdim<nd2>()),
1334
+ std::forward<Func>(func), nthreads);
1335
+ }
1336
+
1337
+ }
1338
+
1339
+ using detail_mav::UNINITIALIZED;
1340
+ using detail_mav::fmav_info;
1341
+ using detail_mav::mav_info;
1342
+ using detail_mav::slice;
1343
+ using detail_mav::MAXIDX;
1344
+ using detail_mav::cfmav;
1345
+ using detail_mav::vfmav;
1346
+ using detail_mav::cmav;
1347
+ using detail_mav::vmav;
1348
+ using detail_mav::subarray;
1349
+ using detail_mav::mav_apply;
1350
+ using detail_mav::mav_apply_with_index;
1351
+ using detail_mav::flexible_mav_apply;
1352
+ }
1353
+
1354
+ #endif
deps/exla/cache/xla_extension/include/_virtual_includes/fft/ducc/src/ducc0/infra/threading.h ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** \file ducc0/infra/threading.h
2
+ * Mulithreading support, similar to functionality provided by OpenMP
3
+ *
4
+ * \copyright Copyright (C) 2019-2023 Peter Bell, Max-Planck-Society
5
+ * \authors Peter Bell, Martin Reinecke
6
+ */
7
+
8
+ /* SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0-or-later */
9
+
10
+ /*
11
+ All rights reserved.
12
+
13
+ Redistribution and use in source and binary forms, with or without modification,
14
+ are permitted provided that the following conditions are met:
15
+
16
+ * Redistributions of source code must retain the above copyright notice, this
17
+ list of conditions and the following disclaimer.
18
+ * Redistributions in binary form must reproduce the above copyright notice, this
19
+ list of conditions and the following disclaimer in the documentation and/or
20
+ other materials provided with the distribution.
21
+ * Neither the name of the copyright holder nor the names of its contributors may
22
+ be used to endorse or promote products derived from this software without
23
+ specific prior written permission.
24
+
25
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
26
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
27
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
29
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
32
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
+ */
36
+
37
+ /*
38
+ * This code is free software; you can redistribute it and/or modify
39
+ * it under the terms of the GNU General Public License as published by
40
+ * the Free Software Foundation; either version 2 of the License, or
41
+ * (at your option) any later version.
42
+ *
43
+ * This code is distributed in the hope that it will be useful,
44
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
45
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46
+ * GNU General Public License for more details.
47
+ *
48
+ * You should have received a copy of the GNU General Public License
49
+ * along with this code; if not, write to the Free Software
50
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
51
+ */
52
+
53
+ #ifndef DUCC0_THREADING_H
54
+ #define DUCC0_THREADING_H
55
+
56
+ // Low level threading support can be influenced by the following macros:
57
+ // - DUCC0_NO_LOWLEVEL_THREADING: if defined, multithreading is disabled
58
+ // and all parallel regions will be executed sequentially
59
+ // on the invoking thread.
60
+ // - DUCC0_CUSTOM_LOWLEVEL_THREADING: if defined, external definitions of
61
+ // Mutex, UniqueLock, LockGuard, CondVar, set_active_pool(),
62
+ // and get active_pool() must be supplied in "ducc0_custom_lowlevel_threading.h"
63
+ // and the code will use those.
64
+ // Both macros must not be defined at the same time.
65
+ // If neither macro is defined, standard ducc0 multihreading will be active.
66
+
67
+ #if (defined(DUCC0_NO_LOWLEVEL_THREADING) && defined(DUCC0_CUSTOM_LOWLEVEL_THREADING))
68
+ static_assert(false, "DUCC0_NO_LOWLEVEL_THREADING and DUCC0_CUSTOMLOWLEVEL_THREADING must not be both defined");
69
+ #endif
70
+
71
+ #if defined(DUCC0_STDCXX_LOWLEVEL_THREADING)
72
+ static_assert(false, "DUCC0_STDCXX_LOWLEVEL_THREADING must not be defined externally");
73
+ #endif
74
+
75
+ #if ((!defined(DUCC0_NO_LOWLEVEL_THREADING)) && (!defined(DUCC0_CUSTOM_LOWLEVEL_THREADING)))
76
+ #define DUCC0_STDCXX_LOWLEVEL_THREADING
77
+ #endif
78
+
79
+ #include <cstddef>
80
+ #include <functional>
81
+ #include <optional>
82
+ #include <vector>
83
+
84
+ #include "ducc0/infra/error_handling.h"
85
+
86
+ // threading-specific headers
87
+ #ifdef DUCC0_STDCXX_LOWLEVEL_THREADING
88
+ #include <mutex>
89
+ #include <condition_variable>
90
+ #endif
91
+
92
+ #ifdef DUCC0_NO_LOWLEVEL_THREADING
93
+ // no headers needed
94
+ #endif
95
+
96
+ namespace ducc0 {
97
+ namespace detail_threading {
98
+
99
+ using std::size_t;
100
+
101
+ /// Abstract base class for minimalistic thread pool functionality
102
+ class thread_pool
103
+ {
104
+ public:
105
+ virtual ~thread_pool() {}
106
+ /// Returns the total number of threads managed by the pool
107
+ virtual size_t nthreads() const = 0;
108
+ /** "Normalizes" a requested number of threads. A useful convention could be
109
+ return (nthreads_in==0) ? nthreads() : min(nthreads(), nthreads_in); */
110
+ virtual void resize(size_t /*nthreads_new*/)
111
+ { MR_fail("Resizing is not supported by this thread pool"); }
112
+ virtual size_t adjust_nthreads(size_t nthreads_in) const = 0;
113
+ virtual void submit(std::function<void()> work) = 0;
114
+ };
115
+
116
+ }}
117
+
118
+ #ifdef DUCC0_CUSTOM_LOWLEVEL_THREADING
119
+ #include "ducc0_custom_lowlevel_threading.h"
120
+ #endif
121
+
122
+ namespace ducc0 {
123
+
124
+ namespace detail_threading {
125
+
126
+ thread_pool *set_active_pool(thread_pool *new_pool);
127
+ thread_pool *get_active_pool();
128
+
129
+ // define threading related types dependent on the underlying implementation
130
+ #ifdef DUCC0_STDCXX_LOWLEVEL_THREADING
131
+ using Mutex = std::mutex;
132
+ using UniqueLock = std::unique_lock<std::mutex>;
133
+ using LockGuard = std::lock_guard<std::mutex>;
134
+ using CondVar = std::condition_variable;
135
+ #endif
136
+
137
+ #ifdef DUCC0_NO_LOWLEVEL_THREADING
138
+ struct Mutex
139
+ {
140
+ void lock(){}
141
+ void unlock(){}
142
+ };
143
+ struct LockGuard
144
+ {
145
+ LockGuard(const Mutex &){}
146
+ };
147
+ struct UniqueLock
148
+ {
149
+ UniqueLock(const Mutex &){}
150
+ void lock() {}
151
+ void unlock() {}
152
+ };
153
+ struct CondVar
154
+ {
155
+ template<class Predicate>
156
+ void wait(UniqueLock &, Predicate) {}
157
+ void notify_one() noexcept {}
158
+ void notify_all() noexcept {}
159
+ };
160
+ #endif
161
+
162
+ using std::size_t;
163
+
164
+ class ScopedUseThreadPool
165
+ {
166
+ private:
167
+ thread_pool *old_pool_;
168
+ public:
169
+ ScopedUseThreadPool(thread_pool &pool)
170
+ { old_pool_ = set_active_pool(&pool); }
171
+ ~ScopedUseThreadPool()
172
+ { set_active_pool(old_pool_); }
173
+ };
174
+
175
+ /// Index range describing a chunk of work inside a parallelized loop
176
+ struct Range
177
+ {
178
+ size_t lo, //< first index of the chunk
179
+ hi; //< one-past-last index of the chunk
180
+ Range() : lo(0), hi(0) {}
181
+ Range(size_t lo_, size_t hi_) : lo(lo_), hi(hi_) {}
182
+ /// Returns true iff the chunk is not empty
183
+ operator bool() const { return hi>lo; }
184
+ };
185
+
186
+ /// Class supplied to parallel regions, which allows them to determine their
187
+ /// work chunks.
188
+ class Scheduler
189
+ {
190
+ public:
191
+ virtual ~Scheduler() {}
192
+ /// Returns the number of threads working in this parallel region
193
+ virtual size_t num_threads() const = 0;
194
+ /// Returns the number of this thread, from the range 0 to num_threads()-1.
195
+ virtual size_t thread_num() const = 0;
196
+ /// Returns information about the next chunk of work.
197
+ /// If this chunk is empty, the work on this thread is done.
198
+ virtual Range getNext() = 0;
199
+ };
200
+
201
+ size_t available_hardware_threads();
202
+ /** Returns the maximum number of threads that are supported by currently
203
+ active thread pool. */
204
+ size_t thread_pool_size();
205
+ void resize_thread_pool(size_t nthreads_new);
206
+ size_t adjust_nthreads(size_t nthreads);
207
+
208
+ /// Execute \a func over \a nwork work items, on a single thread.
209
+ void execSingle(size_t nwork,
210
+ std::function<void(Scheduler &)> func);
211
+ /// Execute \a func over \a nwork work items, on \a nthreads threads.
212
+ /** Chunks will have the size \a chunksize, except for the last one which
213
+ * may be smaller.
214
+ *
215
+ * Chunks are statically assigned to threads at startup. */
216
+ void execStatic(size_t nwork, size_t nthreads, size_t chunksize,
217
+ std::function<void(Scheduler &)> func);
218
+ /// Execute \a func over \a nwork work items, on \a nthreads threads.
219
+ /** Chunks will have the size \a chunksize, except for the last one which
220
+ * may be smaller.
221
+ *
222
+ * Chunks are assigned dynamically to threads;whenever a thread is finished
223
+ * with its current chunk, it will obtain the next one from the list of
224
+ * remaining chunks. */
225
+ void execDynamic(size_t nwork, size_t nthreads, size_t chunksize,
226
+ std::function<void(Scheduler &)> func);
227
+ void execGuided(size_t nwork, size_t nthreads, size_t chunksize_min,
228
+ double fact_max, std::function<void(Scheduler &)> func);
229
+ /// Execute \a func on \a nthreads threads.
230
+ /** Work subdivision must be organized within \a func. */
231
+ void execParallel(size_t nthreads, std::function<void(Scheduler &)> func);
232
+ /// Execute \a func on \a nthreads threads, passing only the thread number.
233
+ /** Work subdivision must be organized within \a func. */
234
+ void execParallel(size_t nthreads, std::function<void(size_t)> func);
235
+ /// Execute \a func on work items [\a lo; \a hi[ over \a nthreads threads.
236
+ /** Work items are subdivided fairly among threads. */
237
+ void execParallel(size_t work_lo, size_t work_hi, size_t nthreads,
238
+ std::function<void(size_t, size_t)> func);
239
+ /// Execute \a func on work items [0; \a nwork[ over \a nthreads threads.
240
+ /** Work items are subdivided fairly among threads. */
241
+ inline void execParallel(size_t nwork, size_t nthreads,
242
+ std::function<void(size_t, size_t)> func)
243
+ { execParallel(0, nwork, nthreads, func); }
244
+ /// Execute \a func on work items [\a lo; \a hi[ over \a nthreads threads.
245
+ /** The first argument to \a func is the thread number.
246
+ *
247
+ * Work items are subdivided fairly among threads. */
248
+ void execParallel(size_t work_lo, size_t work_hi, size_t nthreads,
249
+ std::function<void(size_t, size_t, size_t)> func);
250
+ /// Execute \a func on work items [0; \a nwork[ over \a nthreads threads.
251
+ /** The first argument to \a func is the thread number.
252
+ *
253
+ * Work items are subdivided fairly among threads. */
254
+ inline void execParallel(size_t nwork, size_t nthreads,
255
+ std::function<void(size_t, size_t, size_t)> func)
256
+ { execParallel(0, nwork, nthreads, func); }
257
+
258
+ template<typename T> class Worklist
259
+ {
260
+ private:
261
+ Mutex mtx;
262
+ CondVar cv;
263
+ size_t nworking{0};
264
+ std::vector<T> items;
265
+
266
+ public:
267
+ Worklist(const std::vector<T> &items_)
268
+ : items(items_) {}
269
+
270
+ std::optional<T> get_item()
271
+ {
272
+ UniqueLock lck(mtx);
273
+ if ((--nworking==0) && items.empty()) cv.notify_all();
274
+ cv.wait(lck,[&](){return (!items.empty()) || (nworking==0);});
275
+ if (!items.empty())
276
+ {
277
+ auto res = items.back();
278
+ items.pop_back();
279
+ ++nworking;
280
+ return res;
281
+ }
282
+ else
283
+ return {};
284
+ }
285
+ void startup()
286
+ {
287
+ LockGuard lck(mtx);
288
+ ++nworking;
289
+ }
290
+ void put_item(const T &item)
291
+ {
292
+ LockGuard lck(mtx);
293
+ items.push_back(item);
294
+ cv.notify_one();
295
+ }
296
+ };
297
+
298
+ /// Execute \a func on work items in \a items over \a nthreads threads.
299
+ /** While processing a work item, \a func may submit further items to the list
300
+ * of work items. For this purpose, \a func must take a const T &
301
+ * (the work item to be processed) as well as a function which also takes
302
+ * a const T & (the insert function). Work items will be assigned whenever a
303
+ * thread becomes available. */
304
+ template<typename T, typename Func> auto execWorklist
305
+ (size_t nthreads, const std::vector<T> &items, Func &&func)
306
+ {
307
+ Worklist<T> wl(items);
308
+ execParallel(nthreads, [&wl, &func](auto &) {
309
+ wl.startup();
310
+ while(auto wrk=wl.get_item())
311
+ func(wrk.value(), [&wl](const T &item){wl.put_item(item);});
312
+ });
313
+ }
314
+
315
+ } // end of namespace detail_threading
316
+
317
+ using detail_threading::Mutex;
318
+ using detail_threading::LockGuard;
319
+ using detail_threading::UniqueLock;
320
+ using detail_threading::CondVar;
321
+ using detail_threading::thread_pool;
322
+ using detail_threading::ScopedUseThreadPool;
323
+ using detail_threading::available_hardware_threads;
324
+ using detail_threading::thread_pool_size;
325
+ using detail_threading::resize_thread_pool;
326
+ using detail_threading::adjust_nthreads;
327
+ using detail_threading::Scheduler;
328
+ using detail_threading::execSingle;
329
+ using detail_threading::execStatic;
330
+ using detail_threading::execDynamic;
331
+ using detail_threading::execGuided;
332
+ using detail_threading::execParallel;
333
+ using detail_threading::execWorklist;
334
+
335
+ } // end of namespace ducc0
336
+
337
+ #endif
deps/exla/cache/xla_extension/include/_virtual_includes/fft_wrapper/ducc/google/fft.h ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2023 The TensorFlow Authors. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #ifndef THIRD_PARTY_DUCC_GOOGLE_FFT_H_
17
+ #define THIRD_PARTY_DUCC_GOOGLE_FFT_H_
18
+
19
+ // Wrapper around the DUCC FFT library to isolate usage of exceptions
20
+ // and RTTI. Eliminates all direct usage of DUCC headers.
21
+
22
+ #include <complex>
23
+ #include <cstddef>
24
+ #include <vector>
25
+
26
+ #include "unsupported/Eigen/CXX11/ThreadPool"
27
+
28
+ namespace ducc0 {
29
+ namespace google {
30
+
31
+ using Shape = std::vector<std::size_t>;
32
+ using Stride = std::vector<std::ptrdiff_t>;
33
+
34
+ template <typename RealScalar>
35
+ void c2c(const std::complex<RealScalar>* in, const Shape& in_shape,
36
+ const Stride& in_stride, std::complex<RealScalar>* out,
37
+ const Shape& out_shape, const Stride& out_stride, const Shape& axes,
38
+ bool forward, RealScalar scale,
39
+ Eigen::ThreadPoolInterface* thread_pool);
40
+
41
+ template <typename RealScalar>
42
+ void r2c(const RealScalar* in, const Shape& in_shape, const Stride& in_stride,
43
+ std::complex<RealScalar>* out, const Shape& out_shape,
44
+ const Stride& out_stride, const Shape& axes, bool forward,
45
+ RealScalar scale, Eigen::ThreadPoolInterface* thread_pool);
46
+
47
+ template <typename RealScalar>
48
+ void c2r(const std::complex<RealScalar>* in, const Shape& in_shape,
49
+ const Stride& in_stride, RealScalar* out, const Shape& out_shape,
50
+ const Stride& out_stride, const Shape& axes, bool forward,
51
+ RealScalar scale, Eigen::ThreadPoolInterface* thread_pool);
52
+
53
+ #define FFT_DECLARATIONS(RealScalar) \
54
+ extern template void c2c<RealScalar>( \
55
+ const std::complex<RealScalar>* in, const Shape& in_shape, \
56
+ const Stride& in_stride, std::complex<RealScalar>* out, \
57
+ const Shape& out_shape, const Stride& out_stride, const Shape& axes, \
58
+ bool forward, RealScalar scale, \
59
+ Eigen::ThreadPoolInterface* thread_pool); \
60
+ extern template void r2c<RealScalar>( \
61
+ const RealScalar* in, const Shape& in_shape, const Stride& in_stride, \
62
+ std::complex<RealScalar>* out, const Shape& out_shape, \
63
+ const Stride& out_stride, const Shape& axes, bool forward, \
64
+ RealScalar scale, Eigen::ThreadPoolInterface* thread_pool); \
65
+ extern template void c2r( \
66
+ const std::complex<RealScalar>* in, const Shape& in_shape, \
67
+ const Stride& in_stride, RealScalar* out, const Shape& out_shape, \
68
+ const Stride& out_stride, const Shape& axes, bool forward, \
69
+ RealScalar scale, Eigen::ThreadPoolInterface* thread_pool)
70
+ FFT_DECLARATIONS(float);
71
+ FFT_DECLARATIONS(double);
72
+ #undef FFT_DECLARATIONS
73
+
74
+ } // namespace google
75
+ } // namespace ducc0
76
+
77
+ #endif // THIRD_PARTY_DUCC_GOOGLE_FFT_H_
deps/exla/cache/xla_extension/include/_virtual_includes/pthreadpool/pthreadpool.h ADDED
The diff for this file is too large to render. See raw diff
 
deps/exla/cache/xla_extension/include/external/snappy/config.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #define HAVE_STDDEF_H 1
2
+ #define HAVE_STDINT_H 1
3
+
4
+ #ifdef __has_builtin
5
+ # if !defined(HAVE_BUILTIN_EXPECT) && __has_builtin(__builtin_expect)
6
+ # define HAVE_BUILTIN_EXPECT 1
7
+ # endif
8
+ # if !defined(HAVE_BUILTIN_CTZ) && __has_builtin(__builtin_ctzll)
9
+ # define HAVE_BUILTIN_CTZ 1
10
+ # endif
11
+ #elif defined(__GNUC__) && (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 4)
12
+ # ifndef HAVE_BUILTIN_EXPECT
13
+ # define HAVE_BUILTIN_EXPECT 1
14
+ # endif
15
+ # ifndef HAVE_BUILTIN_CTZ
16
+ # define HAVE_BUILTIN_CTZ 1
17
+ # endif
18
+ #endif
19
+
20
+ #ifdef __has_include
21
+ # if !defined(HAVE_BYTESWAP_H) && __has_include(<byteswap.h>)
22
+ # define HAVE_BYTESWAP_H 1
23
+ # endif
24
+ # if !defined(HAVE_UNISTD_H) && __has_include(<unistd.h>)
25
+ # define HAVE_UNISTD_H 1
26
+ # endif
27
+ # if !defined(HAVE_SYS_ENDIAN_H) && __has_include(<sys/endian.h>)
28
+ # define HAVE_SYS_ENDIAN_H 1
29
+ # endif
30
+ # if !defined(HAVE_SYS_MMAN_H) && __has_include(<sys/mman.h>)
31
+ # define HAVE_SYS_MMAN_H 1
32
+ # endif
33
+ # if !defined(HAVE_SYS_UIO_H) && __has_include(<sys/uio.h>)
34
+ # define HAVE_SYS_UIO_H 1
35
+ # endif
36
+ #endif
37
+
38
+ #ifndef SNAPPY_IS_BIG_ENDIAN
39
+ # ifdef __s390x__
40
+ # define SNAPPY_IS_BIG_ENDIAN 1
41
+ # elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
42
+ # define SNAPPY_IS_BIG_ENDIAN 1
43
+ # endif
44
+ #endif
deps/exla/cache/xla_extension/include/external/snappy/snappy-internal.h ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2008 Google Inc. All Rights Reserved.
2
+ //
3
+ // Redistribution and use in source and binary forms, with or without
4
+ // modification, are permitted provided that the following conditions are
5
+ // met:
6
+ //
7
+ // * Redistributions of source code must retain the above copyright
8
+ // notice, this list of conditions and the following disclaimer.
9
+ // * Redistributions in binary form must reproduce the above
10
+ // copyright notice, this list of conditions and the following disclaimer
11
+ // in the documentation and/or other materials provided with the
12
+ // distribution.
13
+ // * Neither the name of Google Inc. nor the names of its
14
+ // contributors may be used to endorse or promote products derived from
15
+ // this software without specific prior written permission.
16
+ //
17
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+ //
29
+ // Internals shared between the Snappy implementation and its unittest.
30
+
31
+ #ifndef THIRD_PARTY_SNAPPY_SNAPPY_INTERNAL_H_
32
+ #define THIRD_PARTY_SNAPPY_SNAPPY_INTERNAL_H_
33
+
34
+ #include "snappy-stubs-internal.h"
35
+
36
+ #if SNAPPY_HAVE_SSSE3
37
+ // Please do not replace with <x86intrin.h> or with headers that assume more
38
+ // advanced SSE versions without checking with all the OWNERS.
39
+ #include <emmintrin.h>
40
+ #include <tmmintrin.h>
41
+ #endif
42
+
43
+ #if SNAPPY_HAVE_NEON
44
+ #include <arm_neon.h>
45
+ #endif
46
+
47
+ #if SNAPPY_HAVE_SSSE3 || SNAPPY_HAVE_NEON
48
+ #define SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE 1
49
+ #else
50
+ #define SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE 0
51
+ #endif
52
+
53
+ namespace snappy {
54
+ namespace internal {
55
+
56
+ #if SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
57
+ #if SNAPPY_HAVE_SSSE3
58
+ using V128 = __m128i;
59
+ #elif SNAPPY_HAVE_NEON
60
+ using V128 = uint8x16_t;
61
+ #endif
62
+
63
+ // Load 128 bits of integer data. `src` must be 16-byte aligned.
64
+ inline V128 V128_Load(const V128* src);
65
+
66
+ // Load 128 bits of integer data. `src` does not need to be aligned.
67
+ inline V128 V128_LoadU(const V128* src);
68
+
69
+ // Store 128 bits of integer data. `dst` does not need to be aligned.
70
+ inline void V128_StoreU(V128* dst, V128 val);
71
+
72
+ // Shuffle packed 8-bit integers using a shuffle mask.
73
+ // Each packed integer in the shuffle mask must be in [0,16).
74
+ inline V128 V128_Shuffle(V128 input, V128 shuffle_mask);
75
+
76
+ // Constructs V128 with 16 chars |c|.
77
+ inline V128 V128_DupChar(char c);
78
+
79
+ #if SNAPPY_HAVE_SSSE3
80
+ inline V128 V128_Load(const V128* src) { return _mm_load_si128(src); }
81
+
82
+ inline V128 V128_LoadU(const V128* src) { return _mm_loadu_si128(src); }
83
+
84
+ inline void V128_StoreU(V128* dst, V128 val) { _mm_storeu_si128(dst, val); }
85
+
86
+ inline V128 V128_Shuffle(V128 input, V128 shuffle_mask) {
87
+ return _mm_shuffle_epi8(input, shuffle_mask);
88
+ }
89
+
90
+ inline V128 V128_DupChar(char c) { return _mm_set1_epi8(c); }
91
+
92
+ #elif SNAPPY_HAVE_NEON
93
+ inline V128 V128_Load(const V128* src) {
94
+ return vld1q_u8(reinterpret_cast<const uint8_t*>(src));
95
+ }
96
+
97
+ inline V128 V128_LoadU(const V128* src) {
98
+ return vld1q_u8(reinterpret_cast<const uint8_t*>(src));
99
+ }
100
+
101
+ inline void V128_StoreU(V128* dst, V128 val) {
102
+ vst1q_u8(reinterpret_cast<uint8_t*>(dst), val);
103
+ }
104
+
105
+ inline V128 V128_Shuffle(V128 input, V128 shuffle_mask) {
106
+ assert(vminvq_u8(shuffle_mask) >= 0 && vmaxvq_u8(shuffle_mask) <= 15);
107
+ return vqtbl1q_u8(input, shuffle_mask);
108
+ }
109
+
110
+ inline V128 V128_DupChar(char c) { return vdupq_n_u8(c); }
111
+ #endif
112
+ #endif // SNAPPY_HAVE_VECTOR_BYTE_SHUFFLE
113
+
114
+ // Working memory performs a single allocation to hold all scratch space
115
+ // required for compression.
116
+ class WorkingMemory {
117
+ public:
118
+ explicit WorkingMemory(size_t input_size);
119
+ ~WorkingMemory();
120
+
121
+ // Allocates and clears a hash table using memory in "*this",
122
+ // stores the number of buckets in "*table_size" and returns a pointer to
123
+ // the base of the hash table.
124
+ uint16_t* GetHashTable(size_t fragment_size, int* table_size) const;
125
+ char* GetScratchInput() const { return input_; }
126
+ char* GetScratchOutput() const { return output_; }
127
+
128
+ private:
129
+ char* mem_; // the allocated memory, never nullptr
130
+ size_t size_; // the size of the allocated memory, never 0
131
+ uint16_t* table_; // the pointer to the hashtable
132
+ char* input_; // the pointer to the input scratch buffer
133
+ char* output_; // the pointer to the output scratch buffer
134
+
135
+ // No copying
136
+ WorkingMemory(const WorkingMemory&);
137
+ void operator=(const WorkingMemory&);
138
+ };
139
+
140
+ // Flat array compression that does not emit the "uncompressed length"
141
+ // prefix. Compresses "input" string to the "*op" buffer.
142
+ //
143
+ // REQUIRES: "input_length <= kBlockSize"
144
+ // REQUIRES: "op" points to an array of memory that is at least
145
+ // "MaxCompressedLength(input_length)" in size.
146
+ // REQUIRES: All elements in "table[0..table_size-1]" are initialized to zero.
147
+ // REQUIRES: "table_size" is a power of two
148
+ //
149
+ // Returns an "end" pointer into "op" buffer.
150
+ // "end - op" is the compressed size of "input".
151
+ char* CompressFragment(const char* input,
152
+ size_t input_length,
153
+ char* op,
154
+ uint16_t* table,
155
+ const int table_size);
156
+
157
+ // Find the largest n such that
158
+ //
159
+ // s1[0,n-1] == s2[0,n-1]
160
+ // and n <= (s2_limit - s2).
161
+ //
162
+ // Return make_pair(n, n < 8).
163
+ // Does not read *s2_limit or beyond.
164
+ // Does not read *(s1 + (s2_limit - s2)) or beyond.
165
+ // Requires that s2_limit >= s2.
166
+ //
167
+ // In addition populate *data with the next 5 bytes from the end of the match.
168
+ // This is only done if 8 bytes are available (s2_limit - s2 >= 8). The point is
169
+ // that on some arch's this can be done faster in this routine than subsequent
170
+ // loading from s2 + n.
171
+ //
172
+ // Separate implementation for 64-bit, little-endian cpus.
173
+ #if !SNAPPY_IS_BIG_ENDIAN && \
174
+ (defined(__x86_64__) || defined(_M_X64) || defined(ARCH_PPC) || \
175
+ defined(ARCH_ARM))
176
+ static inline std::pair<size_t, bool> FindMatchLength(const char* s1,
177
+ const char* s2,
178
+ const char* s2_limit,
179
+ uint64_t* data) {
180
+ assert(s2_limit >= s2);
181
+ size_t matched = 0;
182
+
183
+ // This block isn't necessary for correctness; we could just start looping
184
+ // immediately. As an optimization though, it is useful. It creates some not
185
+ // uncommon code paths that determine, without extra effort, whether the match
186
+ // length is less than 8. In short, we are hoping to avoid a conditional
187
+ // branch, and perhaps get better code layout from the C++ compiler.
188
+ if (SNAPPY_PREDICT_TRUE(s2 <= s2_limit - 16)) {
189
+ uint64_t a1 = UNALIGNED_LOAD64(s1);
190
+ uint64_t a2 = UNALIGNED_LOAD64(s2);
191
+ if (SNAPPY_PREDICT_TRUE(a1 != a2)) {
192
+ // This code is critical for performance. The reason is that it determines
193
+ // how much to advance `ip` (s2). This obviously depends on both the loads
194
+ // from the `candidate` (s1) and `ip`. Furthermore the next `candidate`
195
+ // depends on the advanced `ip` calculated here through a load, hash and
196
+ // new candidate hash lookup (a lot of cycles). This makes s1 (ie.
197
+ // `candidate`) the variable that limits throughput. This is the reason we
198
+ // go through hoops to have this function update `data` for the next iter.
199
+ // The straightforward code would use *data, given by
200
+ //
201
+ // *data = UNALIGNED_LOAD64(s2 + matched_bytes) (Latency of 5 cycles),
202
+ //
203
+ // as input for the hash table lookup to find next candidate. However
204
+ // this forces the load on the data dependency chain of s1, because
205
+ // matched_bytes directly depends on s1. However matched_bytes is 0..7, so
206
+ // we can also calculate *data by
207
+ //
208
+ // *data = AlignRight(UNALIGNED_LOAD64(s2), UNALIGNED_LOAD64(s2 + 8),
209
+ // matched_bytes);
210
+ //
211
+ // The loads do not depend on s1 anymore and are thus off the bottleneck.
212
+ // The straightforward implementation on x86_64 would be to use
213
+ //
214
+ // shrd rax, rdx, cl (cl being matched_bytes * 8)
215
+ //
216
+ // unfortunately shrd with a variable shift has a 4 cycle latency. So this
217
+ // only wins 1 cycle. The BMI2 shrx instruction is a 1 cycle variable
218
+ // shift instruction but can only shift 64 bits. If we focus on just
219
+ // obtaining the least significant 4 bytes, we can obtain this by
220
+ //
221
+ // *data = ConditionalMove(matched_bytes < 4, UNALIGNED_LOAD64(s2),
222
+ // UNALIGNED_LOAD64(s2 + 4) >> ((matched_bytes & 3) * 8);
223
+ //
224
+ // Writen like above this is not a big win, the conditional move would be
225
+ // a cmp followed by a cmov (2 cycles) followed by a shift (1 cycle).
226
+ // However matched_bytes < 4 is equal to
227
+ // static_cast<uint32_t>(xorval) != 0. Writen that way, the conditional
228
+ // move (2 cycles) can execute in parallel with FindLSBSetNonZero64
229
+ // (tzcnt), which takes 3 cycles.
230
+ uint64_t xorval = a1 ^ a2;
231
+ int shift = Bits::FindLSBSetNonZero64(xorval);
232
+ size_t matched_bytes = shift >> 3;
233
+ uint64_t a3 = UNALIGNED_LOAD64(s2 + 4);
234
+ #ifndef __x86_64__
235
+ a2 = static_cast<uint32_t>(xorval) == 0 ? a3 : a2;
236
+ #else
237
+ // Ideally this would just be
238
+ //
239
+ // a2 = static_cast<uint32_t>(xorval) == 0 ? a3 : a2;
240
+ //
241
+ // However clang correctly infers that the above statement participates on
242
+ // a critical data dependency chain and thus, unfortunately, refuses to
243
+ // use a conditional move (it's tuned to cut data dependencies). In this
244
+ // case there is a longer parallel chain anyway AND this will be fairly
245
+ // unpredictable.
246
+ asm("testl %k2, %k2\n\t"
247
+ "cmovzq %1, %0\n\t"
248
+ : "+r"(a2)
249
+ : "r"(a3), "r"(xorval));
250
+ #endif
251
+ *data = a2 >> (shift & (3 * 8));
252
+ return std::pair<size_t, bool>(matched_bytes, true);
253
+ } else {
254
+ matched = 8;
255
+ s2 += 8;
256
+ }
257
+ }
258
+
259
+ // Find out how long the match is. We loop over the data 64 bits at a
260
+ // time until we find a 64-bit block that doesn't match; then we find
261
+ // the first non-matching bit and use that to calculate the total
262
+ // length of the match.
263
+ while (SNAPPY_PREDICT_TRUE(s2 <= s2_limit - 16)) {
264
+ uint64_t a1 = UNALIGNED_LOAD64(s1 + matched);
265
+ uint64_t a2 = UNALIGNED_LOAD64(s2);
266
+ if (a1 == a2) {
267
+ s2 += 8;
268
+ matched += 8;
269
+ } else {
270
+ uint64_t xorval = a1 ^ a2;
271
+ int shift = Bits::FindLSBSetNonZero64(xorval);
272
+ size_t matched_bytes = shift >> 3;
273
+ uint64_t a3 = UNALIGNED_LOAD64(s2 + 4);
274
+ #ifndef __x86_64__
275
+ a2 = static_cast<uint32_t>(xorval) == 0 ? a3 : a2;
276
+ #else
277
+ asm("testl %k2, %k2\n\t"
278
+ "cmovzq %1, %0\n\t"
279
+ : "+r"(a2)
280
+ : "r"(a3), "r"(xorval));
281
+ #endif
282
+ *data = a2 >> (shift & (3 * 8));
283
+ matched += matched_bytes;
284
+ assert(matched >= 8);
285
+ return std::pair<size_t, bool>(matched, false);
286
+ }
287
+ }
288
+ while (SNAPPY_PREDICT_TRUE(s2 < s2_limit)) {
289
+ if (s1[matched] == *s2) {
290
+ ++s2;
291
+ ++matched;
292
+ } else {
293
+ if (s2 <= s2_limit - 8) {
294
+ *data = UNALIGNED_LOAD64(s2);
295
+ }
296
+ return std::pair<size_t, bool>(matched, matched < 8);
297
+ }
298
+ }
299
+ return std::pair<size_t, bool>(matched, matched < 8);
300
+ }
301
+ #else
302
+ static inline std::pair<size_t, bool> FindMatchLength(const char* s1,
303
+ const char* s2,
304
+ const char* s2_limit,
305
+ uint64_t* data) {
306
+ // Implementation based on the x86-64 version, above.
307
+ assert(s2_limit >= s2);
308
+ int matched = 0;
309
+
310
+ while (s2 <= s2_limit - 4 &&
311
+ UNALIGNED_LOAD32(s2) == UNALIGNED_LOAD32(s1 + matched)) {
312
+ s2 += 4;
313
+ matched += 4;
314
+ }
315
+ if (LittleEndian::IsLittleEndian() && s2 <= s2_limit - 4) {
316
+ uint32_t x = UNALIGNED_LOAD32(s2) ^ UNALIGNED_LOAD32(s1 + matched);
317
+ int matching_bits = Bits::FindLSBSetNonZero(x);
318
+ matched += matching_bits >> 3;
319
+ s2 += matching_bits >> 3;
320
+ } else {
321
+ while ((s2 < s2_limit) && (s1[matched] == *s2)) {
322
+ ++s2;
323
+ ++matched;
324
+ }
325
+ }
326
+ if (s2 <= s2_limit - 8) *data = LittleEndian::Load64(s2);
327
+ return std::pair<size_t, bool>(matched, matched < 8);
328
+ }
329
+ #endif
330
+
331
+ // Lookup tables for decompression code. Give --snappy_dump_decompression_table
332
+ // to the unit test to recompute char_table.
333
+
334
+ enum {
335
+ LITERAL = 0,
336
+ COPY_1_BYTE_OFFSET = 1, // 3 bit length + 3 bits of offset in opcode
337
+ COPY_2_BYTE_OFFSET = 2,
338
+ COPY_4_BYTE_OFFSET = 3
339
+ };
340
+ static const int kMaximumTagLength = 5; // COPY_4_BYTE_OFFSET plus the actual offset.
341
+
342
+ // Data stored per entry in lookup table:
343
+ // Range Bits-used Description
344
+ // ------------------------------------
345
+ // 1..64 0..7 Literal/copy length encoded in opcode byte
346
+ // 0..7 8..10 Copy offset encoded in opcode byte / 256
347
+ // 0..4 11..13 Extra bytes after opcode
348
+ //
349
+ // We use eight bits for the length even though 7 would have sufficed
350
+ // because of efficiency reasons:
351
+ // (1) Extracting a byte is faster than a bit-field
352
+ // (2) It properly aligns copy offset so we do not need a <<8
353
+ static constexpr uint16_t char_table[256] = {
354
+ // clang-format off
355
+ 0x0001, 0x0804, 0x1001, 0x2001, 0x0002, 0x0805, 0x1002, 0x2002,
356
+ 0x0003, 0x0806, 0x1003, 0x2003, 0x0004, 0x0807, 0x1004, 0x2004,
357
+ 0x0005, 0x0808, 0x1005, 0x2005, 0x0006, 0x0809, 0x1006, 0x2006,
358
+ 0x0007, 0x080a, 0x1007, 0x2007, 0x0008, 0x080b, 0x1008, 0x2008,
359
+ 0x0009, 0x0904, 0x1009, 0x2009, 0x000a, 0x0905, 0x100a, 0x200a,
360
+ 0x000b, 0x0906, 0x100b, 0x200b, 0x000c, 0x0907, 0x100c, 0x200c,
361
+ 0x000d, 0x0908, 0x100d, 0x200d, 0x000e, 0x0909, 0x100e, 0x200e,
362
+ 0x000f, 0x090a, 0x100f, 0x200f, 0x0010, 0x090b, 0x1010, 0x2010,
363
+ 0x0011, 0x0a04, 0x1011, 0x2011, 0x0012, 0x0a05, 0x1012, 0x2012,
364
+ 0x0013, 0x0a06, 0x1013, 0x2013, 0x0014, 0x0a07, 0x1014, 0x2014,
365
+ 0x0015, 0x0a08, 0x1015, 0x2015, 0x0016, 0x0a09, 0x1016, 0x2016,
366
+ 0x0017, 0x0a0a, 0x1017, 0x2017, 0x0018, 0x0a0b, 0x1018, 0x2018,
367
+ 0x0019, 0x0b04, 0x1019, 0x2019, 0x001a, 0x0b05, 0x101a, 0x201a,
368
+ 0x001b, 0x0b06, 0x101b, 0x201b, 0x001c, 0x0b07, 0x101c, 0x201c,
369
+ 0x001d, 0x0b08, 0x101d, 0x201d, 0x001e, 0x0b09, 0x101e, 0x201e,
370
+ 0x001f, 0x0b0a, 0x101f, 0x201f, 0x0020, 0x0b0b, 0x1020, 0x2020,
371
+ 0x0021, 0x0c04, 0x1021, 0x2021, 0x0022, 0x0c05, 0x1022, 0x2022,
372
+ 0x0023, 0x0c06, 0x1023, 0x2023, 0x0024, 0x0c07, 0x1024, 0x2024,
373
+ 0x0025, 0x0c08, 0x1025, 0x2025, 0x0026, 0x0c09, 0x1026, 0x2026,
374
+ 0x0027, 0x0c0a, 0x1027, 0x2027, 0x0028, 0x0c0b, 0x1028, 0x2028,
375
+ 0x0029, 0x0d04, 0x1029, 0x2029, 0x002a, 0x0d05, 0x102a, 0x202a,
376
+ 0x002b, 0x0d06, 0x102b, 0x202b, 0x002c, 0x0d07, 0x102c, 0x202c,
377
+ 0x002d, 0x0d08, 0x102d, 0x202d, 0x002e, 0x0d09, 0x102e, 0x202e,
378
+ 0x002f, 0x0d0a, 0x102f, 0x202f, 0x0030, 0x0d0b, 0x1030, 0x2030,
379
+ 0x0031, 0x0e04, 0x1031, 0x2031, 0x0032, 0x0e05, 0x1032, 0x2032,
380
+ 0x0033, 0x0e06, 0x1033, 0x2033, 0x0034, 0x0e07, 0x1034, 0x2034,
381
+ 0x0035, 0x0e08, 0x1035, 0x2035, 0x0036, 0x0e09, 0x1036, 0x2036,
382
+ 0x0037, 0x0e0a, 0x1037, 0x2037, 0x0038, 0x0e0b, 0x1038, 0x2038,
383
+ 0x0039, 0x0f04, 0x1039, 0x2039, 0x003a, 0x0f05, 0x103a, 0x203a,
384
+ 0x003b, 0x0f06, 0x103b, 0x203b, 0x003c, 0x0f07, 0x103c, 0x203c,
385
+ 0x0801, 0x0f08, 0x103d, 0x203d, 0x1001, 0x0f09, 0x103e, 0x203e,
386
+ 0x1801, 0x0f0a, 0x103f, 0x203f, 0x2001, 0x0f0b, 0x1040, 0x2040,
387
+ // clang-format on
388
+ };
389
+
390
+ } // end namespace internal
391
+ } // end namespace snappy
392
+
393
+ #endif // THIRD_PARTY_SNAPPY_SNAPPY_INTERNAL_H_
deps/exla/cache/xla_extension/include/external/snappy/snappy-sinksource.h ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 Google Inc. All Rights Reserved.
2
+ //
3
+ // Redistribution and use in source and binary forms, with or without
4
+ // modification, are permitted provided that the following conditions are
5
+ // met:
6
+ //
7
+ // * Redistributions of source code must retain the above copyright
8
+ // notice, this list of conditions and the following disclaimer.
9
+ // * Redistributions in binary form must reproduce the above
10
+ // copyright notice, this list of conditions and the following disclaimer
11
+ // in the documentation and/or other materials provided with the
12
+ // distribution.
13
+ // * Neither the name of Google Inc. nor the names of its
14
+ // contributors may be used to endorse or promote products derived from
15
+ // this software without specific prior written permission.
16
+ //
17
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+
29
+ #ifndef THIRD_PARTY_SNAPPY_SNAPPY_SINKSOURCE_H_
30
+ #define THIRD_PARTY_SNAPPY_SNAPPY_SINKSOURCE_H_
31
+
32
+ #include <stddef.h>
33
+
34
+ namespace snappy {
35
+
36
+ // A Sink is an interface that consumes a sequence of bytes.
37
+ class Sink {
38
+ public:
39
+ Sink() { }
40
+ virtual ~Sink();
41
+
42
+ // Append "bytes[0,n-1]" to this.
43
+ virtual void Append(const char* bytes, size_t n) = 0;
44
+
45
+ // Returns a writable buffer of the specified length for appending.
46
+ // May return a pointer to the caller-owned scratch buffer which
47
+ // must have at least the indicated length. The returned buffer is
48
+ // only valid until the next operation on this Sink.
49
+ //
50
+ // After writing at most "length" bytes, call Append() with the
51
+ // pointer returned from this function and the number of bytes
52
+ // written. Many Append() implementations will avoid copying
53
+ // bytes if this function returned an internal buffer.
54
+ //
55
+ // If a non-scratch buffer is returned, the caller may only pass a
56
+ // prefix of it to Append(). That is, it is not correct to pass an
57
+ // interior pointer of the returned array to Append().
58
+ //
59
+ // The default implementation always returns the scratch buffer.
60
+ virtual char* GetAppendBuffer(size_t length, char* scratch);
61
+
62
+ // For higher performance, Sink implementations can provide custom
63
+ // AppendAndTakeOwnership() and GetAppendBufferVariable() methods.
64
+ // These methods can reduce the number of copies done during
65
+ // compression/decompression.
66
+
67
+ // Append "bytes[0,n-1] to the sink. Takes ownership of "bytes"
68
+ // and calls the deleter function as (*deleter)(deleter_arg, bytes, n)
69
+ // to free the buffer. deleter function must be non NULL.
70
+ //
71
+ // The default implementation just calls Append and frees "bytes".
72
+ // Other implementations may avoid a copy while appending the buffer.
73
+ virtual void AppendAndTakeOwnership(
74
+ char* bytes, size_t n, void (*deleter)(void*, const char*, size_t),
75
+ void *deleter_arg);
76
+
77
+ // Returns a writable buffer for appending and writes the buffer's capacity to
78
+ // *allocated_size. Guarantees *allocated_size >= min_size.
79
+ // May return a pointer to the caller-owned scratch buffer which must have
80
+ // scratch_size >= min_size.
81
+ //
82
+ // The returned buffer is only valid until the next operation
83
+ // on this ByteSink.
84
+ //
85
+ // After writing at most *allocated_size bytes, call Append() with the
86
+ // pointer returned from this function and the number of bytes written.
87
+ // Many Append() implementations will avoid copying bytes if this function
88
+ // returned an internal buffer.
89
+ //
90
+ // If the sink implementation allocates or reallocates an internal buffer,
91
+ // it should use the desired_size_hint if appropriate. If a caller cannot
92
+ // provide a reasonable guess at the desired capacity, it should set
93
+ // desired_size_hint = 0.
94
+ //
95
+ // If a non-scratch buffer is returned, the caller may only pass
96
+ // a prefix to it to Append(). That is, it is not correct to pass an
97
+ // interior pointer to Append().
98
+ //
99
+ // The default implementation always returns the scratch buffer.
100
+ virtual char* GetAppendBufferVariable(
101
+ size_t min_size, size_t desired_size_hint, char* scratch,
102
+ size_t scratch_size, size_t* allocated_size);
103
+
104
+ private:
105
+ // No copying
106
+ Sink(const Sink&);
107
+ void operator=(const Sink&);
108
+ };
109
+
110
+ // A Source is an interface that yields a sequence of bytes
111
+ class Source {
112
+ public:
113
+ Source() { }
114
+ virtual ~Source();
115
+
116
+ // Return the number of bytes left to read from the source
117
+ virtual size_t Available() const = 0;
118
+
119
+ // Peek at the next flat region of the source. Does not reposition
120
+ // the source. The returned region is empty iff Available()==0.
121
+ //
122
+ // Returns a pointer to the beginning of the region and store its
123
+ // length in *len.
124
+ //
125
+ // The returned region is valid until the next call to Skip() or
126
+ // until this object is destroyed, whichever occurs first.
127
+ //
128
+ // The returned region may be larger than Available() (for example
129
+ // if this ByteSource is a view on a substring of a larger source).
130
+ // The caller is responsible for ensuring that it only reads the
131
+ // Available() bytes.
132
+ virtual const char* Peek(size_t* len) = 0;
133
+
134
+ // Skip the next n bytes. Invalidates any buffer returned by
135
+ // a previous call to Peek().
136
+ // REQUIRES: Available() >= n
137
+ virtual void Skip(size_t n) = 0;
138
+
139
+ private:
140
+ // No copying
141
+ Source(const Source&);
142
+ void operator=(const Source&);
143
+ };
144
+
145
+ // A Source implementation that yields the contents of a flat array
146
+ class ByteArraySource : public Source {
147
+ public:
148
+ ByteArraySource(const char* p, size_t n) : ptr_(p), left_(n) { }
149
+ ~ByteArraySource() override;
150
+ size_t Available() const override;
151
+ const char* Peek(size_t* len) override;
152
+ void Skip(size_t n) override;
153
+ private:
154
+ const char* ptr_;
155
+ size_t left_;
156
+ };
157
+
158
+ // A Sink implementation that writes to a flat array without any bound checks.
159
+ class UncheckedByteArraySink : public Sink {
160
+ public:
161
+ explicit UncheckedByteArraySink(char* dest) : dest_(dest) { }
162
+ ~UncheckedByteArraySink() override;
163
+ void Append(const char* data, size_t n) override;
164
+ char* GetAppendBuffer(size_t len, char* scratch) override;
165
+ char* GetAppendBufferVariable(
166
+ size_t min_size, size_t desired_size_hint, char* scratch,
167
+ size_t scratch_size, size_t* allocated_size) override;
168
+ void AppendAndTakeOwnership(
169
+ char* bytes, size_t n, void (*deleter)(void*, const char*, size_t),
170
+ void *deleter_arg) override;
171
+
172
+ // Return the current output pointer so that a caller can see how
173
+ // many bytes were produced.
174
+ // Note: this is not a Sink method.
175
+ char* CurrentDestination() const { return dest_; }
176
+ private:
177
+ char* dest_;
178
+ };
179
+
180
+ } // namespace snappy
181
+
182
+ #endif // THIRD_PARTY_SNAPPY_SNAPPY_SINKSOURCE_H_
deps/exla/cache/xla_extension/include/external/snappy/snappy-stubs-internal.h ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 Google Inc. All Rights Reserved.
2
+ //
3
+ // Redistribution and use in source and binary forms, with or without
4
+ // modification, are permitted provided that the following conditions are
5
+ // met:
6
+ //
7
+ // * Redistributions of source code must retain the above copyright
8
+ // notice, this list of conditions and the following disclaimer.
9
+ // * Redistributions in binary form must reproduce the above
10
+ // copyright notice, this list of conditions and the following disclaimer
11
+ // in the documentation and/or other materials provided with the
12
+ // distribution.
13
+ // * Neither the name of Google Inc. nor the names of its
14
+ // contributors may be used to endorse or promote products derived from
15
+ // this software without specific prior written permission.
16
+ //
17
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+ //
29
+ // Various stubs for the open-source version of Snappy.
30
+
31
+ #ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_
32
+ #define THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_
33
+
34
+ #if HAVE_CONFIG_H
35
+ #include "config.h"
36
+ #endif
37
+
38
+ #include <stdint.h>
39
+
40
+ #include <cassert>
41
+ #include <cstdlib>
42
+ #include <cstring>
43
+ #include <limits>
44
+ #include <string>
45
+
46
+ #if HAVE_SYS_MMAN_H
47
+ #include <sys/mman.h>
48
+ #endif
49
+
50
+ #if HAVE_UNISTD_H
51
+ #include <unistd.h>
52
+ #endif
53
+
54
+ #if defined(_MSC_VER)
55
+ #include <intrin.h>
56
+ #endif // defined(_MSC_VER)
57
+
58
+ #ifndef __has_feature
59
+ #define __has_feature(x) 0
60
+ #endif
61
+
62
+ #if __has_feature(memory_sanitizer)
63
+ #include <sanitizer/msan_interface.h>
64
+ #define SNAPPY_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) \
65
+ __msan_unpoison((address), (size))
66
+ #else
67
+ #define SNAPPY_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) /* empty */
68
+ #endif // __has_feature(memory_sanitizer)
69
+
70
+ #include "snappy-stubs-public.h"
71
+
72
+ // Used to enable 64-bit optimized versions of some routines.
73
+ #if defined(__PPC64__) || defined(__powerpc64__)
74
+ #define ARCH_PPC 1
75
+ #elif defined(__aarch64__) || defined(_M_ARM64)
76
+ #define ARCH_ARM 1
77
+ #endif
78
+
79
+ // Needed by OS X, among others.
80
+ #ifndef MAP_ANONYMOUS
81
+ #define MAP_ANONYMOUS MAP_ANON
82
+ #endif
83
+
84
+ // The size of an array, if known at compile-time.
85
+ // Will give unexpected results if used on a pointer.
86
+ // We undefine it first, since some compilers already have a definition.
87
+ #ifdef ARRAYSIZE
88
+ #undef ARRAYSIZE
89
+ #endif
90
+ #define ARRAYSIZE(a) int{sizeof(a) / sizeof(*(a))}
91
+
92
+ // Static prediction hints.
93
+ #if HAVE_BUILTIN_EXPECT
94
+ #define SNAPPY_PREDICT_FALSE(x) (__builtin_expect(x, 0))
95
+ #define SNAPPY_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
96
+ #else
97
+ #define SNAPPY_PREDICT_FALSE(x) x
98
+ #define SNAPPY_PREDICT_TRUE(x) x
99
+ #endif // HAVE_BUILTIN_EXPECT
100
+
101
+ // Inlining hints.
102
+ #if HAVE_ATTRIBUTE_ALWAYS_INLINE
103
+ #define SNAPPY_ATTRIBUTE_ALWAYS_INLINE __attribute__((always_inline))
104
+ #else
105
+ #define SNAPPY_ATTRIBUTE_ALWAYS_INLINE
106
+ #endif // HAVE_ATTRIBUTE_ALWAYS_INLINE
107
+
108
+ // Stubbed version of ABSL_FLAG.
109
+ //
110
+ // In the open source version, flags can only be changed at compile time.
111
+ #define SNAPPY_FLAG(flag_type, flag_name, default_value, help) \
112
+ flag_type FLAGS_ ## flag_name = default_value
113
+
114
+ namespace snappy {
115
+
116
+ // Stubbed version of absl::GetFlag().
117
+ template <typename T>
118
+ inline T GetFlag(T flag) { return flag; }
119
+
120
+ static const uint32_t kuint32max = std::numeric_limits<uint32_t>::max();
121
+ static const int64_t kint64max = std::numeric_limits<int64_t>::max();
122
+
123
+ // Potentially unaligned loads and stores.
124
+
125
+ inline uint16_t UNALIGNED_LOAD16(const void *p) {
126
+ // Compiles to a single movzx/ldrh on clang/gcc/msvc.
127
+ uint16_t v;
128
+ std::memcpy(&v, p, sizeof(v));
129
+ return v;
130
+ }
131
+
132
+ inline uint32_t UNALIGNED_LOAD32(const void *p) {
133
+ // Compiles to a single mov/ldr on clang/gcc/msvc.
134
+ uint32_t v;
135
+ std::memcpy(&v, p, sizeof(v));
136
+ return v;
137
+ }
138
+
139
+ inline uint64_t UNALIGNED_LOAD64(const void *p) {
140
+ // Compiles to a single mov/ldr on clang/gcc/msvc.
141
+ uint64_t v;
142
+ std::memcpy(&v, p, sizeof(v));
143
+ return v;
144
+ }
145
+
146
+ inline void UNALIGNED_STORE16(void *p, uint16_t v) {
147
+ // Compiles to a single mov/strh on clang/gcc/msvc.
148
+ std::memcpy(p, &v, sizeof(v));
149
+ }
150
+
151
+ inline void UNALIGNED_STORE32(void *p, uint32_t v) {
152
+ // Compiles to a single mov/str on clang/gcc/msvc.
153
+ std::memcpy(p, &v, sizeof(v));
154
+ }
155
+
156
+ inline void UNALIGNED_STORE64(void *p, uint64_t v) {
157
+ // Compiles to a single mov/str on clang/gcc/msvc.
158
+ std::memcpy(p, &v, sizeof(v));
159
+ }
160
+
161
+ // Convert to little-endian storage, opposite of network format.
162
+ // Convert x from host to little endian: x = LittleEndian.FromHost(x);
163
+ // convert x from little endian to host: x = LittleEndian.ToHost(x);
164
+ //
165
+ // Store values into unaligned memory converting to little endian order:
166
+ // LittleEndian.Store16(p, x);
167
+ //
168
+ // Load unaligned values stored in little endian converting to host order:
169
+ // x = LittleEndian.Load16(p);
170
+ class LittleEndian {
171
+ public:
172
+ // Functions to do unaligned loads and stores in little-endian order.
173
+ static inline uint16_t Load16(const void *ptr) {
174
+ const uint8_t* const buffer = reinterpret_cast<const uint8_t*>(ptr);
175
+
176
+ // Compiles to a single mov/str on recent clang and gcc.
177
+ return (static_cast<uint16_t>(buffer[0])) |
178
+ (static_cast<uint16_t>(buffer[1]) << 8);
179
+ }
180
+
181
+ static inline uint32_t Load32(const void *ptr) {
182
+ const uint8_t* const buffer = reinterpret_cast<const uint8_t*>(ptr);
183
+
184
+ // Compiles to a single mov/str on recent clang and gcc.
185
+ return (static_cast<uint32_t>(buffer[0])) |
186
+ (static_cast<uint32_t>(buffer[1]) << 8) |
187
+ (static_cast<uint32_t>(buffer[2]) << 16) |
188
+ (static_cast<uint32_t>(buffer[3]) << 24);
189
+ }
190
+
191
+ static inline uint64_t Load64(const void *ptr) {
192
+ const uint8_t* const buffer = reinterpret_cast<const uint8_t*>(ptr);
193
+
194
+ // Compiles to a single mov/str on recent clang and gcc.
195
+ return (static_cast<uint64_t>(buffer[0])) |
196
+ (static_cast<uint64_t>(buffer[1]) << 8) |
197
+ (static_cast<uint64_t>(buffer[2]) << 16) |
198
+ (static_cast<uint64_t>(buffer[3]) << 24) |
199
+ (static_cast<uint64_t>(buffer[4]) << 32) |
200
+ (static_cast<uint64_t>(buffer[5]) << 40) |
201
+ (static_cast<uint64_t>(buffer[6]) << 48) |
202
+ (static_cast<uint64_t>(buffer[7]) << 56);
203
+ }
204
+
205
+ static inline void Store16(void *dst, uint16_t value) {
206
+ uint8_t* const buffer = reinterpret_cast<uint8_t*>(dst);
207
+
208
+ // Compiles to a single mov/str on recent clang and gcc.
209
+ buffer[0] = static_cast<uint8_t>(value);
210
+ buffer[1] = static_cast<uint8_t>(value >> 8);
211
+ }
212
+
213
+ static void Store32(void *dst, uint32_t value) {
214
+ uint8_t* const buffer = reinterpret_cast<uint8_t*>(dst);
215
+
216
+ // Compiles to a single mov/str on recent clang and gcc.
217
+ buffer[0] = static_cast<uint8_t>(value);
218
+ buffer[1] = static_cast<uint8_t>(value >> 8);
219
+ buffer[2] = static_cast<uint8_t>(value >> 16);
220
+ buffer[3] = static_cast<uint8_t>(value >> 24);
221
+ }
222
+
223
+ static void Store64(void* dst, uint64_t value) {
224
+ uint8_t* const buffer = reinterpret_cast<uint8_t*>(dst);
225
+
226
+ // Compiles to a single mov/str on recent clang and gcc.
227
+ buffer[0] = static_cast<uint8_t>(value);
228
+ buffer[1] = static_cast<uint8_t>(value >> 8);
229
+ buffer[2] = static_cast<uint8_t>(value >> 16);
230
+ buffer[3] = static_cast<uint8_t>(value >> 24);
231
+ buffer[4] = static_cast<uint8_t>(value >> 32);
232
+ buffer[5] = static_cast<uint8_t>(value >> 40);
233
+ buffer[6] = static_cast<uint8_t>(value >> 48);
234
+ buffer[7] = static_cast<uint8_t>(value >> 56);
235
+ }
236
+
237
+ static inline constexpr bool IsLittleEndian() {
238
+ #if SNAPPY_IS_BIG_ENDIAN
239
+ return false;
240
+ #else
241
+ return true;
242
+ #endif // SNAPPY_IS_BIG_ENDIAN
243
+ }
244
+ };
245
+
246
+ // Some bit-manipulation functions.
247
+ class Bits {
248
+ public:
249
+ // Return floor(log2(n)) for positive integer n.
250
+ static int Log2FloorNonZero(uint32_t n);
251
+
252
+ // Return floor(log2(n)) for positive integer n. Returns -1 iff n == 0.
253
+ static int Log2Floor(uint32_t n);
254
+
255
+ // Return the first set least / most significant bit, 0-indexed. Returns an
256
+ // undefined value if n == 0. FindLSBSetNonZero() is similar to ffs() except
257
+ // that it's 0-indexed.
258
+ static int FindLSBSetNonZero(uint32_t n);
259
+
260
+ static int FindLSBSetNonZero64(uint64_t n);
261
+
262
+ private:
263
+ // No copying
264
+ Bits(const Bits&);
265
+ void operator=(const Bits&);
266
+ };
267
+
268
+ #if HAVE_BUILTIN_CTZ
269
+
270
+ inline int Bits::Log2FloorNonZero(uint32_t n) {
271
+ assert(n != 0);
272
+ // (31 ^ x) is equivalent to (31 - x) for x in [0, 31]. An easy proof
273
+ // represents subtraction in base 2 and observes that there's no carry.
274
+ //
275
+ // GCC and Clang represent __builtin_clz on x86 as 31 ^ _bit_scan_reverse(x).
276
+ // Using "31 ^" here instead of "31 -" allows the optimizer to strip the
277
+ // function body down to _bit_scan_reverse(x).
278
+ return 31 ^ __builtin_clz(n);
279
+ }
280
+
281
+ inline int Bits::Log2Floor(uint32_t n) {
282
+ return (n == 0) ? -1 : Bits::Log2FloorNonZero(n);
283
+ }
284
+
285
+ inline int Bits::FindLSBSetNonZero(uint32_t n) {
286
+ assert(n != 0);
287
+ return __builtin_ctz(n);
288
+ }
289
+
290
+ #elif defined(_MSC_VER)
291
+
292
+ inline int Bits::Log2FloorNonZero(uint32_t n) {
293
+ assert(n != 0);
294
+ // NOLINTNEXTLINE(runtime/int): The MSVC intrinsic demands unsigned long.
295
+ unsigned long where;
296
+ _BitScanReverse(&where, n);
297
+ return static_cast<int>(where);
298
+ }
299
+
300
+ inline int Bits::Log2Floor(uint32_t n) {
301
+ // NOLINTNEXTLINE(runtime/int): The MSVC intrinsic demands unsigned long.
302
+ unsigned long where;
303
+ if (_BitScanReverse(&where, n))
304
+ return static_cast<int>(where);
305
+ return -1;
306
+ }
307
+
308
+ inline int Bits::FindLSBSetNonZero(uint32_t n) {
309
+ assert(n != 0);
310
+ // NOLINTNEXTLINE(runtime/int): The MSVC intrinsic demands unsigned long.
311
+ unsigned long where;
312
+ if (_BitScanForward(&where, n))
313
+ return static_cast<int>(where);
314
+ return 32;
315
+ }
316
+
317
+ #else // Portable versions.
318
+
319
+ inline int Bits::Log2FloorNonZero(uint32_t n) {
320
+ assert(n != 0);
321
+
322
+ int log = 0;
323
+ uint32_t value = n;
324
+ for (int i = 4; i >= 0; --i) {
325
+ int shift = (1 << i);
326
+ uint32_t x = value >> shift;
327
+ if (x != 0) {
328
+ value = x;
329
+ log += shift;
330
+ }
331
+ }
332
+ assert(value == 1);
333
+ return log;
334
+ }
335
+
336
+ inline int Bits::Log2Floor(uint32_t n) {
337
+ return (n == 0) ? -1 : Bits::Log2FloorNonZero(n);
338
+ }
339
+
340
+ inline int Bits::FindLSBSetNonZero(uint32_t n) {
341
+ assert(n != 0);
342
+
343
+ int rc = 31;
344
+ for (int i = 4, shift = 1 << 4; i >= 0; --i) {
345
+ const uint32_t x = n << shift;
346
+ if (x != 0) {
347
+ n = x;
348
+ rc -= shift;
349
+ }
350
+ shift >>= 1;
351
+ }
352
+ return rc;
353
+ }
354
+
355
+ #endif // End portable versions.
356
+
357
+ #if HAVE_BUILTIN_CTZ
358
+
359
+ inline int Bits::FindLSBSetNonZero64(uint64_t n) {
360
+ assert(n != 0);
361
+ return __builtin_ctzll(n);
362
+ }
363
+
364
+ #elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64))
365
+ // _BitScanForward64() is only available on x64 and ARM64.
366
+
367
+ inline int Bits::FindLSBSetNonZero64(uint64_t n) {
368
+ assert(n != 0);
369
+ // NOLINTNEXTLINE(runtime/int): The MSVC intrinsic demands unsigned long.
370
+ unsigned long where;
371
+ if (_BitScanForward64(&where, n))
372
+ return static_cast<int>(where);
373
+ return 64;
374
+ }
375
+
376
+ #else // Portable version.
377
+
378
+ // FindLSBSetNonZero64() is defined in terms of FindLSBSetNonZero().
379
+ inline int Bits::FindLSBSetNonZero64(uint64_t n) {
380
+ assert(n != 0);
381
+
382
+ const uint32_t bottombits = static_cast<uint32_t>(n);
383
+ if (bottombits == 0) {
384
+ // Bottom bits are zero, so scan the top bits.
385
+ return 32 + FindLSBSetNonZero(static_cast<uint32_t>(n >> 32));
386
+ } else {
387
+ return FindLSBSetNonZero(bottombits);
388
+ }
389
+ }
390
+
391
+ #endif // HAVE_BUILTIN_CTZ
392
+
393
+ // Variable-length integer encoding.
394
+ class Varint {
395
+ public:
396
+ // Maximum lengths of varint encoding of uint32_t.
397
+ static const int kMax32 = 5;
398
+
399
+ // Attempts to parse a varint32 from a prefix of the bytes in [ptr,limit-1].
400
+ // Never reads a character at or beyond limit. If a valid/terminated varint32
401
+ // was found in the range, stores it in *OUTPUT and returns a pointer just
402
+ // past the last byte of the varint32. Else returns NULL. On success,
403
+ // "result <= limit".
404
+ static const char* Parse32WithLimit(const char* ptr, const char* limit,
405
+ uint32_t* OUTPUT);
406
+
407
+ // REQUIRES "ptr" points to a buffer of length sufficient to hold "v".
408
+ // EFFECTS Encodes "v" into "ptr" and returns a pointer to the
409
+ // byte just past the last encoded byte.
410
+ static char* Encode32(char* ptr, uint32_t v);
411
+
412
+ // EFFECTS Appends the varint representation of "value" to "*s".
413
+ static void Append32(std::string* s, uint32_t value);
414
+ };
415
+
416
+ inline const char* Varint::Parse32WithLimit(const char* p,
417
+ const char* l,
418
+ uint32_t* OUTPUT) {
419
+ const unsigned char* ptr = reinterpret_cast<const unsigned char*>(p);
420
+ const unsigned char* limit = reinterpret_cast<const unsigned char*>(l);
421
+ uint32_t b, result;
422
+ if (ptr >= limit) return NULL;
423
+ b = *(ptr++); result = b & 127; if (b < 128) goto done;
424
+ if (ptr >= limit) return NULL;
425
+ b = *(ptr++); result |= (b & 127) << 7; if (b < 128) goto done;
426
+ if (ptr >= limit) return NULL;
427
+ b = *(ptr++); result |= (b & 127) << 14; if (b < 128) goto done;
428
+ if (ptr >= limit) return NULL;
429
+ b = *(ptr++); result |= (b & 127) << 21; if (b < 128) goto done;
430
+ if (ptr >= limit) return NULL;
431
+ b = *(ptr++); result |= (b & 127) << 28; if (b < 16) goto done;
432
+ return NULL; // Value is too long to be a varint32
433
+ done:
434
+ *OUTPUT = result;
435
+ return reinterpret_cast<const char*>(ptr);
436
+ }
437
+
438
+ inline char* Varint::Encode32(char* sptr, uint32_t v) {
439
+ // Operate on characters as unsigneds
440
+ uint8_t* ptr = reinterpret_cast<uint8_t*>(sptr);
441
+ static const uint8_t B = 128;
442
+ if (v < (1 << 7)) {
443
+ *(ptr++) = static_cast<uint8_t>(v);
444
+ } else if (v < (1 << 14)) {
445
+ *(ptr++) = static_cast<uint8_t>(v | B);
446
+ *(ptr++) = static_cast<uint8_t>(v >> 7);
447
+ } else if (v < (1 << 21)) {
448
+ *(ptr++) = static_cast<uint8_t>(v | B);
449
+ *(ptr++) = static_cast<uint8_t>((v >> 7) | B);
450
+ *(ptr++) = static_cast<uint8_t>(v >> 14);
451
+ } else if (v < (1 << 28)) {
452
+ *(ptr++) = static_cast<uint8_t>(v | B);
453
+ *(ptr++) = static_cast<uint8_t>((v >> 7) | B);
454
+ *(ptr++) = static_cast<uint8_t>((v >> 14) | B);
455
+ *(ptr++) = static_cast<uint8_t>(v >> 21);
456
+ } else {
457
+ *(ptr++) = static_cast<uint8_t>(v | B);
458
+ *(ptr++) = static_cast<uint8_t>((v>>7) | B);
459
+ *(ptr++) = static_cast<uint8_t>((v>>14) | B);
460
+ *(ptr++) = static_cast<uint8_t>((v>>21) | B);
461
+ *(ptr++) = static_cast<uint8_t>(v >> 28);
462
+ }
463
+ return reinterpret_cast<char*>(ptr);
464
+ }
465
+
466
+ // If you know the internal layout of the std::string in use, you can
467
+ // replace this function with one that resizes the string without
468
+ // filling the new space with zeros (if applicable) --
469
+ // it will be non-portable but faster.
470
+ inline void STLStringResizeUninitialized(std::string* s, size_t new_size) {
471
+ s->resize(new_size);
472
+ }
473
+
474
+ // Return a mutable char* pointing to a string's internal buffer,
475
+ // which may not be null-terminated. Writing through this pointer will
476
+ // modify the string.
477
+ //
478
+ // string_as_array(&str)[i] is valid for 0 <= i < str.size() until the
479
+ // next call to a string method that invalidates iterators.
480
+ //
481
+ // As of 2006-04, there is no standard-blessed way of getting a
482
+ // mutable reference to a string's internal buffer. However, issue 530
483
+ // (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-defects.html#530)
484
+ // proposes this as the method. It will officially be part of the standard
485
+ // for C++0x. This should already work on all current implementations.
486
+ inline char* string_as_array(std::string* str) {
487
+ return str->empty() ? NULL : &*str->begin();
488
+ }
489
+
490
+ } // namespace snappy
491
+
492
+ #endif // THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_
deps/exla/cache/xla_extension/include/external/snappy/snappy-stubs-public.h ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 Google Inc. All Rights Reserved.
2
+ //
3
+ // Redistribution and use in source and binary forms, with or without
4
+ // modification, are permitted provided that the following conditions are
5
+ // met:
6
+ //
7
+ // * Redistributions of source code must retain the above copyright
8
+ // notice, this list of conditions and the following disclaimer.
9
+ // * Redistributions in binary form must reproduce the above
10
+ // copyright notice, this list of conditions and the following disclaimer
11
+ // in the documentation and/or other materials provided with the
12
+ // distribution.
13
+ // * Neither the name of Google Inc. nor the names of its
14
+ // contributors may be used to endorse or promote products derived from
15
+ // this software without specific prior written permission.
16
+ //
17
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+ //
29
+ // Various type stubs for the open-source version of Snappy.
30
+ //
31
+ // This file cannot include config.h, as it is included from snappy.h,
32
+ // which is a public header. Instead, snappy-stubs-public.h is generated by
33
+ // from snappy-stubs-public.h.in at configure time.
34
+
35
+ #ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_PUBLIC_H_
36
+ #define THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_PUBLIC_H_
37
+
38
+ #include <cstddef>
39
+
40
+ #if HAVE_SYS_UIO_H // HAVE_SYS_UIO_H
41
+ #include <sys/uio.h>
42
+ #endif // HAVE_SYS_UIO_H
43
+
44
+ #define SNAPPY_MAJOR ${PROJECT_VERSION_MAJOR}
45
+ #define SNAPPY_MINOR ${PROJECT_VERSION_MINOR}
46
+ #define SNAPPY_PATCHLEVEL ${PROJECT_VERSION_PATCH}
47
+ #define SNAPPY_VERSION \
48
+ ((SNAPPY_MAJOR << 16) | (SNAPPY_MINOR << 8) | SNAPPY_PATCHLEVEL)
49
+
50
+ namespace snappy {
51
+
52
+ #if !HAVE_SYS_UIO_H // !HAVE_SYS_UIO_H
53
+ // Windows does not have an iovec type, yet the concept is universally useful.
54
+ // It is simple to define it ourselves, so we put it inside our own namespace.
55
+ struct iovec {
56
+ void* iov_base;
57
+ size_t iov_len;
58
+ };
59
+ #endif // !HAVE_SYS_UIO_H
60
+
61
+ } // namespace snappy
62
+
63
+ #endif // THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_PUBLIC_H_
deps/exla/cache/xla_extension/include/external/snappy/snappy.h ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2005 and onwards Google Inc.
2
+ //
3
+ // Redistribution and use in source and binary forms, with or without
4
+ // modification, are permitted provided that the following conditions are
5
+ // met:
6
+ //
7
+ // * Redistributions of source code must retain the above copyright
8
+ // notice, this list of conditions and the following disclaimer.
9
+ // * Redistributions in binary form must reproduce the above
10
+ // copyright notice, this list of conditions and the following disclaimer
11
+ // in the documentation and/or other materials provided with the
12
+ // distribution.
13
+ // * Neither the name of Google Inc. nor the names of its
14
+ // contributors may be used to endorse or promote products derived from
15
+ // this software without specific prior written permission.
16
+ //
17
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+ //
29
+ // A light-weight compression algorithm. It is designed for speed of
30
+ // compression and decompression, rather than for the utmost in space
31
+ // savings.
32
+ //
33
+ // For getting better compression ratios when you are compressing data
34
+ // with long repeated sequences or compressing data that is similar to
35
+ // other data, while still compressing fast, you might look at first
36
+ // using BMDiff and then compressing the output of BMDiff with
37
+ // Snappy.
38
+
39
+ #ifndef THIRD_PARTY_SNAPPY_SNAPPY_H__
40
+ #define THIRD_PARTY_SNAPPY_SNAPPY_H__
41
+
42
+ #include <stddef.h>
43
+ #include <stdint.h>
44
+
45
+ #include <string>
46
+
47
+ #include "snappy-stubs-public.h"
48
+
49
+ namespace snappy {
50
+ class Source;
51
+ class Sink;
52
+
53
+ // ------------------------------------------------------------------------
54
+ // Generic compression/decompression routines.
55
+ // ------------------------------------------------------------------------
56
+
57
+ // Compress the bytes read from "*source" and append to "*sink". Return the
58
+ // number of bytes written.
59
+ size_t Compress(Source* source, Sink* sink);
60
+
61
+ // Find the uncompressed length of the given stream, as given by the header.
62
+ // Note that the true length could deviate from this; the stream could e.g.
63
+ // be truncated.
64
+ //
65
+ // Also note that this leaves "*source" in a state that is unsuitable for
66
+ // further operations, such as RawUncompress(). You will need to rewind
67
+ // or recreate the source yourself before attempting any further calls.
68
+ bool GetUncompressedLength(Source* source, uint32_t* result);
69
+
70
+ // ------------------------------------------------------------------------
71
+ // Higher-level string based routines (should be sufficient for most users)
72
+ // ------------------------------------------------------------------------
73
+
74
+ // Sets "*compressed" to the compressed version of "input[0..input_length-1]".
75
+ // Original contents of *compressed are lost.
76
+ //
77
+ // REQUIRES: "input[]" is not an alias of "*compressed".
78
+ size_t Compress(const char* input, size_t input_length,
79
+ std::string* compressed);
80
+
81
+ // Same as `Compress` above but taking an `iovec` array as input. Note that
82
+ // this function preprocesses the inputs to compute the sum of
83
+ // `iov[0..iov_cnt-1].iov_len` before reading. To avoid this, use
84
+ // `RawCompressFromIOVec` below.
85
+ size_t CompressFromIOVec(const struct iovec* iov, size_t iov_cnt,
86
+ std::string* compressed);
87
+
88
+ // Decompresses "compressed[0..compressed_length-1]" to "*uncompressed".
89
+ // Original contents of "*uncompressed" are lost.
90
+ //
91
+ // REQUIRES: "compressed[]" is not an alias of "*uncompressed".
92
+ //
93
+ // returns false if the message is corrupted and could not be decompressed
94
+ bool Uncompress(const char* compressed, size_t compressed_length,
95
+ std::string* uncompressed);
96
+
97
+ // Decompresses "compressed" to "*uncompressed".
98
+ //
99
+ // returns false if the message is corrupted and could not be decompressed
100
+ bool Uncompress(Source* compressed, Sink* uncompressed);
101
+
102
+ // This routine uncompresses as much of the "compressed" as possible
103
+ // into sink. It returns the number of valid bytes added to sink
104
+ // (extra invalid bytes may have been added due to errors; the caller
105
+ // should ignore those). The emitted data typically has length
106
+ // GetUncompressedLength(), but may be shorter if an error is
107
+ // encountered.
108
+ size_t UncompressAsMuchAsPossible(Source* compressed, Sink* uncompressed);
109
+
110
+ // ------------------------------------------------------------------------
111
+ // Lower-level character array based routines. May be useful for
112
+ // efficiency reasons in certain circumstances.
113
+ // ------------------------------------------------------------------------
114
+
115
+ // REQUIRES: "compressed" must point to an area of memory that is at
116
+ // least "MaxCompressedLength(input_length)" bytes in length.
117
+ //
118
+ // Takes the data stored in "input[0..input_length]" and stores
119
+ // it in the array pointed to by "compressed".
120
+ //
121
+ // "*compressed_length" is set to the length of the compressed output.
122
+ //
123
+ // Example:
124
+ // char* output = new char[snappy::MaxCompressedLength(input_length)];
125
+ // size_t output_length;
126
+ // RawCompress(input, input_length, output, &output_length);
127
+ // ... Process(output, output_length) ...
128
+ // delete [] output;
129
+ void RawCompress(const char* input,
130
+ size_t input_length,
131
+ char* compressed,
132
+ size_t* compressed_length);
133
+
134
+ // Same as `RawCompress` above but taking an `iovec` array as input. Note that
135
+ // `uncompressed_length` is the total number of bytes to be read from the
136
+ // elements of `iov` (_not_ the number of elements in `iov`).
137
+ void RawCompressFromIOVec(const struct iovec* iov, size_t uncompressed_length,
138
+ char* compressed, size_t* compressed_length);
139
+
140
+ // Given data in "compressed[0..compressed_length-1]" generated by
141
+ // calling the Snappy::Compress routine, this routine
142
+ // stores the uncompressed data to
143
+ // uncompressed[0..GetUncompressedLength(compressed)-1]
144
+ // returns false if the message is corrupted and could not be decrypted
145
+ bool RawUncompress(const char* compressed, size_t compressed_length,
146
+ char* uncompressed);
147
+
148
+ // Given data from the byte source 'compressed' generated by calling
149
+ // the Snappy::Compress routine, this routine stores the uncompressed
150
+ // data to
151
+ // uncompressed[0..GetUncompressedLength(compressed,compressed_length)-1]
152
+ // returns false if the message is corrupted and could not be decrypted
153
+ bool RawUncompress(Source* compressed, char* uncompressed);
154
+
155
+ // Given data in "compressed[0..compressed_length-1]" generated by
156
+ // calling the Snappy::Compress routine, this routine
157
+ // stores the uncompressed data to the iovec "iov". The number of physical
158
+ // buffers in "iov" is given by iov_cnt and their cumulative size
159
+ // must be at least GetUncompressedLength(compressed). The individual buffers
160
+ // in "iov" must not overlap with each other.
161
+ //
162
+ // returns false if the message is corrupted and could not be decrypted
163
+ bool RawUncompressToIOVec(const char* compressed, size_t compressed_length,
164
+ const struct iovec* iov, size_t iov_cnt);
165
+
166
+ // Given data from the byte source 'compressed' generated by calling
167
+ // the Snappy::Compress routine, this routine stores the uncompressed
168
+ // data to the iovec "iov". The number of physical
169
+ // buffers in "iov" is given by iov_cnt and their cumulative size
170
+ // must be at least GetUncompressedLength(compressed). The individual buffers
171
+ // in "iov" must not overlap with each other.
172
+ //
173
+ // returns false if the message is corrupted and could not be decrypted
174
+ bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov,
175
+ size_t iov_cnt);
176
+
177
+ // Returns the maximal size of the compressed representation of
178
+ // input data that is "source_bytes" bytes in length;
179
+ size_t MaxCompressedLength(size_t source_bytes);
180
+
181
+ // REQUIRES: "compressed[]" was produced by RawCompress() or Compress()
182
+ // Returns true and stores the length of the uncompressed data in
183
+ // *result normally. Returns false on parsing error.
184
+ // This operation takes O(1) time.
185
+ bool GetUncompressedLength(const char* compressed, size_t compressed_length,
186
+ size_t* result);
187
+
188
+ // Returns true iff the contents of "compressed[]" can be uncompressed
189
+ // successfully. Does not return the uncompressed data. Takes
190
+ // time proportional to compressed_length, but is usually at least
191
+ // a factor of four faster than actual decompression.
192
+ bool IsValidCompressedBuffer(const char* compressed,
193
+ size_t compressed_length);
194
+
195
+ // Returns true iff the contents of "compressed" can be uncompressed
196
+ // successfully. Does not return the uncompressed data. Takes
197
+ // time proportional to *compressed length, but is usually at least
198
+ // a factor of four faster than actual decompression.
199
+ // On success, consumes all of *compressed. On failure, consumes an
200
+ // unspecified prefix of *compressed.
201
+ bool IsValidCompressed(Source* compressed);
202
+
203
+ // The size of a compression block. Note that many parts of the compression
204
+ // code assumes that kBlockSize <= 65536; in particular, the hash table
205
+ // can only store 16-bit offsets, and EmitCopy() also assumes the offset
206
+ // is 65535 bytes or less. Note also that if you change this, it will
207
+ // affect the framing format (see framing_format.txt).
208
+ //
209
+ // Note that there might be older data around that is compressed with larger
210
+ // block sizes, so the decompression code should not rely on the
211
+ // non-existence of long backreferences.
212
+ static constexpr int kBlockLog = 16;
213
+ static constexpr size_t kBlockSize = 1 << kBlockLog;
214
+
215
+ static constexpr int kMinHashTableBits = 8;
216
+ static constexpr size_t kMinHashTableSize = 1 << kMinHashTableBits;
217
+
218
+ static constexpr int kMaxHashTableBits = 14;
219
+ static constexpr size_t kMaxHashTableSize = 1 << kMaxHashTableBits;
220
+ } // end namespace snappy
221
+
222
+ #endif // THIRD_PARTY_SNAPPY_SNAPPY_H__
deps/exla/cache/xla_extension/include/external/zlib/crc32.h ADDED
The diff for this file is too large to render. See raw diff
 
deps/exla/cache/xla_extension/include/external/zlib/deflate.h ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* deflate.h -- internal compression state
2
+ * Copyright (C) 1995-2024 Jean-loup Gailly
3
+ * For conditions of distribution and use, see copyright notice in zlib.h
4
+ */
5
+
6
+ /* WARNING: this file should *not* be used by applications. It is
7
+ part of the implementation of the compression library and is
8
+ subject to change. Applications should only use zlib.h.
9
+ */
10
+
11
+ /* @(#) $Id$ */
12
+
13
+ #ifndef DEFLATE_H
14
+ #define DEFLATE_H
15
+
16
+ #include "zutil.h"
17
+
18
+ /* define NO_GZIP when compiling if you want to disable gzip header and
19
+ trailer creation by deflate(). NO_GZIP would be used to avoid linking in
20
+ the crc code when it is not needed. For shared libraries, gzip encoding
21
+ should be left enabled. */
22
+ #ifndef NO_GZIP
23
+ # define GZIP
24
+ #endif
25
+
26
+ /* define LIT_MEM to slightly increase the speed of deflate (order 1% to 2%) at
27
+ the cost of a larger memory footprint */
28
+ /* #define LIT_MEM */
29
+
30
+ /* ===========================================================================
31
+ * Internal compression state.
32
+ */
33
+
34
+ #define LENGTH_CODES 29
35
+ /* number of length codes, not counting the special END_BLOCK code */
36
+
37
+ #define LITERALS 256
38
+ /* number of literal bytes 0..255 */
39
+
40
+ #define L_CODES (LITERALS+1+LENGTH_CODES)
41
+ /* number of Literal or Length codes, including the END_BLOCK code */
42
+
43
+ #define D_CODES 30
44
+ /* number of distance codes */
45
+
46
+ #define BL_CODES 19
47
+ /* number of codes used to transfer the bit lengths */
48
+
49
+ #define HEAP_SIZE (2*L_CODES+1)
50
+ /* maximum heap size */
51
+
52
+ #define MAX_BITS 15
53
+ /* All codes must not exceed MAX_BITS bits */
54
+
55
+ #define Buf_size 16
56
+ /* size of bit buffer in bi_buf */
57
+
58
+ #define INIT_STATE 42 /* zlib header -> BUSY_STATE */
59
+ #ifdef GZIP
60
+ # define GZIP_STATE 57 /* gzip header -> BUSY_STATE | EXTRA_STATE */
61
+ #endif
62
+ #define EXTRA_STATE 69 /* gzip extra block -> NAME_STATE */
63
+ #define NAME_STATE 73 /* gzip file name -> COMMENT_STATE */
64
+ #define COMMENT_STATE 91 /* gzip comment -> HCRC_STATE */
65
+ #define HCRC_STATE 103 /* gzip header CRC -> BUSY_STATE */
66
+ #define BUSY_STATE 113 /* deflate -> FINISH_STATE */
67
+ #define FINISH_STATE 666 /* stream complete */
68
+ /* Stream status */
69
+
70
+
71
+ /* Data structure describing a single value and its code string. */
72
+ typedef struct ct_data_s {
73
+ union {
74
+ ush freq; /* frequency count */
75
+ ush code; /* bit string */
76
+ } fc;
77
+ union {
78
+ ush dad; /* father node in Huffman tree */
79
+ ush len; /* length of bit string */
80
+ } dl;
81
+ } FAR ct_data;
82
+
83
+ #define Freq fc.freq
84
+ #define Code fc.code
85
+ #define Dad dl.dad
86
+ #define Len dl.len
87
+
88
+ typedef struct static_tree_desc_s static_tree_desc;
89
+
90
+ typedef struct tree_desc_s {
91
+ ct_data *dyn_tree; /* the dynamic tree */
92
+ int max_code; /* largest code with non zero frequency */
93
+ const static_tree_desc *stat_desc; /* the corresponding static tree */
94
+ } FAR tree_desc;
95
+
96
+ typedef ush Pos;
97
+ typedef Pos FAR Posf;
98
+ typedef unsigned IPos;
99
+
100
+ /* A Pos is an index in the character window. We use short instead of int to
101
+ * save space in the various tables. IPos is used only for parameter passing.
102
+ */
103
+
104
+ typedef struct internal_state {
105
+ z_streamp strm; /* pointer back to this zlib stream */
106
+ int status; /* as the name implies */
107
+ Bytef *pending_buf; /* output still pending */
108
+ ulg pending_buf_size; /* size of pending_buf */
109
+ Bytef *pending_out; /* next pending byte to output to the stream */
110
+ ulg pending; /* nb of bytes in the pending buffer */
111
+ int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
112
+ gz_headerp gzhead; /* gzip header information to write */
113
+ ulg gzindex; /* where in extra, name, or comment */
114
+ Byte method; /* can only be DEFLATED */
115
+ int last_flush; /* value of flush param for previous deflate call */
116
+
117
+ /* used by deflate.c: */
118
+
119
+ uInt w_size; /* LZ77 window size (32K by default) */
120
+ uInt w_bits; /* log2(w_size) (8..16) */
121
+ uInt w_mask; /* w_size - 1 */
122
+
123
+ Bytef *window;
124
+ /* Sliding window. Input bytes are read into the second half of the window,
125
+ * and move to the first half later to keep a dictionary of at least wSize
126
+ * bytes. With this organization, matches are limited to a distance of
127
+ * wSize-MAX_MATCH bytes, but this ensures that IO is always
128
+ * performed with a length multiple of the block size. Also, it limits
129
+ * the window size to 64K, which is quite useful on MSDOS.
130
+ * To do: use the user input buffer as sliding window.
131
+ */
132
+
133
+ ulg window_size;
134
+ /* Actual size of window: 2*wSize, except when the user input buffer
135
+ * is directly used as sliding window.
136
+ */
137
+
138
+ Posf *prev;
139
+ /* Link to older string with same hash index. To limit the size of this
140
+ * array to 64K, this link is maintained only for the last 32K strings.
141
+ * An index in this array is thus a window index modulo 32K.
142
+ */
143
+
144
+ Posf *head; /* Heads of the hash chains or NIL. */
145
+
146
+ uInt ins_h; /* hash index of string to be inserted */
147
+ uInt hash_size; /* number of elements in hash table */
148
+ uInt hash_bits; /* log2(hash_size) */
149
+ uInt hash_mask; /* hash_size-1 */
150
+
151
+ uInt hash_shift;
152
+ /* Number of bits by which ins_h must be shifted at each input
153
+ * step. It must be such that after MIN_MATCH steps, the oldest
154
+ * byte no longer takes part in the hash key, that is:
155
+ * hash_shift * MIN_MATCH >= hash_bits
156
+ */
157
+
158
+ long block_start;
159
+ /* Window position at the beginning of the current output block. Gets
160
+ * negative when the window is moved backwards.
161
+ */
162
+
163
+ uInt match_length; /* length of best match */
164
+ IPos prev_match; /* previous match */
165
+ int match_available; /* set if previous match exists */
166
+ uInt strstart; /* start of string to insert */
167
+ uInt match_start; /* start of matching string */
168
+ uInt lookahead; /* number of valid bytes ahead in window */
169
+
170
+ uInt prev_length;
171
+ /* Length of the best match at previous step. Matches not greater than this
172
+ * are discarded. This is used in the lazy match evaluation.
173
+ */
174
+
175
+ uInt max_chain_length;
176
+ /* To speed up deflation, hash chains are never searched beyond this
177
+ * length. A higher limit improves compression ratio but degrades the
178
+ * speed.
179
+ */
180
+
181
+ uInt max_lazy_match;
182
+ /* Attempt to find a better match only when the current match is strictly
183
+ * smaller than this value. This mechanism is used only for compression
184
+ * levels >= 4.
185
+ */
186
+ # define max_insert_length max_lazy_match
187
+ /* Insert new strings in the hash table only if the match length is not
188
+ * greater than this length. This saves time but degrades compression.
189
+ * max_insert_length is used only for compression levels <= 3.
190
+ */
191
+
192
+ int level; /* compression level (1..9) */
193
+ int strategy; /* favor or force Huffman coding*/
194
+
195
+ uInt good_match;
196
+ /* Use a faster search when the previous match is longer than this */
197
+
198
+ int nice_match; /* Stop searching when current match exceeds this */
199
+
200
+ /* used by trees.c: */
201
+ /* Didn't use ct_data typedef below to suppress compiler warning */
202
+ struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
203
+ struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
204
+ struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
205
+
206
+ struct tree_desc_s l_desc; /* desc. for literal tree */
207
+ struct tree_desc_s d_desc; /* desc. for distance tree */
208
+ struct tree_desc_s bl_desc; /* desc. for bit length tree */
209
+
210
+ ush bl_count[MAX_BITS+1];
211
+ /* number of codes at each bit length for an optimal tree */
212
+
213
+ int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
214
+ int heap_len; /* number of elements in the heap */
215
+ int heap_max; /* element of largest frequency */
216
+ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
217
+ * The same heap array is used to build all trees.
218
+ */
219
+
220
+ uch depth[2*L_CODES+1];
221
+ /* Depth of each subtree used as tie breaker for trees of equal frequency
222
+ */
223
+
224
+ #ifdef LIT_MEM
225
+ # define LIT_BUFS 5
226
+ ushf *d_buf; /* buffer for distances */
227
+ uchf *l_buf; /* buffer for literals/lengths */
228
+ #else
229
+ # define LIT_BUFS 4
230
+ uchf *sym_buf; /* buffer for distances and literals/lengths */
231
+ #endif
232
+
233
+ uInt lit_bufsize;
234
+ /* Size of match buffer for literals/lengths. There are 4 reasons for
235
+ * limiting lit_bufsize to 64K:
236
+ * - frequencies can be kept in 16 bit counters
237
+ * - if compression is not successful for the first block, all input
238
+ * data is still in the window so we can still emit a stored block even
239
+ * when input comes from standard input. (This can also be done for
240
+ * all blocks if lit_bufsize is not greater than 32K.)
241
+ * - if compression is not successful for a file smaller than 64K, we can
242
+ * even emit a stored file instead of a stored block (saving 5 bytes).
243
+ * This is applicable only for zip (not gzip or zlib).
244
+ * - creating new Huffman trees less frequently may not provide fast
245
+ * adaptation to changes in the input data statistics. (Take for
246
+ * example a binary file with poorly compressible code followed by
247
+ * a highly compressible string table.) Smaller buffer sizes give
248
+ * fast adaptation but have of course the overhead of transmitting
249
+ * trees more frequently.
250
+ * - I can't count above 4
251
+ */
252
+
253
+ uInt sym_next; /* running index in symbol buffer */
254
+ uInt sym_end; /* symbol table full when sym_next reaches this */
255
+
256
+ ulg opt_len; /* bit length of current block with optimal trees */
257
+ ulg static_len; /* bit length of current block with static trees */
258
+ uInt matches; /* number of string matches in current block */
259
+ uInt insert; /* bytes at end of window left to insert */
260
+
261
+ #ifdef ZLIB_DEBUG
262
+ ulg compressed_len; /* total bit length of compressed file mod 2^32 */
263
+ ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
264
+ #endif
265
+
266
+ ush bi_buf;
267
+ /* Output buffer. bits are inserted starting at the bottom (least
268
+ * significant bits).
269
+ */
270
+ int bi_valid;
271
+ /* Number of valid bits in bi_buf. All bits above the last valid bit
272
+ * are always zero.
273
+ */
274
+
275
+ ulg high_water;
276
+ /* High water mark offset in window for initialized bytes -- bytes above
277
+ * this are set to zero in order to avoid memory check warnings when
278
+ * longest match routines access bytes past the input. This is then
279
+ * updated to the new high water mark.
280
+ */
281
+
282
+ } FAR deflate_state;
283
+
284
+ /* Output a byte on the stream.
285
+ * IN assertion: there is enough room in pending_buf.
286
+ */
287
+ #define put_byte(s, c) {s->pending_buf[s->pending++] = (Bytef)(c);}
288
+
289
+
290
+ #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
291
+ /* Minimum amount of lookahead, except at the end of the input file.
292
+ * See deflate.c for comments about the MIN_MATCH+1.
293
+ */
294
+
295
+ #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
296
+ /* In order to simplify the code, particularly on 16 bit machines, match
297
+ * distances are limited to MAX_DIST instead of WSIZE.
298
+ */
299
+
300
+ #define WIN_INIT MAX_MATCH
301
+ /* Number of bytes after end of data in window to initialize in order to avoid
302
+ memory checker errors from longest match routines */
303
+
304
+ /* in trees.c */
305
+ void ZLIB_INTERNAL _tr_init(deflate_state *s);
306
+ int ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc);
307
+ void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf,
308
+ ulg stored_len, int last);
309
+ void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s);
310
+ void ZLIB_INTERNAL _tr_align(deflate_state *s);
311
+ void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf,
312
+ ulg stored_len, int last);
313
+
314
+ #define d_code(dist) \
315
+ ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
316
+ /* Mapping from a distance to a distance code. dist is the distance - 1 and
317
+ * must not have side effects. _dist_code[256] and _dist_code[257] are never
318
+ * used.
319
+ */
320
+
321
+ #ifndef ZLIB_DEBUG
322
+ /* Inline versions of _tr_tally for speed: */
323
+
324
+ #if defined(GEN_TREES_H) || !defined(STDC)
325
+ extern uch ZLIB_INTERNAL _length_code[];
326
+ extern uch ZLIB_INTERNAL _dist_code[];
327
+ #else
328
+ extern const uch ZLIB_INTERNAL _length_code[];
329
+ extern const uch ZLIB_INTERNAL _dist_code[];
330
+ #endif
331
+
332
+ #ifdef LIT_MEM
333
+ # define _tr_tally_lit(s, c, flush) \
334
+ { uch cc = (c); \
335
+ s->d_buf[s->sym_next] = 0; \
336
+ s->l_buf[s->sym_next++] = cc; \
337
+ s->dyn_ltree[cc].Freq++; \
338
+ flush = (s->sym_next == s->sym_end); \
339
+ }
340
+ # define _tr_tally_dist(s, distance, length, flush) \
341
+ { uch len = (uch)(length); \
342
+ ush dist = (ush)(distance); \
343
+ s->d_buf[s->sym_next] = dist; \
344
+ s->l_buf[s->sym_next++] = len; \
345
+ dist--; \
346
+ s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
347
+ s->dyn_dtree[d_code(dist)].Freq++; \
348
+ flush = (s->sym_next == s->sym_end); \
349
+ }
350
+ #else
351
+ # define _tr_tally_lit(s, c, flush) \
352
+ { uch cc = (c); \
353
+ s->sym_buf[s->sym_next++] = 0; \
354
+ s->sym_buf[s->sym_next++] = 0; \
355
+ s->sym_buf[s->sym_next++] = cc; \
356
+ s->dyn_ltree[cc].Freq++; \
357
+ flush = (s->sym_next == s->sym_end); \
358
+ }
359
+ # define _tr_tally_dist(s, distance, length, flush) \
360
+ { uch len = (uch)(length); \
361
+ ush dist = (ush)(distance); \
362
+ s->sym_buf[s->sym_next++] = (uch)dist; \
363
+ s->sym_buf[s->sym_next++] = (uch)(dist >> 8); \
364
+ s->sym_buf[s->sym_next++] = len; \
365
+ dist--; \
366
+ s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
367
+ s->dyn_dtree[d_code(dist)].Freq++; \
368
+ flush = (s->sym_next == s->sym_end); \
369
+ }
370
+ #endif
371
+ #else
372
+ # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
373
+ # define _tr_tally_dist(s, distance, length, flush) \
374
+ flush = _tr_tally(s, distance, length)
375
+ #endif
376
+
377
+ #endif /* DEFLATE_H */
deps/exla/cache/xla_extension/include/external/zlib/gzguts.h ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* gzguts.h -- zlib internal header definitions for gz* operations
2
+ * Copyright (C) 2004-2024 Mark Adler
3
+ * For conditions of distribution and use, see copyright notice in zlib.h
4
+ */
5
+
6
+ #ifdef _LARGEFILE64_SOURCE
7
+ # ifndef _LARGEFILE_SOURCE
8
+ # define _LARGEFILE_SOURCE 1
9
+ # endif
10
+ # undef _FILE_OFFSET_BITS
11
+ # undef _TIME_BITS
12
+ #endif
13
+
14
+ #ifdef HAVE_HIDDEN
15
+ # define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
16
+ #else
17
+ # define ZLIB_INTERNAL
18
+ #endif
19
+
20
+ #include <stdio.h>
21
+ #include "zlib.h"
22
+ #ifdef STDC
23
+ # include <string.h>
24
+ # include <stdlib.h>
25
+ # include <limits.h>
26
+ #endif
27
+
28
+ #ifndef _POSIX_SOURCE
29
+ # define _POSIX_SOURCE
30
+ #endif
31
+ #include <fcntl.h>
32
+
33
+ #ifdef _WIN32
34
+ # include <stddef.h>
35
+ #endif
36
+
37
+ #if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32)
38
+ # include <io.h>
39
+ #endif
40
+
41
+ #if defined(_WIN32)
42
+ # define WIDECHAR
43
+ #endif
44
+
45
+ #ifdef WINAPI_FAMILY
46
+ # define open _open
47
+ # define read _read
48
+ # define write _write
49
+ # define close _close
50
+ #endif
51
+
52
+ #ifdef NO_DEFLATE /* for compatibility with old definition */
53
+ # define NO_GZCOMPRESS
54
+ #endif
55
+
56
+ #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
57
+ # ifndef HAVE_VSNPRINTF
58
+ # define HAVE_VSNPRINTF
59
+ # endif
60
+ #endif
61
+
62
+ #if defined(__CYGWIN__)
63
+ # ifndef HAVE_VSNPRINTF
64
+ # define HAVE_VSNPRINTF
65
+ # endif
66
+ #endif
67
+
68
+ #if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410)
69
+ # ifndef HAVE_VSNPRINTF
70
+ # define HAVE_VSNPRINTF
71
+ # endif
72
+ #endif
73
+
74
+ #ifndef HAVE_VSNPRINTF
75
+ # ifdef MSDOS
76
+ /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
77
+ but for now we just assume it doesn't. */
78
+ # define NO_vsnprintf
79
+ # endif
80
+ # ifdef __TURBOC__
81
+ # define NO_vsnprintf
82
+ # endif
83
+ # ifdef WIN32
84
+ /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
85
+ # if !defined(vsnprintf) && !defined(NO_vsnprintf)
86
+ # if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )
87
+ # define vsnprintf _vsnprintf
88
+ # endif
89
+ # endif
90
+ # endif
91
+ # ifdef __SASC
92
+ # define NO_vsnprintf
93
+ # endif
94
+ # ifdef VMS
95
+ # define NO_vsnprintf
96
+ # endif
97
+ # ifdef __OS400__
98
+ # define NO_vsnprintf
99
+ # endif
100
+ # ifdef __MVS__
101
+ # define NO_vsnprintf
102
+ # endif
103
+ #endif
104
+
105
+ /* unlike snprintf (which is required in C99), _snprintf does not guarantee
106
+ null termination of the result -- however this is only used in gzlib.c where
107
+ the result is assured to fit in the space provided */
108
+ #if defined(_MSC_VER) && _MSC_VER < 1900
109
+ # define snprintf _snprintf
110
+ #endif
111
+
112
+ #ifndef local
113
+ # define local static
114
+ #endif
115
+ /* since "static" is used to mean two completely different things in C, we
116
+ define "local" for the non-static meaning of "static", for readability
117
+ (compile with -Dlocal if your debugger can't find static symbols) */
118
+
119
+ /* gz* functions always use library allocation functions */
120
+ #ifndef STDC
121
+ extern voidp malloc(uInt size);
122
+ extern void free(voidpf ptr);
123
+ #endif
124
+
125
+ /* get errno and strerror definition */
126
+ #if defined UNDER_CE
127
+ # include <windows.h>
128
+ # define zstrerror() gz_strwinerror((DWORD)GetLastError())
129
+ #else
130
+ # ifndef NO_STRERROR
131
+ # include <errno.h>
132
+ # define zstrerror() strerror(errno)
133
+ # else
134
+ # define zstrerror() "stdio error (consult errno)"
135
+ # endif
136
+ #endif
137
+
138
+ /* provide prototypes for these when building zlib without LFS */
139
+ #if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0
140
+ ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *);
141
+ ZEXTERN z_off64_t ZEXPORT gzseek64(gzFile, z_off64_t, int);
142
+ ZEXTERN z_off64_t ZEXPORT gztell64(gzFile);
143
+ ZEXTERN z_off64_t ZEXPORT gzoffset64(gzFile);
144
+ #endif
145
+
146
+ /* default memLevel */
147
+ #if MAX_MEM_LEVEL >= 8
148
+ # define DEF_MEM_LEVEL 8
149
+ #else
150
+ # define DEF_MEM_LEVEL MAX_MEM_LEVEL
151
+ #endif
152
+
153
+ /* default i/o buffer size -- double this for output when reading (this and
154
+ twice this must be able to fit in an unsigned type) */
155
+ #define GZBUFSIZE 8192
156
+
157
+ /* gzip modes, also provide a little integrity check on the passed structure */
158
+ #define GZ_NONE 0
159
+ #define GZ_READ 7247
160
+ #define GZ_WRITE 31153
161
+ #define GZ_APPEND 1 /* mode set to GZ_WRITE after the file is opened */
162
+
163
+ /* values for gz_state how */
164
+ #define LOOK 0 /* look for a gzip header */
165
+ #define COPY 1 /* copy input directly */
166
+ #define GZIP 2 /* decompress a gzip stream */
167
+
168
+ /* internal gzip file state data structure */
169
+ typedef struct {
170
+ /* exposed contents for gzgetc() macro */
171
+ struct gzFile_s x; /* "x" for exposed */
172
+ /* x.have: number of bytes available at x.next */
173
+ /* x.next: next output data to deliver or write */
174
+ /* x.pos: current position in uncompressed data */
175
+ /* used for both reading and writing */
176
+ int mode; /* see gzip modes above */
177
+ int fd; /* file descriptor */
178
+ char *path; /* path or fd for error messages */
179
+ unsigned size; /* buffer size, zero if not allocated yet */
180
+ unsigned want; /* requested buffer size, default is GZBUFSIZE */
181
+ unsigned char *in; /* input buffer (double-sized when writing) */
182
+ unsigned char *out; /* output buffer (double-sized when reading) */
183
+ int direct; /* 0 if processing gzip, 1 if transparent */
184
+ /* just for reading */
185
+ int how; /* 0: get header, 1: copy, 2: decompress */
186
+ z_off64_t start; /* where the gzip data started, for rewinding */
187
+ int eof; /* true if end of input file reached */
188
+ int past; /* true if read requested past end */
189
+ /* just for writing */
190
+ int level; /* compression level */
191
+ int strategy; /* compression strategy */
192
+ int reset; /* true if a reset is pending after a Z_FINISH */
193
+ /* seek request */
194
+ z_off64_t skip; /* amount to skip (already rewound if backwards) */
195
+ int seek; /* true if seek request pending */
196
+ /* error information */
197
+ int err; /* error code */
198
+ char *msg; /* error message */
199
+ /* zlib inflate or deflate stream */
200
+ z_stream strm; /* stream structure in-place (not a pointer) */
201
+ } gz_state;
202
+ typedef gz_state FAR *gz_statep;
203
+
204
+ /* shared functions */
205
+ void ZLIB_INTERNAL gz_error(gz_statep, int, const char *);
206
+ #if defined UNDER_CE
207
+ char ZLIB_INTERNAL *gz_strwinerror(DWORD error);
208
+ #endif
209
+
210
+ /* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t
211
+ value -- needed when comparing unsigned to z_off64_t, which is signed
212
+ (possible z_off64_t types off_t, off64_t, and long are all signed) */
213
+ unsigned ZLIB_INTERNAL gz_intmax(void);
214
+ #define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax())
deps/exla/cache/xla_extension/include/external/zlib/inffast.h ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* inffast.h -- header to use inffast.c
2
+ * Copyright (C) 1995-2003, 2010 Mark Adler
3
+ * For conditions of distribution and use, see copyright notice in zlib.h
4
+ */
5
+
6
+ /* WARNING: this file should *not* be used by applications. It is
7
+ part of the implementation of the compression library and is
8
+ subject to change. Applications should only use zlib.h.
9
+ */
10
+
11
+ void ZLIB_INTERNAL inflate_fast(z_streamp strm, unsigned start);
deps/exla/cache/xla_extension/include/external/zlib/inffixed.h ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* inffixed.h -- table for decoding fixed codes
2
+ * Generated automatically by makefixed().
3
+ */
4
+
5
+ /* WARNING: this file should *not* be used by applications.
6
+ It is part of the implementation of this library and is
7
+ subject to change. Applications should only use zlib.h.
8
+ */
9
+
10
+ static const code lenfix[512] = {
11
+ {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
12
+ {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
13
+ {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
14
+ {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
15
+ {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
16
+ {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
17
+ {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
18
+ {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
19
+ {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
20
+ {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
21
+ {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
22
+ {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
23
+ {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
24
+ {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
25
+ {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
26
+ {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
27
+ {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
28
+ {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
29
+ {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
30
+ {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
31
+ {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
32
+ {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
33
+ {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
34
+ {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
35
+ {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
36
+ {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
37
+ {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
38
+ {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
39
+ {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
40
+ {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
41
+ {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
42
+ {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
43
+ {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
44
+ {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
45
+ {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
46
+ {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
47
+ {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
48
+ {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
49
+ {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
50
+ {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
51
+ {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
52
+ {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
53
+ {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
54
+ {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
55
+ {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
56
+ {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
57
+ {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
58
+ {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
59
+ {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
60
+ {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
61
+ {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
62
+ {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
63
+ {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
64
+ {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
65
+ {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
66
+ {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
67
+ {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
68
+ {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
69
+ {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
70
+ {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
71
+ {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
72
+ {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
73
+ {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
74
+ {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
75
+ {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
76
+ {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
77
+ {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
78
+ {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
79
+ {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
80
+ {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
81
+ {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
82
+ {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
83
+ {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
84
+ {0,9,255}
85
+ };
86
+
87
+ static const code distfix[32] = {
88
+ {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
89
+ {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
90
+ {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
91
+ {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
92
+ {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
93
+ {22,5,193},{64,5,0}
94
+ };
deps/exla/cache/xla_extension/include/external/zlib/inflate.h ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* inflate.h -- internal inflate state definition
2
+ * Copyright (C) 1995-2019 Mark Adler
3
+ * For conditions of distribution and use, see copyright notice in zlib.h
4
+ */
5
+
6
+ /* WARNING: this file should *not* be used by applications. It is
7
+ part of the implementation of the compression library and is
8
+ subject to change. Applications should only use zlib.h.
9
+ */
10
+
11
+ /* define NO_GZIP when compiling if you want to disable gzip header and
12
+ trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
13
+ the crc code when it is not needed. For shared libraries, gzip decoding
14
+ should be left enabled. */
15
+ #ifndef NO_GZIP
16
+ # define GUNZIP
17
+ #endif
18
+
19
+ /* Possible inflate modes between inflate() calls */
20
+ typedef enum {
21
+ HEAD = 16180, /* i: waiting for magic header */
22
+ FLAGS, /* i: waiting for method and flags (gzip) */
23
+ TIME, /* i: waiting for modification time (gzip) */
24
+ OS, /* i: waiting for extra flags and operating system (gzip) */
25
+ EXLEN, /* i: waiting for extra length (gzip) */
26
+ EXTRA, /* i: waiting for extra bytes (gzip) */
27
+ NAME, /* i: waiting for end of file name (gzip) */
28
+ COMMENT, /* i: waiting for end of comment (gzip) */
29
+ HCRC, /* i: waiting for header crc (gzip) */
30
+ DICTID, /* i: waiting for dictionary check value */
31
+ DICT, /* waiting for inflateSetDictionary() call */
32
+ TYPE, /* i: waiting for type bits, including last-flag bit */
33
+ TYPEDO, /* i: same, but skip check to exit inflate on new block */
34
+ STORED, /* i: waiting for stored size (length and complement) */
35
+ COPY_, /* i/o: same as COPY below, but only first time in */
36
+ COPY, /* i/o: waiting for input or output to copy stored block */
37
+ TABLE, /* i: waiting for dynamic block table lengths */
38
+ LENLENS, /* i: waiting for code length code lengths */
39
+ CODELENS, /* i: waiting for length/lit and distance code lengths */
40
+ LEN_, /* i: same as LEN below, but only first time in */
41
+ LEN, /* i: waiting for length/lit/eob code */
42
+ LENEXT, /* i: waiting for length extra bits */
43
+ DIST, /* i: waiting for distance code */
44
+ DISTEXT, /* i: waiting for distance extra bits */
45
+ MATCH, /* o: waiting for output space to copy string */
46
+ LIT, /* o: waiting for output space to write literal */
47
+ CHECK, /* i: waiting for 32-bit check value */
48
+ LENGTH, /* i: waiting for 32-bit length (gzip) */
49
+ DONE, /* finished check, done -- remain here until reset */
50
+ BAD, /* got a data error -- remain here until reset */
51
+ MEM, /* got an inflate() memory error -- remain here until reset */
52
+ SYNC /* looking for synchronization bytes to restart inflate() */
53
+ } inflate_mode;
54
+
55
+ /*
56
+ State transitions between above modes -
57
+
58
+ (most modes can go to BAD or MEM on error -- not shown for clarity)
59
+
60
+ Process header:
61
+ HEAD -> (gzip) or (zlib) or (raw)
62
+ (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
63
+ HCRC -> TYPE
64
+ (zlib) -> DICTID or TYPE
65
+ DICTID -> DICT -> TYPE
66
+ (raw) -> TYPEDO
67
+ Read deflate blocks:
68
+ TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
69
+ STORED -> COPY_ -> COPY -> TYPE
70
+ TABLE -> LENLENS -> CODELENS -> LEN_
71
+ LEN_ -> LEN
72
+ Read deflate codes in fixed or dynamic block:
73
+ LEN -> LENEXT or LIT or TYPE
74
+ LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
75
+ LIT -> LEN
76
+ Process trailer:
77
+ CHECK -> LENGTH -> DONE
78
+ */
79
+
80
+ /* State maintained between inflate() calls -- approximately 7K bytes, not
81
+ including the allocated sliding window, which is up to 32K bytes. */
82
+ struct inflate_state {
83
+ z_streamp strm; /* pointer back to this zlib stream */
84
+ inflate_mode mode; /* current inflate mode */
85
+ int last; /* true if processing last block */
86
+ int wrap; /* bit 0 true for zlib, bit 1 true for gzip,
87
+ bit 2 true to validate check value */
88
+ int havedict; /* true if dictionary provided */
89
+ int flags; /* gzip header method and flags, 0 if zlib, or
90
+ -1 if raw or no header yet */
91
+ unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
92
+ unsigned long check; /* protected copy of check value */
93
+ unsigned long total; /* protected copy of output count */
94
+ gz_headerp head; /* where to save gzip header information */
95
+ /* sliding window */
96
+ unsigned wbits; /* log base 2 of requested window size */
97
+ unsigned wsize; /* window size or zero if not using window */
98
+ unsigned whave; /* valid bytes in the window */
99
+ unsigned wnext; /* window write index */
100
+ unsigned char FAR *window; /* allocated sliding window, if needed */
101
+ /* bit accumulator */
102
+ unsigned long hold; /* input bit accumulator */
103
+ unsigned bits; /* number of bits in "in" */
104
+ /* for string and stored block copying */
105
+ unsigned length; /* literal or length of data to copy */
106
+ unsigned offset; /* distance back to copy string from */
107
+ /* for table and code decoding */
108
+ unsigned extra; /* extra bits needed */
109
+ /* fixed and dynamic code tables */
110
+ code const FAR *lencode; /* starting table for length/literal codes */
111
+ code const FAR *distcode; /* starting table for distance codes */
112
+ unsigned lenbits; /* index bits for lencode */
113
+ unsigned distbits; /* index bits for distcode */
114
+ /* dynamic table building */
115
+ unsigned ncode; /* number of code length code lengths */
116
+ unsigned nlen; /* number of length code lengths */
117
+ unsigned ndist; /* number of distance code lengths */
118
+ unsigned have; /* number of code lengths in lens[] */
119
+ code FAR *next; /* next available space in codes[] */
120
+ unsigned short lens[320]; /* temporary storage for code lengths */
121
+ unsigned short work[288]; /* work area for code table building */
122
+ code codes[ENOUGH]; /* space for code tables */
123
+ int sane; /* if false, allow invalid distance too far */
124
+ int back; /* bits back of last unprocessed length/lit */
125
+ unsigned was; /* initial length of match */
126
+ };
deps/exla/cache/xla_extension/include/external/zlib/inftrees.h ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* inftrees.h -- header to use inftrees.c
2
+ * Copyright (C) 1995-2005, 2010 Mark Adler
3
+ * For conditions of distribution and use, see copyright notice in zlib.h
4
+ */
5
+
6
+ /* WARNING: this file should *not* be used by applications. It is
7
+ part of the implementation of the compression library and is
8
+ subject to change. Applications should only use zlib.h.
9
+ */
10
+
11
+ /* Structure for decoding tables. Each entry provides either the
12
+ information needed to do the operation requested by the code that
13
+ indexed that table entry, or it provides a pointer to another
14
+ table that indexes more bits of the code. op indicates whether
15
+ the entry is a pointer to another table, a literal, a length or
16
+ distance, an end-of-block, or an invalid code. For a table
17
+ pointer, the low four bits of op is the number of index bits of
18
+ that table. For a length or distance, the low four bits of op
19
+ is the number of extra bits to get after the code. bits is
20
+ the number of bits in this code or part of the code to drop off
21
+ of the bit buffer. val is the actual byte to output in the case
22
+ of a literal, the base length or distance, or the offset from
23
+ the current table to the next table. Each entry is four bytes. */
24
+ typedef struct {
25
+ unsigned char op; /* operation, extra bits, table bits */
26
+ unsigned char bits; /* bits in this part of the code */
27
+ unsigned short val; /* offset in table or code value */
28
+ } code;
29
+
30
+ /* op values as set by inflate_table():
31
+ 00000000 - literal
32
+ 0000tttt - table link, tttt != 0 is the number of table index bits
33
+ 0001eeee - length or distance, eeee is the number of extra bits
34
+ 01100000 - end of block
35
+ 01000000 - invalid code
36
+ */
37
+
38
+ /* Maximum size of the dynamic table. The maximum number of code structures is
39
+ 1444, which is the sum of 852 for literal/length codes and 592 for distance
40
+ codes. These values were found by exhaustive searches using the program
41
+ examples/enough.c found in the zlib distribution. The arguments to that
42
+ program are the number of symbols, the initial root table size, and the
43
+ maximum bit length of a code. "enough 286 9 15" for literal/length codes
44
+ returns 852, and "enough 30 6 15" for distance codes returns 592. The
45
+ initial root table size (9 or 6) is found in the fifth argument of the
46
+ inflate_table() calls in inflate.c and infback.c. If the root table size is
47
+ changed, then these maximum sizes would be need to be recalculated and
48
+ updated. */
49
+ #define ENOUGH_LENS 852
50
+ #define ENOUGH_DISTS 592
51
+ #define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
52
+
53
+ /* Type of code to build for inflate_table() */
54
+ typedef enum {
55
+ CODES,
56
+ LENS,
57
+ DISTS
58
+ } codetype;
59
+
60
+ int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,
61
+ unsigned codes, code FAR * FAR *table,
62
+ unsigned FAR *bits, unsigned short FAR *work);
deps/exla/cache/xla_extension/include/external/zlib/trees.h ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* header created automatically with -DGEN_TREES_H */
2
+
3
+ local const ct_data static_ltree[L_CODES+2] = {
4
+ {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
5
+ {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
6
+ {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
7
+ {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
8
+ {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
9
+ {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
10
+ {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
11
+ {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
12
+ {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
13
+ {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
14
+ {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
15
+ {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
16
+ {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
17
+ {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
18
+ {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
19
+ {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
20
+ {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
21
+ {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
22
+ {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
23
+ {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
24
+ {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
25
+ {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
26
+ {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
27
+ {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
28
+ {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
29
+ {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
30
+ {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
31
+ {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
32
+ {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
33
+ {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
34
+ {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
35
+ {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
36
+ {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
37
+ {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
38
+ {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
39
+ {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
40
+ {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
41
+ {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
42
+ {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
43
+ {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
44
+ {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
45
+ {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
46
+ {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
47
+ {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
48
+ {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
49
+ {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
50
+ {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
51
+ {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
52
+ {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
53
+ {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
54
+ {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
55
+ {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
56
+ {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
57
+ {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
58
+ {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
59
+ {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
60
+ {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
61
+ {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
62
+ };
63
+
64
+ local const ct_data static_dtree[D_CODES] = {
65
+ {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
66
+ {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
67
+ {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
68
+ {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
69
+ {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
70
+ {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
71
+ };
72
+
73
+ const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {
74
+ 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
75
+ 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
76
+ 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
77
+ 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
78
+ 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
79
+ 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
80
+ 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
81
+ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
82
+ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
83
+ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
84
+ 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
85
+ 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
86
+ 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
87
+ 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
88
+ 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
89
+ 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
90
+ 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
91
+ 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
92
+ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
93
+ 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
94
+ 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
95
+ 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
96
+ 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
97
+ 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
98
+ 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
99
+ 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
100
+ };
101
+
102
+ const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {
103
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
104
+ 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
105
+ 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
106
+ 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
107
+ 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
108
+ 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
109
+ 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
110
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
111
+ 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
112
+ 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
113
+ 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
114
+ 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
115
+ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
116
+ };
117
+
118
+ local const int base_length[LENGTH_CODES] = {
119
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
120
+ 64, 80, 96, 112, 128, 160, 192, 224, 0
121
+ };
122
+
123
+ local const int base_dist[D_CODES] = {
124
+ 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
125
+ 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
126
+ 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
127
+ };
128
+
deps/exla/cache/xla_extension/include/external/zlib/zconf.h ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* zconf.h -- configuration of the zlib compression library
2
+ * Copyright (C) 1995-2024 Jean-loup Gailly, Mark Adler
3
+ * For conditions of distribution and use, see copyright notice in zlib.h
4
+ */
5
+
6
+ /* @(#) $Id$ */
7
+
8
+ #ifndef ZCONF_H
9
+ #define ZCONF_H
10
+
11
+ /*
12
+ * If you *really* need a unique prefix for all types and library functions,
13
+ * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
14
+ * Even better than compiling with -DZ_PREFIX would be to use configure to set
15
+ * this permanently in zconf.h using "./configure --zprefix".
16
+ */
17
+ #ifdef Z_PREFIX /* may be set to #if 1 by ./configure */
18
+ # define Z_PREFIX_SET
19
+
20
+ /* all linked symbols and init macros */
21
+ # define _dist_code z__dist_code
22
+ # define _length_code z__length_code
23
+ # define _tr_align z__tr_align
24
+ # define _tr_flush_bits z__tr_flush_bits
25
+ # define _tr_flush_block z__tr_flush_block
26
+ # define _tr_init z__tr_init
27
+ # define _tr_stored_block z__tr_stored_block
28
+ # define _tr_tally z__tr_tally
29
+ # define adler32 z_adler32
30
+ # define adler32_combine z_adler32_combine
31
+ # define adler32_combine64 z_adler32_combine64
32
+ # define adler32_z z_adler32_z
33
+ # ifndef Z_SOLO
34
+ # define compress z_compress
35
+ # define compress2 z_compress2
36
+ # define compressBound z_compressBound
37
+ # endif
38
+ # define crc32 z_crc32
39
+ # define crc32_combine z_crc32_combine
40
+ # define crc32_combine64 z_crc32_combine64
41
+ # define crc32_combine_gen z_crc32_combine_gen
42
+ # define crc32_combine_gen64 z_crc32_combine_gen64
43
+ # define crc32_combine_op z_crc32_combine_op
44
+ # define crc32_z z_crc32_z
45
+ # define deflate z_deflate
46
+ # define deflateBound z_deflateBound
47
+ # define deflateCopy z_deflateCopy
48
+ # define deflateEnd z_deflateEnd
49
+ # define deflateGetDictionary z_deflateGetDictionary
50
+ # define deflateInit z_deflateInit
51
+ # define deflateInit2 z_deflateInit2
52
+ # define deflateInit2_ z_deflateInit2_
53
+ # define deflateInit_ z_deflateInit_
54
+ # define deflateParams z_deflateParams
55
+ # define deflatePending z_deflatePending
56
+ # define deflatePrime z_deflatePrime
57
+ # define deflateReset z_deflateReset
58
+ # define deflateResetKeep z_deflateResetKeep
59
+ # define deflateSetDictionary z_deflateSetDictionary
60
+ # define deflateSetHeader z_deflateSetHeader
61
+ # define deflateTune z_deflateTune
62
+ # define deflate_copyright z_deflate_copyright
63
+ # define get_crc_table z_get_crc_table
64
+ # ifndef Z_SOLO
65
+ # define gz_error z_gz_error
66
+ # define gz_intmax z_gz_intmax
67
+ # define gz_strwinerror z_gz_strwinerror
68
+ # define gzbuffer z_gzbuffer
69
+ # define gzclearerr z_gzclearerr
70
+ # define gzclose z_gzclose
71
+ # define gzclose_r z_gzclose_r
72
+ # define gzclose_w z_gzclose_w
73
+ # define gzdirect z_gzdirect
74
+ # define gzdopen z_gzdopen
75
+ # define gzeof z_gzeof
76
+ # define gzerror z_gzerror
77
+ # define gzflush z_gzflush
78
+ # define gzfread z_gzfread
79
+ # define gzfwrite z_gzfwrite
80
+ # define gzgetc z_gzgetc
81
+ # define gzgetc_ z_gzgetc_
82
+ # define gzgets z_gzgets
83
+ # define gzoffset z_gzoffset
84
+ # define gzoffset64 z_gzoffset64
85
+ # define gzopen z_gzopen
86
+ # define gzopen64 z_gzopen64
87
+ # ifdef _WIN32
88
+ # define gzopen_w z_gzopen_w
89
+ # endif
90
+ # define gzprintf z_gzprintf
91
+ # define gzputc z_gzputc
92
+ # define gzputs z_gzputs
93
+ # define gzread z_gzread
94
+ # define gzrewind z_gzrewind
95
+ # define gzseek z_gzseek
96
+ # define gzseek64 z_gzseek64
97
+ # define gzsetparams z_gzsetparams
98
+ # define gztell z_gztell
99
+ # define gztell64 z_gztell64
100
+ # define gzungetc z_gzungetc
101
+ # define gzvprintf z_gzvprintf
102
+ # define gzwrite z_gzwrite
103
+ # endif
104
+ # define inflate z_inflate
105
+ # define inflateBack z_inflateBack
106
+ # define inflateBackEnd z_inflateBackEnd
107
+ # define inflateBackInit z_inflateBackInit
108
+ # define inflateBackInit_ z_inflateBackInit_
109
+ # define inflateCodesUsed z_inflateCodesUsed
110
+ # define inflateCopy z_inflateCopy
111
+ # define inflateEnd z_inflateEnd
112
+ # define inflateGetDictionary z_inflateGetDictionary
113
+ # define inflateGetHeader z_inflateGetHeader
114
+ # define inflateInit z_inflateInit
115
+ # define inflateInit2 z_inflateInit2
116
+ # define inflateInit2_ z_inflateInit2_
117
+ # define inflateInit_ z_inflateInit_
118
+ # define inflateMark z_inflateMark
119
+ # define inflatePrime z_inflatePrime
120
+ # define inflateReset z_inflateReset
121
+ # define inflateReset2 z_inflateReset2
122
+ # define inflateResetKeep z_inflateResetKeep
123
+ # define inflateSetDictionary z_inflateSetDictionary
124
+ # define inflateSync z_inflateSync
125
+ # define inflateSyncPoint z_inflateSyncPoint
126
+ # define inflateUndermine z_inflateUndermine
127
+ # define inflateValidate z_inflateValidate
128
+ # define inflate_copyright z_inflate_copyright
129
+ # define inflate_fast z_inflate_fast
130
+ # define inflate_table z_inflate_table
131
+ # ifndef Z_SOLO
132
+ # define uncompress z_uncompress
133
+ # define uncompress2 z_uncompress2
134
+ # endif
135
+ # define zError z_zError
136
+ # ifndef Z_SOLO
137
+ # define zcalloc z_zcalloc
138
+ # define zcfree z_zcfree
139
+ # endif
140
+ # define zlibCompileFlags z_zlibCompileFlags
141
+ # define zlibVersion z_zlibVersion
142
+
143
+ /* all zlib typedefs in zlib.h and zconf.h */
144
+ # define Byte z_Byte
145
+ # define Bytef z_Bytef
146
+ # define alloc_func z_alloc_func
147
+ # define charf z_charf
148
+ # define free_func z_free_func
149
+ # ifndef Z_SOLO
150
+ # define gzFile z_gzFile
151
+ # endif
152
+ # define gz_header z_gz_header
153
+ # define gz_headerp z_gz_headerp
154
+ # define in_func z_in_func
155
+ # define intf z_intf
156
+ # define out_func z_out_func
157
+ # define uInt z_uInt
158
+ # define uIntf z_uIntf
159
+ # define uLong z_uLong
160
+ # define uLongf z_uLongf
161
+ # define voidp z_voidp
162
+ # define voidpc z_voidpc
163
+ # define voidpf z_voidpf
164
+
165
+ /* all zlib structs in zlib.h and zconf.h */
166
+ # define gz_header_s z_gz_header_s
167
+ # define internal_state z_internal_state
168
+
169
+ #endif
170
+
171
+ #if defined(__MSDOS__) && !defined(MSDOS)
172
+ # define MSDOS
173
+ #endif
174
+ #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
175
+ # define OS2
176
+ #endif
177
+ #if defined(_WINDOWS) && !defined(WINDOWS)
178
+ # define WINDOWS
179
+ #endif
180
+ #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
181
+ # ifndef WIN32
182
+ # define WIN32
183
+ # endif
184
+ #endif
185
+ #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
186
+ # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
187
+ # ifndef SYS16BIT
188
+ # define SYS16BIT
189
+ # endif
190
+ # endif
191
+ #endif
192
+
193
+ /*
194
+ * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
195
+ * than 64k bytes at a time (needed on systems with 16-bit int).
196
+ */
197
+ #ifdef SYS16BIT
198
+ # define MAXSEG_64K
199
+ #endif
200
+ #ifdef MSDOS
201
+ # define UNALIGNED_OK
202
+ #endif
203
+
204
+ #ifdef __STDC_VERSION__
205
+ # ifndef STDC
206
+ # define STDC
207
+ # endif
208
+ # if __STDC_VERSION__ >= 199901L
209
+ # ifndef STDC99
210
+ # define STDC99
211
+ # endif
212
+ # endif
213
+ #endif
214
+ #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
215
+ # define STDC
216
+ #endif
217
+ #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
218
+ # define STDC
219
+ #endif
220
+ #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
221
+ # define STDC
222
+ #endif
223
+ #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
224
+ # define STDC
225
+ #endif
226
+
227
+ #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
228
+ # define STDC
229
+ #endif
230
+
231
+ #ifndef STDC
232
+ # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
233
+ # define const /* note: need a more gentle solution here */
234
+ # endif
235
+ #endif
236
+
237
+ #if defined(ZLIB_CONST) && !defined(z_const)
238
+ # define z_const const
239
+ #else
240
+ # define z_const
241
+ #endif
242
+
243
+ #ifdef Z_SOLO
244
+ # ifdef _WIN64
245
+ typedef unsigned long long z_size_t;
246
+ # else
247
+ typedef unsigned long z_size_t;
248
+ # endif
249
+ #else
250
+ # define z_longlong long long
251
+ # if defined(NO_SIZE_T)
252
+ typedef unsigned NO_SIZE_T z_size_t;
253
+ # elif defined(STDC)
254
+ # include <stddef.h>
255
+ typedef size_t z_size_t;
256
+ # else
257
+ typedef unsigned long z_size_t;
258
+ # endif
259
+ # undef z_longlong
260
+ #endif
261
+
262
+ /* Maximum value for memLevel in deflateInit2 */
263
+ #ifndef MAX_MEM_LEVEL
264
+ # ifdef MAXSEG_64K
265
+ # define MAX_MEM_LEVEL 8
266
+ # else
267
+ # define MAX_MEM_LEVEL 9
268
+ # endif
269
+ #endif
270
+
271
+ /* Maximum value for windowBits in deflateInit2 and inflateInit2.
272
+ * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
273
+ * created by gzip. (Files created by minigzip can still be extracted by
274
+ * gzip.)
275
+ */
276
+ #ifndef MAX_WBITS
277
+ # define MAX_WBITS 15 /* 32K LZ77 window */
278
+ #endif
279
+
280
+ /* The memory requirements for deflate are (in bytes):
281
+ (1 << (windowBits+2)) + (1 << (memLevel+9))
282
+ that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
283
+ plus a few kilobytes for small objects. For example, if you want to reduce
284
+ the default memory requirements from 256K to 128K, compile with
285
+ make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
286
+ Of course this will generally degrade compression (there's no free lunch).
287
+
288
+ The memory requirements for inflate are (in bytes) 1 << windowBits
289
+ that is, 32K for windowBits=15 (default value) plus about 7 kilobytes
290
+ for small objects.
291
+ */
292
+
293
+ /* Type declarations */
294
+
295
+ #ifndef OF /* function prototypes */
296
+ # ifdef STDC
297
+ # define OF(args) args
298
+ # else
299
+ # define OF(args) ()
300
+ # endif
301
+ #endif
302
+
303
+ /* The following definitions for FAR are needed only for MSDOS mixed
304
+ * model programming (small or medium model with some far allocations).
305
+ * This was tested only with MSC; for other MSDOS compilers you may have
306
+ * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
307
+ * just define FAR to be empty.
308
+ */
309
+ #ifdef SYS16BIT
310
+ # if defined(M_I86SM) || defined(M_I86MM)
311
+ /* MSC small or medium model */
312
+ # define SMALL_MEDIUM
313
+ # ifdef _MSC_VER
314
+ # define FAR _far
315
+ # else
316
+ # define FAR far
317
+ # endif
318
+ # endif
319
+ # if (defined(__SMALL__) || defined(__MEDIUM__))
320
+ /* Turbo C small or medium model */
321
+ # define SMALL_MEDIUM
322
+ # ifdef __BORLANDC__
323
+ # define FAR _far
324
+ # else
325
+ # define FAR far
326
+ # endif
327
+ # endif
328
+ #endif
329
+
330
+ #if defined(WINDOWS) || defined(WIN32)
331
+ /* If building or using zlib as a DLL, define ZLIB_DLL.
332
+ * This is not mandatory, but it offers a little performance increase.
333
+ */
334
+ # ifdef ZLIB_DLL
335
+ # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
336
+ # ifdef ZLIB_INTERNAL
337
+ # define ZEXTERN extern __declspec(dllexport)
338
+ # else
339
+ # define ZEXTERN extern __declspec(dllimport)
340
+ # endif
341
+ # endif
342
+ # endif /* ZLIB_DLL */
343
+ /* If building or using zlib with the WINAPI/WINAPIV calling convention,
344
+ * define ZLIB_WINAPI.
345
+ * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
346
+ */
347
+ # ifdef ZLIB_WINAPI
348
+ # ifdef FAR
349
+ # undef FAR
350
+ # endif
351
+ # ifndef WIN32_LEAN_AND_MEAN
352
+ # define WIN32_LEAN_AND_MEAN
353
+ # endif
354
+ # include <windows.h>
355
+ /* No need for _export, use ZLIB.DEF instead. */
356
+ /* For complete Windows compatibility, use WINAPI, not __stdcall. */
357
+ # define ZEXPORT WINAPI
358
+ # ifdef WIN32
359
+ # define ZEXPORTVA WINAPIV
360
+ # else
361
+ # define ZEXPORTVA FAR CDECL
362
+ # endif
363
+ # endif
364
+ #endif
365
+
366
+ #if defined (__BEOS__)
367
+ # ifdef ZLIB_DLL
368
+ # ifdef ZLIB_INTERNAL
369
+ # define ZEXPORT __declspec(dllexport)
370
+ # define ZEXPORTVA __declspec(dllexport)
371
+ # else
372
+ # define ZEXPORT __declspec(dllimport)
373
+ # define ZEXPORTVA __declspec(dllimport)
374
+ # endif
375
+ # endif
376
+ #endif
377
+
378
+ #ifndef ZEXTERN
379
+ # define ZEXTERN extern
380
+ #endif
381
+ #ifndef ZEXPORT
382
+ # define ZEXPORT
383
+ #endif
384
+ #ifndef ZEXPORTVA
385
+ # define ZEXPORTVA
386
+ #endif
387
+
388
+ #ifndef FAR
389
+ # define FAR
390
+ #endif
391
+
392
+ #if !defined(__MACTYPES__)
393
+ typedef unsigned char Byte; /* 8 bits */
394
+ #endif
395
+ typedef unsigned int uInt; /* 16 bits or more */
396
+ typedef unsigned long uLong; /* 32 bits or more */
397
+
398
+ #ifdef SMALL_MEDIUM
399
+ /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
400
+ # define Bytef Byte FAR
401
+ #else
402
+ typedef Byte FAR Bytef;
403
+ #endif
404
+ typedef char FAR charf;
405
+ typedef int FAR intf;
406
+ typedef uInt FAR uIntf;
407
+ typedef uLong FAR uLongf;
408
+
409
+ #ifdef STDC
410
+ typedef void const *voidpc;
411
+ typedef void FAR *voidpf;
412
+ typedef void *voidp;
413
+ #else
414
+ typedef Byte const *voidpc;
415
+ typedef Byte FAR *voidpf;
416
+ typedef Byte *voidp;
417
+ #endif
418
+
419
+ #if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC)
420
+ # include <limits.h>
421
+ # if (UINT_MAX == 0xffffffffUL)
422
+ # define Z_U4 unsigned
423
+ # elif (ULONG_MAX == 0xffffffffUL)
424
+ # define Z_U4 unsigned long
425
+ # elif (USHRT_MAX == 0xffffffffUL)
426
+ # define Z_U4 unsigned short
427
+ # endif
428
+ #endif
429
+
430
+ #ifdef Z_U4
431
+ typedef Z_U4 z_crc_t;
432
+ #else
433
+ typedef unsigned long z_crc_t;
434
+ #endif
435
+
436
+ #ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */
437
+ # define Z_HAVE_UNISTD_H
438
+ #endif
439
+
440
+ #ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */
441
+ # define Z_HAVE_STDARG_H
442
+ #endif
443
+
444
+ #ifdef STDC
445
+ # ifndef Z_SOLO
446
+ # include <sys/types.h> /* for off_t */
447
+ # endif
448
+ #endif
449
+
450
+ #if defined(STDC) || defined(Z_HAVE_STDARG_H)
451
+ # ifndef Z_SOLO
452
+ # include <stdarg.h> /* for va_list */
453
+ # endif
454
+ #endif
455
+
456
+ #ifdef _WIN32
457
+ # ifndef Z_SOLO
458
+ # include <stddef.h> /* for wchar_t */
459
+ # endif
460
+ #endif
461
+
462
+ /* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
463
+ * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
464
+ * though the former does not conform to the LFS document), but considering
465
+ * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
466
+ * equivalently requesting no 64-bit operations
467
+ */
468
+ #if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1
469
+ # undef _LARGEFILE64_SOURCE
470
+ #endif
471
+
472
+ #ifndef Z_HAVE_UNISTD_H
473
+ # ifdef __WATCOMC__
474
+ # define Z_HAVE_UNISTD_H
475
+ # endif
476
+ #endif
477
+ #ifndef Z_HAVE_UNISTD_H
478
+ # if defined(_LARGEFILE64_SOURCE) && !defined(_WIN32)
479
+ # define Z_HAVE_UNISTD_H
480
+ # endif
481
+ #endif
482
+ #ifndef Z_SOLO
483
+ # if defined(Z_HAVE_UNISTD_H)
484
+ # include <unistd.h> /* for SEEK_*, off_t, and _LFS64_LARGEFILE */
485
+ # ifdef VMS
486
+ # include <unixio.h> /* for off_t */
487
+ # endif
488
+ # ifndef z_off_t
489
+ # define z_off_t off_t
490
+ # endif
491
+ # endif
492
+ #endif
493
+
494
+ #if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
495
+ # define Z_LFS64
496
+ #endif
497
+
498
+ #if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
499
+ # define Z_LARGE64
500
+ #endif
501
+
502
+ #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64)
503
+ # define Z_WANT64
504
+ #endif
505
+
506
+ #if !defined(SEEK_SET) && !defined(Z_SOLO)
507
+ # define SEEK_SET 0 /* Seek from beginning of file. */
508
+ # define SEEK_CUR 1 /* Seek from current position. */
509
+ # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
510
+ #endif
511
+
512
+ #ifndef z_off_t
513
+ # define z_off_t long
514
+ #endif
515
+
516
+ #if !defined(_WIN32) && defined(Z_LARGE64)
517
+ # define z_off64_t off64_t
518
+ #else
519
+ # if defined(_WIN32) && !defined(__GNUC__)
520
+ # define z_off64_t __int64
521
+ # else
522
+ # define z_off64_t z_off_t
523
+ # endif
524
+ #endif
525
+
526
+ /* MVS linker does not support external names larger than 8 bytes */
527
+ #if defined(__MVS__)
528
+ #pragma map(deflateInit_,"DEIN")
529
+ #pragma map(deflateInit2_,"DEIN2")
530
+ #pragma map(deflateEnd,"DEEND")
531
+ #pragma map(deflateBound,"DEBND")
532
+ #pragma map(inflateInit_,"ININ")
533
+ #pragma map(inflateInit2_,"ININ2")
534
+ #pragma map(inflateEnd,"INEND")
535
+ #pragma map(inflateSync,"INSY")
536
+ #pragma map(inflateSetDictionary,"INSEDI")
537
+ #pragma map(compressBound,"CMBND")
538
+ #pragma map(inflate_table,"INTABL")
539
+ #pragma map(inflate_fast,"INFA")
540
+ #pragma map(inflate_copyright,"INCOPY")
541
+ #endif
542
+
543
+ #endif /* ZCONF_H */
deps/exla/cache/xla_extension/include/external/zlib/zlib.h ADDED
@@ -0,0 +1,1938 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* zlib.h -- interface of the 'zlib' general purpose compression library
2
+ version 1.3.1, January 22nd, 2024
3
+
4
+ Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler
5
+
6
+ This software is provided 'as-is', without any express or implied
7
+ warranty. In no event will the authors be held liable for any damages
8
+ arising from the use of this software.
9
+
10
+ Permission is granted to anyone to use this software for any purpose,
11
+ including commercial applications, and to alter it and redistribute it
12
+ freely, subject to the following restrictions:
13
+
14
+ 1. The origin of this software must not be misrepresented; you must not
15
+ claim that you wrote the original software. If you use this software
16
+ in a product, an acknowledgment in the product documentation would be
17
+ appreciated but is not required.
18
+ 2. Altered source versions must be plainly marked as such, and must not be
19
+ misrepresented as being the original software.
20
+ 3. This notice may not be removed or altered from any source distribution.
21
+
22
+ Jean-loup Gailly Mark Adler
23
+ jloup@gzip.org madler@alumni.caltech.edu
24
+
25
+
26
+ The data format used by the zlib library is described by RFCs (Request for
27
+ Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
28
+ (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
29
+ */
30
+
31
+ #ifndef ZLIB_H
32
+ #define ZLIB_H
33
+
34
+ #include "zconf.h"
35
+
36
+ #ifdef __cplusplus
37
+ extern "C" {
38
+ #endif
39
+
40
+ #define ZLIB_VERSION "1.3.1"
41
+ #define ZLIB_VERNUM 0x1310
42
+ #define ZLIB_VER_MAJOR 1
43
+ #define ZLIB_VER_MINOR 3
44
+ #define ZLIB_VER_REVISION 1
45
+ #define ZLIB_VER_SUBREVISION 0
46
+
47
+ /*
48
+ The 'zlib' compression library provides in-memory compression and
49
+ decompression functions, including integrity checks of the uncompressed data.
50
+ This version of the library supports only one compression method (deflation)
51
+ but other algorithms will be added later and will have the same stream
52
+ interface.
53
+
54
+ Compression can be done in a single step if the buffers are large enough,
55
+ or can be done by repeated calls of the compression function. In the latter
56
+ case, the application must provide more input and/or consume the output
57
+ (providing more output space) before each call.
58
+
59
+ The compressed data format used by default by the in-memory functions is
60
+ the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
61
+ around a deflate stream, which is itself documented in RFC 1951.
62
+
63
+ The library also supports reading and writing files in gzip (.gz) format
64
+ with an interface similar to that of stdio using the functions that start
65
+ with "gz". The gzip format is different from the zlib format. gzip is a
66
+ gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
67
+
68
+ This library can optionally read and write gzip and raw deflate streams in
69
+ memory as well.
70
+
71
+ The zlib format was designed to be compact and fast for use in memory
72
+ and on communications channels. The gzip format was designed for single-
73
+ file compression on file systems, has a larger header than zlib to maintain
74
+ directory information, and uses a different, slower check method than zlib.
75
+
76
+ The library does not install any signal handler. The decoder checks
77
+ the consistency of the compressed data, so the library should never crash
78
+ even in the case of corrupted input.
79
+ */
80
+
81
+ typedef voidpf (*alloc_func)(voidpf opaque, uInt items, uInt size);
82
+ typedef void (*free_func)(voidpf opaque, voidpf address);
83
+
84
+ struct internal_state;
85
+
86
+ typedef struct z_stream_s {
87
+ z_const Bytef *next_in; /* next input byte */
88
+ uInt avail_in; /* number of bytes available at next_in */
89
+ uLong total_in; /* total number of input bytes read so far */
90
+
91
+ Bytef *next_out; /* next output byte will go here */
92
+ uInt avail_out; /* remaining free space at next_out */
93
+ uLong total_out; /* total number of bytes output so far */
94
+
95
+ z_const char *msg; /* last error message, NULL if no error */
96
+ struct internal_state FAR *state; /* not visible by applications */
97
+
98
+ alloc_func zalloc; /* used to allocate the internal state */
99
+ free_func zfree; /* used to free the internal state */
100
+ voidpf opaque; /* private data object passed to zalloc and zfree */
101
+
102
+ int data_type; /* best guess about the data type: binary or text
103
+ for deflate, or the decoding state for inflate */
104
+ uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */
105
+ uLong reserved; /* reserved for future use */
106
+ } z_stream;
107
+
108
+ typedef z_stream FAR *z_streamp;
109
+
110
+ /*
111
+ gzip header information passed to and from zlib routines. See RFC 1952
112
+ for more details on the meanings of these fields.
113
+ */
114
+ typedef struct gz_header_s {
115
+ int text; /* true if compressed data believed to be text */
116
+ uLong time; /* modification time */
117
+ int xflags; /* extra flags (not used when writing a gzip file) */
118
+ int os; /* operating system */
119
+ Bytef *extra; /* pointer to extra field or Z_NULL if none */
120
+ uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
121
+ uInt extra_max; /* space at extra (only when reading header) */
122
+ Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
123
+ uInt name_max; /* space at name (only when reading header) */
124
+ Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
125
+ uInt comm_max; /* space at comment (only when reading header) */
126
+ int hcrc; /* true if there was or will be a header crc */
127
+ int done; /* true when done reading gzip header (not used
128
+ when writing a gzip file) */
129
+ } gz_header;
130
+
131
+ typedef gz_header FAR *gz_headerp;
132
+
133
+ /*
134
+ The application must update next_in and avail_in when avail_in has dropped
135
+ to zero. It must update next_out and avail_out when avail_out has dropped
136
+ to zero. The application must initialize zalloc, zfree and opaque before
137
+ calling the init function. All other fields are set by the compression
138
+ library and must not be updated by the application.
139
+
140
+ The opaque value provided by the application will be passed as the first
141
+ parameter for calls of zalloc and zfree. This can be useful for custom
142
+ memory management. The compression library attaches no meaning to the
143
+ opaque value.
144
+
145
+ zalloc must return Z_NULL if there is not enough memory for the object.
146
+ If zlib is used in a multi-threaded application, zalloc and zfree must be
147
+ thread safe. In that case, zlib is thread-safe. When zalloc and zfree are
148
+ Z_NULL on entry to the initialization function, they are set to internal
149
+ routines that use the standard library functions malloc() and free().
150
+
151
+ On 16-bit systems, the functions zalloc and zfree must be able to allocate
152
+ exactly 65536 bytes, but will not be required to allocate more than this if
153
+ the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers
154
+ returned by zalloc for objects of exactly 65536 bytes *must* have their
155
+ offset normalized to zero. The default allocation function provided by this
156
+ library ensures this (see zutil.c). To reduce memory requirements and avoid
157
+ any allocation of 64K objects, at the expense of compression ratio, compile
158
+ the library with -DMAX_WBITS=14 (see zconf.h).
159
+
160
+ The fields total_in and total_out can be used for statistics or progress
161
+ reports. After compression, total_in holds the total size of the
162
+ uncompressed data and may be saved for use by the decompressor (particularly
163
+ if the decompressor wants to decompress everything in a single step).
164
+ */
165
+
166
+ /* constants */
167
+
168
+ #define Z_NO_FLUSH 0
169
+ #define Z_PARTIAL_FLUSH 1
170
+ #define Z_SYNC_FLUSH 2
171
+ #define Z_FULL_FLUSH 3
172
+ #define Z_FINISH 4
173
+ #define Z_BLOCK 5
174
+ #define Z_TREES 6
175
+ /* Allowed flush values; see deflate() and inflate() below for details */
176
+
177
+ #define Z_OK 0
178
+ #define Z_STREAM_END 1
179
+ #define Z_NEED_DICT 2
180
+ #define Z_ERRNO (-1)
181
+ #define Z_STREAM_ERROR (-2)
182
+ #define Z_DATA_ERROR (-3)
183
+ #define Z_MEM_ERROR (-4)
184
+ #define Z_BUF_ERROR (-5)
185
+ #define Z_VERSION_ERROR (-6)
186
+ /* Return codes for the compression/decompression functions. Negative values
187
+ * are errors, positive values are used for special but normal events.
188
+ */
189
+
190
+ #define Z_NO_COMPRESSION 0
191
+ #define Z_BEST_SPEED 1
192
+ #define Z_BEST_COMPRESSION 9
193
+ #define Z_DEFAULT_COMPRESSION (-1)
194
+ /* compression levels */
195
+
196
+ #define Z_FILTERED 1
197
+ #define Z_HUFFMAN_ONLY 2
198
+ #define Z_RLE 3
199
+ #define Z_FIXED 4
200
+ #define Z_DEFAULT_STRATEGY 0
201
+ /* compression strategy; see deflateInit2() below for details */
202
+
203
+ #define Z_BINARY 0
204
+ #define Z_TEXT 1
205
+ #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
206
+ #define Z_UNKNOWN 2
207
+ /* Possible values of the data_type field for deflate() */
208
+
209
+ #define Z_DEFLATED 8
210
+ /* The deflate compression method (the only one supported in this version) */
211
+
212
+ #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
213
+
214
+ #define zlib_version zlibVersion()
215
+ /* for compatibility with versions < 1.0.2 */
216
+
217
+
218
+ /* basic functions */
219
+
220
+ ZEXTERN const char * ZEXPORT zlibVersion(void);
221
+ /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
222
+ If the first character differs, the library code actually used is not
223
+ compatible with the zlib.h header file used by the application. This check
224
+ is automatically made by deflateInit and inflateInit.
225
+ */
226
+
227
+ /*
228
+ ZEXTERN int ZEXPORT deflateInit(z_streamp strm, int level);
229
+
230
+ Initializes the internal stream state for compression. The fields
231
+ zalloc, zfree and opaque must be initialized before by the caller. If
232
+ zalloc and zfree are set to Z_NULL, deflateInit updates them to use default
233
+ allocation functions. total_in, total_out, adler, and msg are initialized.
234
+
235
+ The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
236
+ 1 gives best speed, 9 gives best compression, 0 gives no compression at all
237
+ (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION
238
+ requests a default compromise between speed and compression (currently
239
+ equivalent to level 6).
240
+
241
+ deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
242
+ memory, Z_STREAM_ERROR if level is not a valid compression level, or
243
+ Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
244
+ with the version assumed by the caller (ZLIB_VERSION). msg is set to null
245
+ if there is no error message. deflateInit does not perform any compression:
246
+ this will be done by deflate().
247
+ */
248
+
249
+
250
+ ZEXTERN int ZEXPORT deflate(z_streamp strm, int flush);
251
+ /*
252
+ deflate compresses as much data as possible, and stops when the input
253
+ buffer becomes empty or the output buffer becomes full. It may introduce
254
+ some output latency (reading input without producing any output) except when
255
+ forced to flush.
256
+
257
+ The detailed semantics are as follows. deflate performs one or both of the
258
+ following actions:
259
+
260
+ - Compress more input starting at next_in and update next_in and avail_in
261
+ accordingly. If not all input can be processed (because there is not
262
+ enough room in the output buffer), next_in and avail_in are updated and
263
+ processing will resume at this point for the next call of deflate().
264
+
265
+ - Generate more output starting at next_out and update next_out and avail_out
266
+ accordingly. This action is forced if the parameter flush is non zero.
267
+ Forcing flush frequently degrades the compression ratio, so this parameter
268
+ should be set only when necessary. Some output may be provided even if
269
+ flush is zero.
270
+
271
+ Before the call of deflate(), the application should ensure that at least
272
+ one of the actions is possible, by providing more input and/or consuming more
273
+ output, and updating avail_in or avail_out accordingly; avail_out should
274
+ never be zero before the call. The application can consume the compressed
275
+ output when it wants, for example when the output buffer is full (avail_out
276
+ == 0), or after each call of deflate(). If deflate returns Z_OK and with
277
+ zero avail_out, it must be called again after making room in the output
278
+ buffer because there might be more output pending. See deflatePending(),
279
+ which can be used if desired to determine whether or not there is more output
280
+ in that case.
281
+
282
+ Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
283
+ decide how much data to accumulate before producing output, in order to
284
+ maximize compression.
285
+
286
+ If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
287
+ flushed to the output buffer and the output is aligned on a byte boundary, so
288
+ that the decompressor can get all input data available so far. (In
289
+ particular avail_in is zero after the call if enough output space has been
290
+ provided before the call.) Flushing may degrade compression for some
291
+ compression algorithms and so it should be used only when necessary. This
292
+ completes the current deflate block and follows it with an empty stored block
293
+ that is three bits plus filler bits to the next byte, followed by four bytes
294
+ (00 00 ff ff).
295
+
296
+ If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
297
+ output buffer, but the output is not aligned to a byte boundary. All of the
298
+ input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
299
+ This completes the current deflate block and follows it with an empty fixed
300
+ codes block that is 10 bits long. This assures that enough bytes are output
301
+ in order for the decompressor to finish the block before the empty fixed
302
+ codes block.
303
+
304
+ If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
305
+ for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
306
+ seven bits of the current block are held to be written as the next byte after
307
+ the next deflate block is completed. In this case, the decompressor may not
308
+ be provided enough bits at this point in order to complete decompression of
309
+ the data provided so far to the compressor. It may need to wait for the next
310
+ block to be emitted. This is for advanced applications that need to control
311
+ the emission of deflate blocks.
312
+
313
+ If flush is set to Z_FULL_FLUSH, all output is flushed as with
314
+ Z_SYNC_FLUSH, and the compression state is reset so that decompression can
315
+ restart from this point if previous compressed data has been damaged or if
316
+ random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
317
+ compression.
318
+
319
+ If deflate returns with avail_out == 0, this function must be called again
320
+ with the same value of the flush parameter and more output space (updated
321
+ avail_out), until the flush is complete (deflate returns with non-zero
322
+ avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
323
+ avail_out is greater than six when the flush marker begins, in order to avoid
324
+ repeated flush markers upon calling deflate() again when avail_out == 0.
325
+
326
+ If the parameter flush is set to Z_FINISH, pending input is processed,
327
+ pending output is flushed and deflate returns with Z_STREAM_END if there was
328
+ enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this
329
+ function must be called again with Z_FINISH and more output space (updated
330
+ avail_out) but no more input data, until it returns with Z_STREAM_END or an
331
+ error. After deflate has returned Z_STREAM_END, the only possible operations
332
+ on the stream are deflateReset or deflateEnd.
333
+
334
+ Z_FINISH can be used in the first deflate call after deflateInit if all the
335
+ compression is to be done in a single step. In order to complete in one
336
+ call, avail_out must be at least the value returned by deflateBound (see
337
+ below). Then deflate is guaranteed to return Z_STREAM_END. If not enough
338
+ output space is provided, deflate will not return Z_STREAM_END, and it must
339
+ be called again as described above.
340
+
341
+ deflate() sets strm->adler to the Adler-32 checksum of all input read
342
+ so far (that is, total_in bytes). If a gzip stream is being generated, then
343
+ strm->adler will be the CRC-32 checksum of the input read so far. (See
344
+ deflateInit2 below.)
345
+
346
+ deflate() may update strm->data_type if it can make a good guess about
347
+ the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is
348
+ considered binary. This field is only for information purposes and does not
349
+ affect the compression algorithm in any manner.
350
+
351
+ deflate() returns Z_OK if some progress has been made (more input
352
+ processed or more output produced), Z_STREAM_END if all input has been
353
+ consumed and all output has been produced (only when flush is set to
354
+ Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
355
+ if next_in or next_out was Z_NULL or the state was inadvertently written over
356
+ by the application), or Z_BUF_ERROR if no progress is possible (for example
357
+ avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and
358
+ deflate() can be called again with more input and more output space to
359
+ continue compressing.
360
+ */
361
+
362
+
363
+ ZEXTERN int ZEXPORT deflateEnd(z_streamp strm);
364
+ /*
365
+ All dynamically allocated data structures for this stream are freed.
366
+ This function discards any unprocessed input and does not flush any pending
367
+ output.
368
+
369
+ deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
370
+ stream state was inconsistent, Z_DATA_ERROR if the stream was freed
371
+ prematurely (some input or output was discarded). In the error case, msg
372
+ may be set but then points to a static string (which must not be
373
+ deallocated).
374
+ */
375
+
376
+
377
+ /*
378
+ ZEXTERN int ZEXPORT inflateInit(z_streamp strm);
379
+
380
+ Initializes the internal stream state for decompression. The fields
381
+ next_in, avail_in, zalloc, zfree and opaque must be initialized before by
382
+ the caller. In the current version of inflate, the provided input is not
383
+ read or consumed. The allocation of a sliding window will be deferred to
384
+ the first call of inflate (if the decompression does not complete on the
385
+ first call). If zalloc and zfree are set to Z_NULL, inflateInit updates
386
+ them to use default allocation functions. total_in, total_out, adler, and
387
+ msg are initialized.
388
+
389
+ inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
390
+ memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
391
+ version assumed by the caller, or Z_STREAM_ERROR if the parameters are
392
+ invalid, such as a null pointer to the structure. msg is set to null if
393
+ there is no error message. inflateInit does not perform any decompression.
394
+ Actual decompression will be done by inflate(). So next_in, and avail_in,
395
+ next_out, and avail_out are unused and unchanged. The current
396
+ implementation of inflateInit() does not process any header information --
397
+ that is deferred until inflate() is called.
398
+ */
399
+
400
+
401
+ ZEXTERN int ZEXPORT inflate(z_streamp strm, int flush);
402
+ /*
403
+ inflate decompresses as much data as possible, and stops when the input
404
+ buffer becomes empty or the output buffer becomes full. It may introduce
405
+ some output latency (reading input without producing any output) except when
406
+ forced to flush.
407
+
408
+ The detailed semantics are as follows. inflate performs one or both of the
409
+ following actions:
410
+
411
+ - Decompress more input starting at next_in and update next_in and avail_in
412
+ accordingly. If not all input can be processed (because there is not
413
+ enough room in the output buffer), then next_in and avail_in are updated
414
+ accordingly, and processing will resume at this point for the next call of
415
+ inflate().
416
+
417
+ - Generate more output starting at next_out and update next_out and avail_out
418
+ accordingly. inflate() provides as much output as possible, until there is
419
+ no more input data or no more space in the output buffer (see below about
420
+ the flush parameter).
421
+
422
+ Before the call of inflate(), the application should ensure that at least
423
+ one of the actions is possible, by providing more input and/or consuming more
424
+ output, and updating the next_* and avail_* values accordingly. If the
425
+ caller of inflate() does not provide both available input and available
426
+ output space, it is possible that there will be no progress made. The
427
+ application can consume the uncompressed output when it wants, for example
428
+ when the output buffer is full (avail_out == 0), or after each call of
429
+ inflate(). If inflate returns Z_OK and with zero avail_out, it must be
430
+ called again after making room in the output buffer because there might be
431
+ more output pending.
432
+
433
+ The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
434
+ Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much
435
+ output as possible to the output buffer. Z_BLOCK requests that inflate()
436
+ stop if and when it gets to the next deflate block boundary. When decoding
437
+ the zlib or gzip format, this will cause inflate() to return immediately
438
+ after the header and before the first block. When doing a raw inflate,
439
+ inflate() will go ahead and process the first block, and will return when it
440
+ gets to the end of that block, or when it runs out of data.
441
+
442
+ The Z_BLOCK option assists in appending to or combining deflate streams.
443
+ To assist in this, on return inflate() always sets strm->data_type to the
444
+ number of unused bits in the last byte taken from strm->next_in, plus 64 if
445
+ inflate() is currently decoding the last block in the deflate stream, plus
446
+ 128 if inflate() returned immediately after decoding an end-of-block code or
447
+ decoding the complete header up to just before the first byte of the deflate
448
+ stream. The end-of-block will not be indicated until all of the uncompressed
449
+ data from that block has been written to strm->next_out. The number of
450
+ unused bits may in general be greater than seven, except when bit 7 of
451
+ data_type is set, in which case the number of unused bits will be less than
452
+ eight. data_type is set as noted here every time inflate() returns for all
453
+ flush options, and so can be used to determine the amount of currently
454
+ consumed input in bits.
455
+
456
+ The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
457
+ end of each deflate block header is reached, before any actual data in that
458
+ block is decoded. This allows the caller to determine the length of the
459
+ deflate block header for later use in random access within a deflate block.
460
+ 256 is added to the value of strm->data_type when inflate() returns
461
+ immediately after reaching the end of the deflate block header.
462
+
463
+ inflate() should normally be called until it returns Z_STREAM_END or an
464
+ error. However if all decompression is to be performed in a single step (a
465
+ single call of inflate), the parameter flush should be set to Z_FINISH. In
466
+ this case all pending input is processed and all pending output is flushed;
467
+ avail_out must be large enough to hold all of the uncompressed data for the
468
+ operation to complete. (The size of the uncompressed data may have been
469
+ saved by the compressor for this purpose.) The use of Z_FINISH is not
470
+ required to perform an inflation in one step. However it may be used to
471
+ inform inflate that a faster approach can be used for the single inflate()
472
+ call. Z_FINISH also informs inflate to not maintain a sliding window if the
473
+ stream completes, which reduces inflate's memory footprint. If the stream
474
+ does not complete, either because not all of the stream is provided or not
475
+ enough output space is provided, then a sliding window will be allocated and
476
+ inflate() can be called again to continue the operation as if Z_NO_FLUSH had
477
+ been used.
478
+
479
+ In this implementation, inflate() always flushes as much output as
480
+ possible to the output buffer, and always uses the faster approach on the
481
+ first call. So the effects of the flush parameter in this implementation are
482
+ on the return value of inflate() as noted below, when inflate() returns early
483
+ when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of
484
+ memory for a sliding window when Z_FINISH is used.
485
+
486
+ If a preset dictionary is needed after this call (see inflateSetDictionary
487
+ below), inflate sets strm->adler to the Adler-32 checksum of the dictionary
488
+ chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
489
+ strm->adler to the Adler-32 checksum of all output produced so far (that is,
490
+ total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
491
+ below. At the end of the stream, inflate() checks that its computed Adler-32
492
+ checksum is equal to that saved by the compressor and returns Z_STREAM_END
493
+ only if the checksum is correct.
494
+
495
+ inflate() can decompress and check either zlib-wrapped or gzip-wrapped
496
+ deflate data. The header type is detected automatically, if requested when
497
+ initializing with inflateInit2(). Any information contained in the gzip
498
+ header is not retained unless inflateGetHeader() is used. When processing
499
+ gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
500
+ produced so far. The CRC-32 is checked against the gzip trailer, as is the
501
+ uncompressed length, modulo 2^32.
502
+
503
+ inflate() returns Z_OK if some progress has been made (more input processed
504
+ or more output produced), Z_STREAM_END if the end of the compressed data has
505
+ been reached and all uncompressed output has been produced, Z_NEED_DICT if a
506
+ preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
507
+ corrupted (input stream not conforming to the zlib format or incorrect check
508
+ value, in which case strm->msg points to a string with a more specific
509
+ error), Z_STREAM_ERROR if the stream structure was inconsistent (for example
510
+ next_in or next_out was Z_NULL, or the state was inadvertently written over
511
+ by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR
512
+ if no progress was possible or if there was not enough room in the output
513
+ buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
514
+ inflate() can be called again with more input and more output space to
515
+ continue decompressing. If Z_DATA_ERROR is returned, the application may
516
+ then call inflateSync() to look for a good compression block if a partial
517
+ recovery of the data is to be attempted.
518
+ */
519
+
520
+
521
+ ZEXTERN int ZEXPORT inflateEnd(z_streamp strm);
522
+ /*
523
+ All dynamically allocated data structures for this stream are freed.
524
+ This function discards any unprocessed input and does not flush any pending
525
+ output.
526
+
527
+ inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state
528
+ was inconsistent.
529
+ */
530
+
531
+
532
+ /* Advanced functions */
533
+
534
+ /*
535
+ The following functions are needed only in some special applications.
536
+ */
537
+
538
+ /*
539
+ ZEXTERN int ZEXPORT deflateInit2(z_streamp strm,
540
+ int level,
541
+ int method,
542
+ int windowBits,
543
+ int memLevel,
544
+ int strategy);
545
+
546
+ This is another version of deflateInit with more compression options. The
547
+ fields zalloc, zfree and opaque must be initialized before by the caller.
548
+
549
+ The method parameter is the compression method. It must be Z_DEFLATED in
550
+ this version of the library.
551
+
552
+ The windowBits parameter is the base two logarithm of the window size
553
+ (the size of the history buffer). It should be in the range 8..15 for this
554
+ version of the library. Larger values of this parameter result in better
555
+ compression at the expense of memory usage. The default value is 15 if
556
+ deflateInit is used instead.
557
+
558
+ For the current implementation of deflate(), a windowBits value of 8 (a
559
+ window size of 256 bytes) is not supported. As a result, a request for 8
560
+ will result in 9 (a 512-byte window). In that case, providing 8 to
561
+ inflateInit2() will result in an error when the zlib header with 9 is
562
+ checked against the initialization of inflate(). The remedy is to not use 8
563
+ with deflateInit2() with this initialization, or at least in that case use 9
564
+ with inflateInit2().
565
+
566
+ windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
567
+ determines the window size. deflate() will then generate raw deflate data
568
+ with no zlib header or trailer, and will not compute a check value.
569
+
570
+ windowBits can also be greater than 15 for optional gzip encoding. Add
571
+ 16 to windowBits to write a simple gzip header and trailer around the
572
+ compressed data instead of a zlib wrapper. The gzip header will have no
573
+ file name, no extra data, no comment, no modification time (set to zero), no
574
+ header crc, and the operating system will be set to the appropriate value,
575
+ if the operating system was determined at compile time. If a gzip stream is
576
+ being written, strm->adler is a CRC-32 instead of an Adler-32.
577
+
578
+ For raw deflate or gzip encoding, a request for a 256-byte window is
579
+ rejected as invalid, since only the zlib header provides a means of
580
+ transmitting the window size to the decompressor.
581
+
582
+ The memLevel parameter specifies how much memory should be allocated
583
+ for the internal compression state. memLevel=1 uses minimum memory but is
584
+ slow and reduces compression ratio; memLevel=9 uses maximum memory for
585
+ optimal speed. The default value is 8. See zconf.h for total memory usage
586
+ as a function of windowBits and memLevel.
587
+
588
+ The strategy parameter is used to tune the compression algorithm. Use the
589
+ value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
590
+ filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
591
+ string match), or Z_RLE to limit match distances to one (run-length
592
+ encoding). Filtered data consists mostly of small values with a somewhat
593
+ random distribution. In this case, the compression algorithm is tuned to
594
+ compress them better. The effect of Z_FILTERED is to force more Huffman
595
+ coding and less string matching; it is somewhat intermediate between
596
+ Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as
597
+ fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The
598
+ strategy parameter only affects the compression ratio but not the
599
+ correctness of the compressed output even if it is not set appropriately.
600
+ Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
601
+ decoder for special applications.
602
+
603
+ deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
604
+ memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
605
+ method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
606
+ incompatible with the version assumed by the caller (ZLIB_VERSION). msg is
607
+ set to null if there is no error message. deflateInit2 does not perform any
608
+ compression: this will be done by deflate().
609
+ */
610
+
611
+ ZEXTERN int ZEXPORT deflateSetDictionary(z_streamp strm,
612
+ const Bytef *dictionary,
613
+ uInt dictLength);
614
+ /*
615
+ Initializes the compression dictionary from the given byte sequence
616
+ without producing any compressed output. When using the zlib format, this
617
+ function must be called immediately after deflateInit, deflateInit2 or
618
+ deflateReset, and before any call of deflate. When doing raw deflate, this
619
+ function must be called either before any call of deflate, or immediately
620
+ after the completion of a deflate block, i.e. after all input has been
621
+ consumed and all output has been delivered when using any of the flush
622
+ options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The
623
+ compressor and decompressor must use exactly the same dictionary (see
624
+ inflateSetDictionary).
625
+
626
+ The dictionary should consist of strings (byte sequences) that are likely
627
+ to be encountered later in the data to be compressed, with the most commonly
628
+ used strings preferably put towards the end of the dictionary. Using a
629
+ dictionary is most useful when the data to be compressed is short and can be
630
+ predicted with good accuracy; the data can then be compressed better than
631
+ with the default empty dictionary.
632
+
633
+ Depending on the size of the compression data structures selected by
634
+ deflateInit or deflateInit2, a part of the dictionary may in effect be
635
+ discarded, for example if the dictionary is larger than the window size
636
+ provided in deflateInit or deflateInit2. Thus the strings most likely to be
637
+ useful should be put at the end of the dictionary, not at the front. In
638
+ addition, the current implementation of deflate will use at most the window
639
+ size minus 262 bytes of the provided dictionary.
640
+
641
+ Upon return of this function, strm->adler is set to the Adler-32 value
642
+ of the dictionary; the decompressor may later use this value to determine
643
+ which dictionary has been used by the compressor. (The Adler-32 value
644
+ applies to the whole dictionary even if only a subset of the dictionary is
645
+ actually used by the compressor.) If a raw deflate was requested, then the
646
+ Adler-32 value is not computed and strm->adler is not set.
647
+
648
+ deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
649
+ parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is
650
+ inconsistent (for example if deflate has already been called for this stream
651
+ or if not at a block boundary for raw deflate). deflateSetDictionary does
652
+ not perform any compression: this will be done by deflate().
653
+ */
654
+
655
+ ZEXTERN int ZEXPORT deflateGetDictionary(z_streamp strm,
656
+ Bytef *dictionary,
657
+ uInt *dictLength);
658
+ /*
659
+ Returns the sliding dictionary being maintained by deflate. dictLength is
660
+ set to the number of bytes in the dictionary, and that many bytes are copied
661
+ to dictionary. dictionary must have enough space, where 32768 bytes is
662
+ always enough. If deflateGetDictionary() is called with dictionary equal to
663
+ Z_NULL, then only the dictionary length is returned, and nothing is copied.
664
+ Similarly, if dictLength is Z_NULL, then it is not set.
665
+
666
+ deflateGetDictionary() may return a length less than the window size, even
667
+ when more than the window size in input has been provided. It may return up
668
+ to 258 bytes less in that case, due to how zlib's implementation of deflate
669
+ manages the sliding window and lookahead for matches, where matches can be
670
+ up to 258 bytes long. If the application needs the last window-size bytes of
671
+ input, then that would need to be saved by the application outside of zlib.
672
+
673
+ deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
674
+ stream state is inconsistent.
675
+ */
676
+
677
+ ZEXTERN int ZEXPORT deflateCopy(z_streamp dest,
678
+ z_streamp source);
679
+ /*
680
+ Sets the destination stream as a complete copy of the source stream.
681
+
682
+ This function can be useful when several compression strategies will be
683
+ tried, for example when there are several ways of pre-processing the input
684
+ data with a filter. The streams that will be discarded should then be freed
685
+ by calling deflateEnd. Note that deflateCopy duplicates the internal
686
+ compression state which can be quite large, so this strategy is slow and can
687
+ consume lots of memory.
688
+
689
+ deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
690
+ enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
691
+ (such as zalloc being Z_NULL). msg is left unchanged in both source and
692
+ destination.
693
+ */
694
+
695
+ ZEXTERN int ZEXPORT deflateReset(z_streamp strm);
696
+ /*
697
+ This function is equivalent to deflateEnd followed by deflateInit, but
698
+ does not free and reallocate the internal compression state. The stream
699
+ will leave the compression level and any other attributes that may have been
700
+ set unchanged. total_in, total_out, adler, and msg are initialized.
701
+
702
+ deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
703
+ stream state was inconsistent (such as zalloc or state being Z_NULL).
704
+ */
705
+
706
+ ZEXTERN int ZEXPORT deflateParams(z_streamp strm,
707
+ int level,
708
+ int strategy);
709
+ /*
710
+ Dynamically update the compression level and compression strategy. The
711
+ interpretation of level and strategy is as in deflateInit2(). This can be
712
+ used to switch between compression and straight copy of the input data, or
713
+ to switch to a different kind of input data requiring a different strategy.
714
+ If the compression approach (which is a function of the level) or the
715
+ strategy is changed, and if there have been any deflate() calls since the
716
+ state was initialized or reset, then the input available so far is
717
+ compressed with the old level and strategy using deflate(strm, Z_BLOCK).
718
+ There are three approaches for the compression levels 0, 1..3, and 4..9
719
+ respectively. The new level and strategy will take effect at the next call
720
+ of deflate().
721
+
722
+ If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does
723
+ not have enough output space to complete, then the parameter change will not
724
+ take effect. In this case, deflateParams() can be called again with the
725
+ same parameters and more output space to try again.
726
+
727
+ In order to assure a change in the parameters on the first try, the
728
+ deflate stream should be flushed using deflate() with Z_BLOCK or other flush
729
+ request until strm.avail_out is not zero, before calling deflateParams().
730
+ Then no more input data should be provided before the deflateParams() call.
731
+ If this is done, the old level and strategy will be applied to the data
732
+ compressed before deflateParams(), and the new level and strategy will be
733
+ applied to the data compressed after deflateParams().
734
+
735
+ deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream
736
+ state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if
737
+ there was not enough output space to complete the compression of the
738
+ available input data before a change in the strategy or approach. Note that
739
+ in the case of a Z_BUF_ERROR, the parameters are not changed. A return
740
+ value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be
741
+ retried with more output space.
742
+ */
743
+
744
+ ZEXTERN int ZEXPORT deflateTune(z_streamp strm,
745
+ int good_length,
746
+ int max_lazy,
747
+ int nice_length,
748
+ int max_chain);
749
+ /*
750
+ Fine tune deflate's internal compression parameters. This should only be
751
+ used by someone who understands the algorithm used by zlib's deflate for
752
+ searching for the best matching string, and even then only by the most
753
+ fanatic optimizer trying to squeeze out the last compressed bit for their
754
+ specific input data. Read the deflate.c source code for the meaning of the
755
+ max_lazy, good_length, nice_length, and max_chain parameters.
756
+
757
+ deflateTune() can be called after deflateInit() or deflateInit2(), and
758
+ returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
759
+ */
760
+
761
+ ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm,
762
+ uLong sourceLen);
763
+ /*
764
+ deflateBound() returns an upper bound on the compressed size after
765
+ deflation of sourceLen bytes. It must be called after deflateInit() or
766
+ deflateInit2(), and after deflateSetHeader(), if used. This would be used
767
+ to allocate an output buffer for deflation in a single pass, and so would be
768
+ called before deflate(). If that first deflate() call is provided the
769
+ sourceLen input bytes, an output buffer allocated to the size returned by
770
+ deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
771
+ to return Z_STREAM_END. Note that it is possible for the compressed size to
772
+ be larger than the value returned by deflateBound() if flush options other
773
+ than Z_FINISH or Z_NO_FLUSH are used.
774
+ */
775
+
776
+ ZEXTERN int ZEXPORT deflatePending(z_streamp strm,
777
+ unsigned *pending,
778
+ int *bits);
779
+ /*
780
+ deflatePending() returns the number of bytes and bits of output that have
781
+ been generated, but not yet provided in the available output. The bytes not
782
+ provided would be due to the available output space having being consumed.
783
+ The number of bits of output not provided are between 0 and 7, where they
784
+ await more bits to join them in order to fill out a full byte. If pending
785
+ or bits are Z_NULL, then those values are not set.
786
+
787
+ deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source
788
+ stream state was inconsistent.
789
+ */
790
+
791
+ ZEXTERN int ZEXPORT deflatePrime(z_streamp strm,
792
+ int bits,
793
+ int value);
794
+ /*
795
+ deflatePrime() inserts bits in the deflate output stream. The intent
796
+ is that this function is used to start off the deflate output with the bits
797
+ leftover from a previous deflate stream when appending to it. As such, this
798
+ function can only be used for raw deflate, and must be used before the first
799
+ deflate() call after a deflateInit2() or deflateReset(). bits must be less
800
+ than or equal to 16, and that many of the least significant bits of value
801
+ will be inserted in the output.
802
+
803
+ deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough
804
+ room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the
805
+ source stream state was inconsistent.
806
+ */
807
+
808
+ ZEXTERN int ZEXPORT deflateSetHeader(z_streamp strm,
809
+ gz_headerp head);
810
+ /*
811
+ deflateSetHeader() provides gzip header information for when a gzip
812
+ stream is requested by deflateInit2(). deflateSetHeader() may be called
813
+ after deflateInit2() or deflateReset() and before the first call of
814
+ deflate(). The text, time, os, extra field, name, and comment information
815
+ in the provided gz_header structure are written to the gzip header (xflag is
816
+ ignored -- the extra flags are set according to the compression level). The
817
+ caller must assure that, if not Z_NULL, name and comment are terminated with
818
+ a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
819
+ available there. If hcrc is true, a gzip header crc is included. Note that
820
+ the current versions of the command-line version of gzip (up through version
821
+ 1.3.x) do not support header crc's, and will report that it is a "multi-part
822
+ gzip file" and give up.
823
+
824
+ If deflateSetHeader is not used, the default gzip header has text false,
825
+ the time set to zero, and os set to the current operating system, with no
826
+ extra, name, or comment fields. The gzip header is returned to the default
827
+ state by deflateReset().
828
+
829
+ deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
830
+ stream state was inconsistent.
831
+ */
832
+
833
+ /*
834
+ ZEXTERN int ZEXPORT inflateInit2(z_streamp strm,
835
+ int windowBits);
836
+
837
+ This is another version of inflateInit with an extra parameter. The
838
+ fields next_in, avail_in, zalloc, zfree and opaque must be initialized
839
+ before by the caller.
840
+
841
+ The windowBits parameter is the base two logarithm of the maximum window
842
+ size (the size of the history buffer). It should be in the range 8..15 for
843
+ this version of the library. The default value is 15 if inflateInit is used
844
+ instead. windowBits must be greater than or equal to the windowBits value
845
+ provided to deflateInit2() while compressing, or it must be equal to 15 if
846
+ deflateInit2() was not used. If a compressed stream with a larger window
847
+ size is given as input, inflate() will return with the error code
848
+ Z_DATA_ERROR instead of trying to allocate a larger window.
849
+
850
+ windowBits can also be zero to request that inflate use the window size in
851
+ the zlib header of the compressed stream.
852
+
853
+ windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
854
+ determines the window size. inflate() will then process raw deflate data,
855
+ not looking for a zlib or gzip header, not generating a check value, and not
856
+ looking for any check values for comparison at the end of the stream. This
857
+ is for use with other formats that use the deflate compressed data format
858
+ such as zip. Those formats provide their own check values. If a custom
859
+ format is developed using the raw deflate format for compressed data, it is
860
+ recommended that a check value such as an Adler-32 or a CRC-32 be applied to
861
+ the uncompressed data as is done in the zlib, gzip, and zip formats. For
862
+ most applications, the zlib format should be used as is. Note that comments
863
+ above on the use in deflateInit2() applies to the magnitude of windowBits.
864
+
865
+ windowBits can also be greater than 15 for optional gzip decoding. Add
866
+ 32 to windowBits to enable zlib and gzip decoding with automatic header
867
+ detection, or add 16 to decode only the gzip format (the zlib format will
868
+ return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a
869
+ CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see
870
+ below), inflate() will *not* automatically decode concatenated gzip members.
871
+ inflate() will return Z_STREAM_END at the end of the gzip member. The state
872
+ would need to be reset to continue decoding a subsequent gzip member. This
873
+ *must* be done if there is more data after a gzip member, in order for the
874
+ decompression to be compliant with the gzip standard (RFC 1952).
875
+
876
+ inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
877
+ memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
878
+ version assumed by the caller, or Z_STREAM_ERROR if the parameters are
879
+ invalid, such as a null pointer to the structure. msg is set to null if
880
+ there is no error message. inflateInit2 does not perform any decompression
881
+ apart from possibly reading the zlib header if present: actual decompression
882
+ will be done by inflate(). (So next_in and avail_in may be modified, but
883
+ next_out and avail_out are unused and unchanged.) The current implementation
884
+ of inflateInit2() does not process any header information -- that is
885
+ deferred until inflate() is called.
886
+ */
887
+
888
+ ZEXTERN int ZEXPORT inflateSetDictionary(z_streamp strm,
889
+ const Bytef *dictionary,
890
+ uInt dictLength);
891
+ /*
892
+ Initializes the decompression dictionary from the given uncompressed byte
893
+ sequence. This function must be called immediately after a call of inflate,
894
+ if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
895
+ can be determined from the Adler-32 value returned by that call of inflate.
896
+ The compressor and decompressor must use exactly the same dictionary (see
897
+ deflateSetDictionary). For raw inflate, this function can be called at any
898
+ time to set the dictionary. If the provided dictionary is smaller than the
899
+ window and there is already data in the window, then the provided dictionary
900
+ will amend what's there. The application must insure that the dictionary
901
+ that was used for compression is provided.
902
+
903
+ inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
904
+ parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is
905
+ inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
906
+ expected one (incorrect Adler-32 value). inflateSetDictionary does not
907
+ perform any decompression: this will be done by subsequent calls of
908
+ inflate().
909
+ */
910
+
911
+ ZEXTERN int ZEXPORT inflateGetDictionary(z_streamp strm,
912
+ Bytef *dictionary,
913
+ uInt *dictLength);
914
+ /*
915
+ Returns the sliding dictionary being maintained by inflate. dictLength is
916
+ set to the number of bytes in the dictionary, and that many bytes are copied
917
+ to dictionary. dictionary must have enough space, where 32768 bytes is
918
+ always enough. If inflateGetDictionary() is called with dictionary equal to
919
+ Z_NULL, then only the dictionary length is returned, and nothing is copied.
920
+ Similarly, if dictLength is Z_NULL, then it is not set.
921
+
922
+ inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
923
+ stream state is inconsistent.
924
+ */
925
+
926
+ ZEXTERN int ZEXPORT inflateSync(z_streamp strm);
927
+ /*
928
+ Skips invalid compressed data until a possible full flush point (see above
929
+ for the description of deflate with Z_FULL_FLUSH) can be found, or until all
930
+ available input is skipped. No output is provided.
931
+
932
+ inflateSync searches for a 00 00 FF FF pattern in the compressed data.
933
+ All full flush points have this pattern, but not all occurrences of this
934
+ pattern are full flush points.
935
+
936
+ inflateSync returns Z_OK if a possible full flush point has been found,
937
+ Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point
938
+ has been found, or Z_STREAM_ERROR if the stream structure was inconsistent.
939
+ In the success case, the application may save the current value of total_in
940
+ which indicates where valid compressed data was found. In the error case,
941
+ the application may repeatedly call inflateSync, providing more input each
942
+ time, until success or end of the input data.
943
+ */
944
+
945
+ ZEXTERN int ZEXPORT inflateCopy(z_streamp dest,
946
+ z_streamp source);
947
+ /*
948
+ Sets the destination stream as a complete copy of the source stream.
949
+
950
+ This function can be useful when randomly accessing a large stream. The
951
+ first pass through the stream can periodically record the inflate state,
952
+ allowing restarting inflate at those points when randomly accessing the
953
+ stream.
954
+
955
+ inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
956
+ enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
957
+ (such as zalloc being Z_NULL). msg is left unchanged in both source and
958
+ destination.
959
+ */
960
+
961
+ ZEXTERN int ZEXPORT inflateReset(z_streamp strm);
962
+ /*
963
+ This function is equivalent to inflateEnd followed by inflateInit,
964
+ but does not free and reallocate the internal decompression state. The
965
+ stream will keep attributes that may have been set by inflateInit2.
966
+ total_in, total_out, adler, and msg are initialized.
967
+
968
+ inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
969
+ stream state was inconsistent (such as zalloc or state being Z_NULL).
970
+ */
971
+
972
+ ZEXTERN int ZEXPORT inflateReset2(z_streamp strm,
973
+ int windowBits);
974
+ /*
975
+ This function is the same as inflateReset, but it also permits changing
976
+ the wrap and window size requests. The windowBits parameter is interpreted
977
+ the same as it is for inflateInit2. If the window size is changed, then the
978
+ memory allocated for the window is freed, and the window will be reallocated
979
+ by inflate() if needed.
980
+
981
+ inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
982
+ stream state was inconsistent (such as zalloc or state being Z_NULL), or if
983
+ the windowBits parameter is invalid.
984
+ */
985
+
986
+ ZEXTERN int ZEXPORT inflatePrime(z_streamp strm,
987
+ int bits,
988
+ int value);
989
+ /*
990
+ This function inserts bits in the inflate input stream. The intent is
991
+ that this function is used to start inflating at a bit position in the
992
+ middle of a byte. The provided bits will be used before any bytes are used
993
+ from next_in. This function should only be used with raw inflate, and
994
+ should be used before the first inflate() call after inflateInit2() or
995
+ inflateReset(). bits must be less than or equal to 16, and that many of the
996
+ least significant bits of value will be inserted in the input.
997
+
998
+ If bits is negative, then the input stream bit buffer is emptied. Then
999
+ inflatePrime() can be called again to put bits in the buffer. This is used
1000
+ to clear out bits leftover after feeding inflate a block description prior
1001
+ to feeding inflate codes.
1002
+
1003
+ inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
1004
+ stream state was inconsistent.
1005
+ */
1006
+
1007
+ ZEXTERN long ZEXPORT inflateMark(z_streamp strm);
1008
+ /*
1009
+ This function returns two values, one in the lower 16 bits of the return
1010
+ value, and the other in the remaining upper bits, obtained by shifting the
1011
+ return value down 16 bits. If the upper value is -1 and the lower value is
1012
+ zero, then inflate() is currently decoding information outside of a block.
1013
+ If the upper value is -1 and the lower value is non-zero, then inflate is in
1014
+ the middle of a stored block, with the lower value equaling the number of
1015
+ bytes from the input remaining to copy. If the upper value is not -1, then
1016
+ it is the number of bits back from the current bit position in the input of
1017
+ the code (literal or length/distance pair) currently being processed. In
1018
+ that case the lower value is the number of bytes already emitted for that
1019
+ code.
1020
+
1021
+ A code is being processed if inflate is waiting for more input to complete
1022
+ decoding of the code, or if it has completed decoding but is waiting for
1023
+ more output space to write the literal or match data.
1024
+
1025
+ inflateMark() is used to mark locations in the input data for random
1026
+ access, which may be at bit positions, and to note those cases where the
1027
+ output of a code may span boundaries of random access blocks. The current
1028
+ location in the input stream can be determined from avail_in and data_type
1029
+ as noted in the description for the Z_BLOCK flush parameter for inflate.
1030
+
1031
+ inflateMark returns the value noted above, or -65536 if the provided
1032
+ source stream state was inconsistent.
1033
+ */
1034
+
1035
+ ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm,
1036
+ gz_headerp head);
1037
+ /*
1038
+ inflateGetHeader() requests that gzip header information be stored in the
1039
+ provided gz_header structure. inflateGetHeader() may be called after
1040
+ inflateInit2() or inflateReset(), and before the first call of inflate().
1041
+ As inflate() processes the gzip stream, head->done is zero until the header
1042
+ is completed, at which time head->done is set to one. If a zlib stream is
1043
+ being decoded, then head->done is set to -1 to indicate that there will be
1044
+ no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be
1045
+ used to force inflate() to return immediately after header processing is
1046
+ complete and before any actual data is decompressed.
1047
+
1048
+ The text, time, xflags, and os fields are filled in with the gzip header
1049
+ contents. hcrc is set to true if there is a header CRC. (The header CRC
1050
+ was valid if done is set to one.) If extra is not Z_NULL, then extra_max
1051
+ contains the maximum number of bytes to write to extra. Once done is true,
1052
+ extra_len contains the actual extra field length, and extra contains the
1053
+ extra field, or that field truncated if extra_max is less than extra_len.
1054
+ If name is not Z_NULL, then up to name_max characters are written there,
1055
+ terminated with a zero unless the length is greater than name_max. If
1056
+ comment is not Z_NULL, then up to comm_max characters are written there,
1057
+ terminated with a zero unless the length is greater than comm_max. When any
1058
+ of extra, name, or comment are not Z_NULL and the respective field is not
1059
+ present in the header, then that field is set to Z_NULL to signal its
1060
+ absence. This allows the use of deflateSetHeader() with the returned
1061
+ structure to duplicate the header. However if those fields are set to
1062
+ allocated memory, then the application will need to save those pointers
1063
+ elsewhere so that they can be eventually freed.
1064
+
1065
+ If inflateGetHeader is not used, then the header information is simply
1066
+ discarded. The header is always checked for validity, including the header
1067
+ CRC if present. inflateReset() will reset the process to discard the header
1068
+ information. The application would need to call inflateGetHeader() again to
1069
+ retrieve the header from the next gzip stream.
1070
+
1071
+ inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
1072
+ stream state was inconsistent.
1073
+ */
1074
+
1075
+ /*
1076
+ ZEXTERN int ZEXPORT inflateBackInit(z_streamp strm, int windowBits,
1077
+ unsigned char FAR *window);
1078
+
1079
+ Initialize the internal stream state for decompression using inflateBack()
1080
+ calls. The fields zalloc, zfree and opaque in strm must be initialized
1081
+ before the call. If zalloc and zfree are Z_NULL, then the default library-
1082
+ derived memory allocation routines are used. windowBits is the base two
1083
+ logarithm of the window size, in the range 8..15. window is a caller
1084
+ supplied buffer of that size. Except for special applications where it is
1085
+ assured that deflate was used with small window sizes, windowBits must be 15
1086
+ and a 32K byte window must be supplied to be able to decompress general
1087
+ deflate streams.
1088
+
1089
+ See inflateBack() for the usage of these routines.
1090
+
1091
+ inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
1092
+ the parameters are invalid, Z_MEM_ERROR if the internal state could not be
1093
+ allocated, or Z_VERSION_ERROR if the version of the library does not match
1094
+ the version of the header file.
1095
+ */
1096
+
1097
+ typedef unsigned (*in_func)(void FAR *,
1098
+ z_const unsigned char FAR * FAR *);
1099
+ typedef int (*out_func)(void FAR *, unsigned char FAR *, unsigned);
1100
+
1101
+ ZEXTERN int ZEXPORT inflateBack(z_streamp strm,
1102
+ in_func in, void FAR *in_desc,
1103
+ out_func out, void FAR *out_desc);
1104
+ /*
1105
+ inflateBack() does a raw inflate with a single call using a call-back
1106
+ interface for input and output. This is potentially more efficient than
1107
+ inflate() for file i/o applications, in that it avoids copying between the
1108
+ output and the sliding window by simply making the window itself the output
1109
+ buffer. inflate() can be faster on modern CPUs when used with large
1110
+ buffers. inflateBack() trusts the application to not change the output
1111
+ buffer passed by the output function, at least until inflateBack() returns.
1112
+
1113
+ inflateBackInit() must be called first to allocate the internal state
1114
+ and to initialize the state with the user-provided window buffer.
1115
+ inflateBack() may then be used multiple times to inflate a complete, raw
1116
+ deflate stream with each call. inflateBackEnd() is then called to free the
1117
+ allocated state.
1118
+
1119
+ A raw deflate stream is one with no zlib or gzip header or trailer.
1120
+ This routine would normally be used in a utility that reads zip or gzip
1121
+ files and writes out uncompressed files. The utility would decode the
1122
+ header and process the trailer on its own, hence this routine expects only
1123
+ the raw deflate stream to decompress. This is different from the default
1124
+ behavior of inflate(), which expects a zlib header and trailer around the
1125
+ deflate stream.
1126
+
1127
+ inflateBack() uses two subroutines supplied by the caller that are then
1128
+ called by inflateBack() for input and output. inflateBack() calls those
1129
+ routines until it reads a complete deflate stream and writes out all of the
1130
+ uncompressed data, or until it encounters an error. The function's
1131
+ parameters and return types are defined above in the in_func and out_func
1132
+ typedefs. inflateBack() will call in(in_desc, &buf) which should return the
1133
+ number of bytes of provided input, and a pointer to that input in buf. If
1134
+ there is no input available, in() must return zero -- buf is ignored in that
1135
+ case -- and inflateBack() will return a buffer error. inflateBack() will
1136
+ call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].
1137
+ out() should return zero on success, or non-zero on failure. If out()
1138
+ returns non-zero, inflateBack() will return with an error. Neither in() nor
1139
+ out() are permitted to change the contents of the window provided to
1140
+ inflateBackInit(), which is also the buffer that out() uses to write from.
1141
+ The length written by out() will be at most the window size. Any non-zero
1142
+ amount of input may be provided by in().
1143
+
1144
+ For convenience, inflateBack() can be provided input on the first call by
1145
+ setting strm->next_in and strm->avail_in. If that input is exhausted, then
1146
+ in() will be called. Therefore strm->next_in must be initialized before
1147
+ calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
1148
+ immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
1149
+ must also be initialized, and then if strm->avail_in is not zero, input will
1150
+ initially be taken from strm->next_in[0 .. strm->avail_in - 1].
1151
+
1152
+ The in_desc and out_desc parameters of inflateBack() is passed as the
1153
+ first parameter of in() and out() respectively when they are called. These
1154
+ descriptors can be optionally used to pass any information that the caller-
1155
+ supplied in() and out() functions need to do their job.
1156
+
1157
+ On return, inflateBack() will set strm->next_in and strm->avail_in to
1158
+ pass back any unused input that was provided by the last in() call. The
1159
+ return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
1160
+ if in() or out() returned an error, Z_DATA_ERROR if there was a format error
1161
+ in the deflate stream (in which case strm->msg is set to indicate the nature
1162
+ of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
1163
+ In the case of Z_BUF_ERROR, an input or output error can be distinguished
1164
+ using strm->next_in which will be Z_NULL only if in() returned an error. If
1165
+ strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
1166
+ non-zero. (in() will always be called before out(), so strm->next_in is
1167
+ assured to be defined if out() returns non-zero.) Note that inflateBack()
1168
+ cannot return Z_OK.
1169
+ */
1170
+
1171
+ ZEXTERN int ZEXPORT inflateBackEnd(z_streamp strm);
1172
+ /*
1173
+ All memory allocated by inflateBackInit() is freed.
1174
+
1175
+ inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
1176
+ state was inconsistent.
1177
+ */
1178
+
1179
+ ZEXTERN uLong ZEXPORT zlibCompileFlags(void);
1180
+ /* Return flags indicating compile-time options.
1181
+
1182
+ Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
1183
+ 1.0: size of uInt
1184
+ 3.2: size of uLong
1185
+ 5.4: size of voidpf (pointer)
1186
+ 7.6: size of z_off_t
1187
+
1188
+ Compiler, assembler, and debug options:
1189
+ 8: ZLIB_DEBUG
1190
+ 9: ASMV or ASMINF -- use ASM code
1191
+ 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
1192
+ 11: 0 (reserved)
1193
+
1194
+ One-time table building (smaller code, but not thread-safe if true):
1195
+ 12: BUILDFIXED -- build static block decoding tables when needed
1196
+ 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
1197
+ 14,15: 0 (reserved)
1198
+
1199
+ Library content (indicates missing functionality):
1200
+ 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
1201
+ deflate code when not needed)
1202
+ 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
1203
+ and decode gzip streams (to avoid linking crc code)
1204
+ 18-19: 0 (reserved)
1205
+
1206
+ Operation variations (changes in library functionality):
1207
+ 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
1208
+ 21: FASTEST -- deflate algorithm with only one, lowest compression level
1209
+ 22,23: 0 (reserved)
1210
+
1211
+ The sprintf variant used by gzprintf (zero is best):
1212
+ 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
1213
+ 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
1214
+ 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
1215
+
1216
+ Remainder:
1217
+ 27-31: 0 (reserved)
1218
+ */
1219
+
1220
+ #ifndef Z_SOLO
1221
+
1222
+ /* utility functions */
1223
+
1224
+ /*
1225
+ The following utility functions are implemented on top of the basic
1226
+ stream-oriented functions. To simplify the interface, some default options
1227
+ are assumed (compression level and memory usage, standard memory allocation
1228
+ functions). The source code of these utility functions can be modified if
1229
+ you need special options.
1230
+ */
1231
+
1232
+ ZEXTERN int ZEXPORT compress(Bytef *dest, uLongf *destLen,
1233
+ const Bytef *source, uLong sourceLen);
1234
+ /*
1235
+ Compresses the source buffer into the destination buffer. sourceLen is
1236
+ the byte length of the source buffer. Upon entry, destLen is the total size
1237
+ of the destination buffer, which must be at least the value returned by
1238
+ compressBound(sourceLen). Upon exit, destLen is the actual size of the
1239
+ compressed data. compress() is equivalent to compress2() with a level
1240
+ parameter of Z_DEFAULT_COMPRESSION.
1241
+
1242
+ compress returns Z_OK if success, Z_MEM_ERROR if there was not
1243
+ enough memory, Z_BUF_ERROR if there was not enough room in the output
1244
+ buffer.
1245
+ */
1246
+
1247
+ ZEXTERN int ZEXPORT compress2(Bytef *dest, uLongf *destLen,
1248
+ const Bytef *source, uLong sourceLen,
1249
+ int level);
1250
+ /*
1251
+ Compresses the source buffer into the destination buffer. The level
1252
+ parameter has the same meaning as in deflateInit. sourceLen is the byte
1253
+ length of the source buffer. Upon entry, destLen is the total size of the
1254
+ destination buffer, which must be at least the value returned by
1255
+ compressBound(sourceLen). Upon exit, destLen is the actual size of the
1256
+ compressed data.
1257
+
1258
+ compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
1259
+ memory, Z_BUF_ERROR if there was not enough room in the output buffer,
1260
+ Z_STREAM_ERROR if the level parameter is invalid.
1261
+ */
1262
+
1263
+ ZEXTERN uLong ZEXPORT compressBound(uLong sourceLen);
1264
+ /*
1265
+ compressBound() returns an upper bound on the compressed size after
1266
+ compress() or compress2() on sourceLen bytes. It would be used before a
1267
+ compress() or compress2() call to allocate the destination buffer.
1268
+ */
1269
+
1270
+ ZEXTERN int ZEXPORT uncompress(Bytef *dest, uLongf *destLen,
1271
+ const Bytef *source, uLong sourceLen);
1272
+ /*
1273
+ Decompresses the source buffer into the destination buffer. sourceLen is
1274
+ the byte length of the source buffer. Upon entry, destLen is the total size
1275
+ of the destination buffer, which must be large enough to hold the entire
1276
+ uncompressed data. (The size of the uncompressed data must have been saved
1277
+ previously by the compressor and transmitted to the decompressor by some
1278
+ mechanism outside the scope of this compression library.) Upon exit, destLen
1279
+ is the actual size of the uncompressed data.
1280
+
1281
+ uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
1282
+ enough memory, Z_BUF_ERROR if there was not enough room in the output
1283
+ buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In
1284
+ the case where there is not enough room, uncompress() will fill the output
1285
+ buffer with the uncompressed data up to that point.
1286
+ */
1287
+
1288
+ ZEXTERN int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen,
1289
+ const Bytef *source, uLong *sourceLen);
1290
+ /*
1291
+ Same as uncompress, except that sourceLen is a pointer, where the
1292
+ length of the source is *sourceLen. On return, *sourceLen is the number of
1293
+ source bytes consumed.
1294
+ */
1295
+
1296
+ /* gzip file access functions */
1297
+
1298
+ /*
1299
+ This library supports reading and writing files in gzip (.gz) format with
1300
+ an interface similar to that of stdio, using the functions that start with
1301
+ "gz". The gzip format is different from the zlib format. gzip is a gzip
1302
+ wrapper, documented in RFC 1952, wrapped around a deflate stream.
1303
+ */
1304
+
1305
+ typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */
1306
+
1307
+ /*
1308
+ ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode);
1309
+
1310
+ Open the gzip (.gz) file at path for reading and decompressing, or
1311
+ compressing and writing. The mode parameter is as in fopen ("rb" or "wb")
1312
+ but can also include a compression level ("wb9") or a strategy: 'f' for
1313
+ filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h",
1314
+ 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression
1315
+ as in "wb9F". (See the description of deflateInit2 for more information
1316
+ about the strategy parameter.) 'T' will request transparent writing or
1317
+ appending with no compression and not using the gzip format.
1318
+
1319
+ "a" can be used instead of "w" to request that the gzip stream that will
1320
+ be written be appended to the file. "+" will result in an error, since
1321
+ reading and writing to the same gzip file is not supported. The addition of
1322
+ "x" when writing will create the file exclusively, which fails if the file
1323
+ already exists. On systems that support it, the addition of "e" when
1324
+ reading or writing will set the flag to close the file on an execve() call.
1325
+
1326
+ These functions, as well as gzip, will read and decode a sequence of gzip
1327
+ streams in a file. The append function of gzopen() can be used to create
1328
+ such a file. (Also see gzflush() for another way to do this.) When
1329
+ appending, gzopen does not test whether the file begins with a gzip stream,
1330
+ nor does it look for the end of the gzip streams to begin appending. gzopen
1331
+ will simply append a gzip stream to the existing file.
1332
+
1333
+ gzopen can be used to read a file which is not in gzip format; in this
1334
+ case gzread will directly read from the file without decompression. When
1335
+ reading, this will be detected automatically by looking for the magic two-
1336
+ byte gzip header.
1337
+
1338
+ gzopen returns NULL if the file could not be opened, if there was
1339
+ insufficient memory to allocate the gzFile state, or if an invalid mode was
1340
+ specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
1341
+ errno can be checked to determine if the reason gzopen failed was that the
1342
+ file could not be opened.
1343
+ */
1344
+
1345
+ ZEXTERN gzFile ZEXPORT gzdopen(int fd, const char *mode);
1346
+ /*
1347
+ Associate a gzFile with the file descriptor fd. File descriptors are
1348
+ obtained from calls like open, dup, creat, pipe or fileno (if the file has
1349
+ been previously opened with fopen). The mode parameter is as in gzopen.
1350
+
1351
+ The next call of gzclose on the returned gzFile will also close the file
1352
+ descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
1353
+ fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
1354
+ mode);. The duplicated descriptor should be saved to avoid a leak, since
1355
+ gzdopen does not close fd if it fails. If you are using fileno() to get the
1356
+ file descriptor from a FILE *, then you will have to use dup() to avoid
1357
+ double-close()ing the file descriptor. Both gzclose() and fclose() will
1358
+ close the associated file descriptor, so they need to have different file
1359
+ descriptors.
1360
+
1361
+ gzdopen returns NULL if there was insufficient memory to allocate the
1362
+ gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
1363
+ provided, or '+' was provided), or if fd is -1. The file descriptor is not
1364
+ used until the next gz* read, write, seek, or close operation, so gzdopen
1365
+ will not detect if fd is invalid (unless fd is -1).
1366
+ */
1367
+
1368
+ ZEXTERN int ZEXPORT gzbuffer(gzFile file, unsigned size);
1369
+ /*
1370
+ Set the internal buffer size used by this library's functions for file to
1371
+ size. The default buffer size is 8192 bytes. This function must be called
1372
+ after gzopen() or gzdopen(), and before any other calls that read or write
1373
+ the file. The buffer memory allocation is always deferred to the first read
1374
+ or write. Three times that size in buffer space is allocated. A larger
1375
+ buffer size of, for example, 64K or 128K bytes will noticeably increase the
1376
+ speed of decompression (reading).
1377
+
1378
+ The new buffer size also affects the maximum length for gzprintf().
1379
+
1380
+ gzbuffer() returns 0 on success, or -1 on failure, such as being called
1381
+ too late.
1382
+ */
1383
+
1384
+ ZEXTERN int ZEXPORT gzsetparams(gzFile file, int level, int strategy);
1385
+ /*
1386
+ Dynamically update the compression level and strategy for file. See the
1387
+ description of deflateInit2 for the meaning of these parameters. Previously
1388
+ provided data is flushed before applying the parameter changes.
1389
+
1390
+ gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not
1391
+ opened for writing, Z_ERRNO if there is an error writing the flushed data,
1392
+ or Z_MEM_ERROR if there is a memory allocation error.
1393
+ */
1394
+
1395
+ ZEXTERN int ZEXPORT gzread(gzFile file, voidp buf, unsigned len);
1396
+ /*
1397
+ Read and decompress up to len uncompressed bytes from file into buf. If
1398
+ the input file is not in gzip format, gzread copies the given number of
1399
+ bytes into the buffer directly from the file.
1400
+
1401
+ After reaching the end of a gzip stream in the input, gzread will continue
1402
+ to read, looking for another gzip stream. Any number of gzip streams may be
1403
+ concatenated in the input file, and will all be decompressed by gzread().
1404
+ If something other than a gzip stream is encountered after a gzip stream,
1405
+ that remaining trailing garbage is ignored (and no error is returned).
1406
+
1407
+ gzread can be used to read a gzip file that is being concurrently written.
1408
+ Upon reaching the end of the input, gzread will return with the available
1409
+ data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then
1410
+ gzclearerr can be used to clear the end of file indicator in order to permit
1411
+ gzread to be tried again. Z_OK indicates that a gzip stream was completed
1412
+ on the last gzread. Z_BUF_ERROR indicates that the input file ended in the
1413
+ middle of a gzip stream. Note that gzread does not return -1 in the event
1414
+ of an incomplete gzip stream. This error is deferred until gzclose(), which
1415
+ will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip
1416
+ stream. Alternatively, gzerror can be used before gzclose to detect this
1417
+ case.
1418
+
1419
+ gzread returns the number of uncompressed bytes actually read, less than
1420
+ len for end of file, or -1 for error. If len is too large to fit in an int,
1421
+ then nothing is read, -1 is returned, and the error state is set to
1422
+ Z_STREAM_ERROR.
1423
+ */
1424
+
1425
+ ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems,
1426
+ gzFile file);
1427
+ /*
1428
+ Read and decompress up to nitems items of size size from file into buf,
1429
+ otherwise operating as gzread() does. This duplicates the interface of
1430
+ stdio's fread(), with size_t request and return types. If the library
1431
+ defines size_t, then z_size_t is identical to size_t. If not, then z_size_t
1432
+ is an unsigned integer type that can contain a pointer.
1433
+
1434
+ gzfread() returns the number of full items read of size size, or zero if
1435
+ the end of the file was reached and a full item could not be read, or if
1436
+ there was an error. gzerror() must be consulted if zero is returned in
1437
+ order to determine if there was an error. If the multiplication of size and
1438
+ nitems overflows, i.e. the product does not fit in a z_size_t, then nothing
1439
+ is read, zero is returned, and the error state is set to Z_STREAM_ERROR.
1440
+
1441
+ In the event that the end of file is reached and only a partial item is
1442
+ available at the end, i.e. the remaining uncompressed data length is not a
1443
+ multiple of size, then the final partial item is nevertheless read into buf
1444
+ and the end-of-file flag is set. The length of the partial item read is not
1445
+ provided, but could be inferred from the result of gztell(). This behavior
1446
+ is the same as the behavior of fread() implementations in common libraries,
1447
+ but it prevents the direct use of gzfread() to read a concurrently written
1448
+ file, resetting and retrying on end-of-file, when size is not 1.
1449
+ */
1450
+
1451
+ ZEXTERN int ZEXPORT gzwrite(gzFile file, voidpc buf, unsigned len);
1452
+ /*
1453
+ Compress and write the len uncompressed bytes at buf to file. gzwrite
1454
+ returns the number of uncompressed bytes written or 0 in case of error.
1455
+ */
1456
+
1457
+ ZEXTERN z_size_t ZEXPORT gzfwrite(voidpc buf, z_size_t size,
1458
+ z_size_t nitems, gzFile file);
1459
+ /*
1460
+ Compress and write nitems items of size size from buf to file, duplicating
1461
+ the interface of stdio's fwrite(), with size_t request and return types. If
1462
+ the library defines size_t, then z_size_t is identical to size_t. If not,
1463
+ then z_size_t is an unsigned integer type that can contain a pointer.
1464
+
1465
+ gzfwrite() returns the number of full items written of size size, or zero
1466
+ if there was an error. If the multiplication of size and nitems overflows,
1467
+ i.e. the product does not fit in a z_size_t, then nothing is written, zero
1468
+ is returned, and the error state is set to Z_STREAM_ERROR.
1469
+ */
1470
+
1471
+ ZEXTERN int ZEXPORTVA gzprintf(gzFile file, const char *format, ...);
1472
+ /*
1473
+ Convert, format, compress, and write the arguments (...) to file under
1474
+ control of the string format, as in fprintf. gzprintf returns the number of
1475
+ uncompressed bytes actually written, or a negative zlib error code in case
1476
+ of error. The number of uncompressed bytes written is limited to 8191, or
1477
+ one less than the buffer size given to gzbuffer(). The caller should assure
1478
+ that this limit is not exceeded. If it is exceeded, then gzprintf() will
1479
+ return an error (0) with nothing written. In this case, there may also be a
1480
+ buffer overflow with unpredictable consequences, which is possible only if
1481
+ zlib was compiled with the insecure functions sprintf() or vsprintf(),
1482
+ because the secure snprintf() or vsnprintf() functions were not available.
1483
+ This can be determined using zlibCompileFlags().
1484
+ */
1485
+
1486
+ ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s);
1487
+ /*
1488
+ Compress and write the given null-terminated string s to file, excluding
1489
+ the terminating null character.
1490
+
1491
+ gzputs returns the number of characters written, or -1 in case of error.
1492
+ */
1493
+
1494
+ ZEXTERN char * ZEXPORT gzgets(gzFile file, char *buf, int len);
1495
+ /*
1496
+ Read and decompress bytes from file into buf, until len-1 characters are
1497
+ read, or until a newline character is read and transferred to buf, or an
1498
+ end-of-file condition is encountered. If any characters are read or if len
1499
+ is one, the string is terminated with a null character. If no characters
1500
+ are read due to an end-of-file or len is less than one, then the buffer is
1501
+ left untouched.
1502
+
1503
+ gzgets returns buf which is a null-terminated string, or it returns NULL
1504
+ for end-of-file or in case of error. If there was an error, the contents at
1505
+ buf are indeterminate.
1506
+ */
1507
+
1508
+ ZEXTERN int ZEXPORT gzputc(gzFile file, int c);
1509
+ /*
1510
+ Compress and write c, converted to an unsigned char, into file. gzputc
1511
+ returns the value that was written, or -1 in case of error.
1512
+ */
1513
+
1514
+ ZEXTERN int ZEXPORT gzgetc(gzFile file);
1515
+ /*
1516
+ Read and decompress one byte from file. gzgetc returns this byte or -1
1517
+ in case of end of file or error. This is implemented as a macro for speed.
1518
+ As such, it does not do all of the checking the other functions do. I.e.
1519
+ it does not check to see if file is NULL, nor whether the structure file
1520
+ points to has been clobbered or not.
1521
+ */
1522
+
1523
+ ZEXTERN int ZEXPORT gzungetc(int c, gzFile file);
1524
+ /*
1525
+ Push c back onto the stream for file to be read as the first character on
1526
+ the next read. At least one character of push-back is always allowed.
1527
+ gzungetc() returns the character pushed, or -1 on failure. gzungetc() will
1528
+ fail if c is -1, and may fail if a character has been pushed but not read
1529
+ yet. If gzungetc is used immediately after gzopen or gzdopen, at least the
1530
+ output buffer size of pushed characters is allowed. (See gzbuffer above.)
1531
+ The pushed character will be discarded if the stream is repositioned with
1532
+ gzseek() or gzrewind().
1533
+ */
1534
+
1535
+ ZEXTERN int ZEXPORT gzflush(gzFile file, int flush);
1536
+ /*
1537
+ Flush all pending output to file. The parameter flush is as in the
1538
+ deflate() function. The return value is the zlib error number (see function
1539
+ gzerror below). gzflush is only permitted when writing.
1540
+
1541
+ If the flush parameter is Z_FINISH, the remaining data is written and the
1542
+ gzip stream is completed in the output. If gzwrite() is called again, a new
1543
+ gzip stream will be started in the output. gzread() is able to read such
1544
+ concatenated gzip streams.
1545
+
1546
+ gzflush should be called only when strictly necessary because it will
1547
+ degrade compression if called too often.
1548
+ */
1549
+
1550
+ /*
1551
+ ZEXTERN z_off_t ZEXPORT gzseek(gzFile file,
1552
+ z_off_t offset, int whence);
1553
+
1554
+ Set the starting position to offset relative to whence for the next gzread
1555
+ or gzwrite on file. The offset represents a number of bytes in the
1556
+ uncompressed data stream. The whence parameter is defined as in lseek(2);
1557
+ the value SEEK_END is not supported.
1558
+
1559
+ If the file is opened for reading, this function is emulated but can be
1560
+ extremely slow. If the file is opened for writing, only forward seeks are
1561
+ supported; gzseek then compresses a sequence of zeroes up to the new
1562
+ starting position.
1563
+
1564
+ gzseek returns the resulting offset location as measured in bytes from
1565
+ the beginning of the uncompressed stream, or -1 in case of error, in
1566
+ particular if the file is opened for writing and the new starting position
1567
+ would be before the current position.
1568
+ */
1569
+
1570
+ ZEXTERN int ZEXPORT gzrewind(gzFile file);
1571
+ /*
1572
+ Rewind file. This function is supported only for reading.
1573
+
1574
+ gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET).
1575
+ */
1576
+
1577
+ /*
1578
+ ZEXTERN z_off_t ZEXPORT gztell(gzFile file);
1579
+
1580
+ Return the starting position for the next gzread or gzwrite on file.
1581
+ This position represents a number of bytes in the uncompressed data stream,
1582
+ and is zero when starting, even if appending or reading a gzip stream from
1583
+ the middle of a file using gzdopen().
1584
+
1585
+ gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
1586
+ */
1587
+
1588
+ /*
1589
+ ZEXTERN z_off_t ZEXPORT gzoffset(gzFile file);
1590
+
1591
+ Return the current compressed (actual) read or write offset of file. This
1592
+ offset includes the count of bytes that precede the gzip stream, for example
1593
+ when appending or when using gzdopen() for reading. When reading, the
1594
+ offset does not include as yet unused buffered input. This information can
1595
+ be used for a progress indicator. On error, gzoffset() returns -1.
1596
+ */
1597
+
1598
+ ZEXTERN int ZEXPORT gzeof(gzFile file);
1599
+ /*
1600
+ Return true (1) if the end-of-file indicator for file has been set while
1601
+ reading, false (0) otherwise. Note that the end-of-file indicator is set
1602
+ only if the read tried to go past the end of the input, but came up short.
1603
+ Therefore, just like feof(), gzeof() may return false even if there is no
1604
+ more data to read, in the event that the last read request was for the exact
1605
+ number of bytes remaining in the input file. This will happen if the input
1606
+ file size is an exact multiple of the buffer size.
1607
+
1608
+ If gzeof() returns true, then the read functions will return no more data,
1609
+ unless the end-of-file indicator is reset by gzclearerr() and the input file
1610
+ has grown since the previous end of file was detected.
1611
+ */
1612
+
1613
+ ZEXTERN int ZEXPORT gzdirect(gzFile file);
1614
+ /*
1615
+ Return true (1) if file is being copied directly while reading, or false
1616
+ (0) if file is a gzip stream being decompressed.
1617
+
1618
+ If the input file is empty, gzdirect() will return true, since the input
1619
+ does not contain a gzip stream.
1620
+
1621
+ If gzdirect() is used immediately after gzopen() or gzdopen() it will
1622
+ cause buffers to be allocated to allow reading the file to determine if it
1623
+ is a gzip file. Therefore if gzbuffer() is used, it should be called before
1624
+ gzdirect().
1625
+
1626
+ When writing, gzdirect() returns true (1) if transparent writing was
1627
+ requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note:
1628
+ gzdirect() is not needed when writing. Transparent writing must be
1629
+ explicitly requested, so the application already knows the answer. When
1630
+ linking statically, using gzdirect() will include all of the zlib code for
1631
+ gzip file reading and decompression, which may not be desired.)
1632
+ */
1633
+
1634
+ ZEXTERN int ZEXPORT gzclose(gzFile file);
1635
+ /*
1636
+ Flush all pending output for file, if necessary, close file and
1637
+ deallocate the (de)compression state. Note that once file is closed, you
1638
+ cannot call gzerror with file, since its structures have been deallocated.
1639
+ gzclose must not be called more than once on the same file, just as free
1640
+ must not be called more than once on the same allocation.
1641
+
1642
+ gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
1643
+ file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the
1644
+ last read ended in the middle of a gzip stream, or Z_OK on success.
1645
+ */
1646
+
1647
+ ZEXTERN int ZEXPORT gzclose_r(gzFile file);
1648
+ ZEXTERN int ZEXPORT gzclose_w(gzFile file);
1649
+ /*
1650
+ Same as gzclose(), but gzclose_r() is only for use when reading, and
1651
+ gzclose_w() is only for use when writing or appending. The advantage to
1652
+ using these instead of gzclose() is that they avoid linking in zlib
1653
+ compression or decompression code that is not used when only reading or only
1654
+ writing respectively. If gzclose() is used, then both compression and
1655
+ decompression code will be included the application when linking to a static
1656
+ zlib library.
1657
+ */
1658
+
1659
+ ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum);
1660
+ /*
1661
+ Return the error message for the last error which occurred on file.
1662
+ errnum is set to zlib error number. If an error occurred in the file system
1663
+ and not in the compression library, errnum is set to Z_ERRNO and the
1664
+ application may consult errno to get the exact error code.
1665
+
1666
+ The application must not modify the returned string. Future calls to
1667
+ this function may invalidate the previously returned string. If file is
1668
+ closed, then the string previously returned by gzerror will no longer be
1669
+ available.
1670
+
1671
+ gzerror() should be used to distinguish errors from end-of-file for those
1672
+ functions above that do not distinguish those cases in their return values.
1673
+ */
1674
+
1675
+ ZEXTERN void ZEXPORT gzclearerr(gzFile file);
1676
+ /*
1677
+ Clear the error and end-of-file flags for file. This is analogous to the
1678
+ clearerr() function in stdio. This is useful for continuing to read a gzip
1679
+ file that is being written concurrently.
1680
+ */
1681
+
1682
+ #endif /* !Z_SOLO */
1683
+
1684
+ /* checksum functions */
1685
+
1686
+ /*
1687
+ These functions are not related to compression but are exported
1688
+ anyway because they might be useful in applications using the compression
1689
+ library.
1690
+ */
1691
+
1692
+ ZEXTERN uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len);
1693
+ /*
1694
+ Update a running Adler-32 checksum with the bytes buf[0..len-1] and
1695
+ return the updated checksum. An Adler-32 value is in the range of a 32-bit
1696
+ unsigned integer. If buf is Z_NULL, this function returns the required
1697
+ initial value for the checksum.
1698
+
1699
+ An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed
1700
+ much faster.
1701
+
1702
+ Usage example:
1703
+
1704
+ uLong adler = adler32(0L, Z_NULL, 0);
1705
+
1706
+ while (read_buffer(buffer, length) != EOF) {
1707
+ adler = adler32(adler, buffer, length);
1708
+ }
1709
+ if (adler != original_adler) error();
1710
+ */
1711
+
1712
+ ZEXTERN uLong ZEXPORT adler32_z(uLong adler, const Bytef *buf,
1713
+ z_size_t len);
1714
+ /*
1715
+ Same as adler32(), but with a size_t length.
1716
+ */
1717
+
1718
+ /*
1719
+ ZEXTERN uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2,
1720
+ z_off_t len2);
1721
+
1722
+ Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
1723
+ and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
1724
+ each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
1725
+ seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note
1726
+ that the z_off_t type (like off_t) is a signed integer. If len2 is
1727
+ negative, the result has no meaning or utility.
1728
+ */
1729
+
1730
+ ZEXTERN uLong ZEXPORT crc32(uLong crc, const Bytef *buf, uInt len);
1731
+ /*
1732
+ Update a running CRC-32 with the bytes buf[0..len-1] and return the
1733
+ updated CRC-32. A CRC-32 value is in the range of a 32-bit unsigned integer.
1734
+ If buf is Z_NULL, this function returns the required initial value for the
1735
+ crc. Pre- and post-conditioning (one's complement) is performed within this
1736
+ function so it shouldn't be done by the application.
1737
+
1738
+ Usage example:
1739
+
1740
+ uLong crc = crc32(0L, Z_NULL, 0);
1741
+
1742
+ while (read_buffer(buffer, length) != EOF) {
1743
+ crc = crc32(crc, buffer, length);
1744
+ }
1745
+ if (crc != original_crc) error();
1746
+ */
1747
+
1748
+ ZEXTERN uLong ZEXPORT crc32_z(uLong crc, const Bytef *buf,
1749
+ z_size_t len);
1750
+ /*
1751
+ Same as crc32(), but with a size_t length.
1752
+ */
1753
+
1754
+ /*
1755
+ ZEXTERN uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2);
1756
+
1757
+ Combine two CRC-32 check values into one. For two sequences of bytes,
1758
+ seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
1759
+ calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
1760
+ check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
1761
+ len2. len2 must be non-negative.
1762
+ */
1763
+
1764
+ /*
1765
+ ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t len2);
1766
+
1767
+ Return the operator corresponding to length len2, to be used with
1768
+ crc32_combine_op(). len2 must be non-negative.
1769
+ */
1770
+
1771
+ ZEXTERN uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op);
1772
+ /*
1773
+ Give the same result as crc32_combine(), using op in place of len2. op is
1774
+ is generated from len2 by crc32_combine_gen(). This will be faster than
1775
+ crc32_combine() if the generated op is used more than once.
1776
+ */
1777
+
1778
+
1779
+ /* various hacks, don't look :) */
1780
+
1781
+ /* deflateInit and inflateInit are macros to allow checking the zlib version
1782
+ * and the compiler's view of z_stream:
1783
+ */
1784
+ ZEXTERN int ZEXPORT deflateInit_(z_streamp strm, int level,
1785
+ const char *version, int stream_size);
1786
+ ZEXTERN int ZEXPORT inflateInit_(z_streamp strm,
1787
+ const char *version, int stream_size);
1788
+ ZEXTERN int ZEXPORT deflateInit2_(z_streamp strm, int level, int method,
1789
+ int windowBits, int memLevel,
1790
+ int strategy, const char *version,
1791
+ int stream_size);
1792
+ ZEXTERN int ZEXPORT inflateInit2_(z_streamp strm, int windowBits,
1793
+ const char *version, int stream_size);
1794
+ ZEXTERN int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits,
1795
+ unsigned char FAR *window,
1796
+ const char *version,
1797
+ int stream_size);
1798
+ #ifdef Z_PREFIX_SET
1799
+ # define z_deflateInit(strm, level) \
1800
+ deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
1801
+ # define z_inflateInit(strm) \
1802
+ inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
1803
+ # define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
1804
+ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
1805
+ (strategy), ZLIB_VERSION, (int)sizeof(z_stream))
1806
+ # define z_inflateInit2(strm, windowBits) \
1807
+ inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
1808
+ (int)sizeof(z_stream))
1809
+ # define z_inflateBackInit(strm, windowBits, window) \
1810
+ inflateBackInit_((strm), (windowBits), (window), \
1811
+ ZLIB_VERSION, (int)sizeof(z_stream))
1812
+ #else
1813
+ # define deflateInit(strm, level) \
1814
+ deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
1815
+ # define inflateInit(strm) \
1816
+ inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
1817
+ # define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
1818
+ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
1819
+ (strategy), ZLIB_VERSION, (int)sizeof(z_stream))
1820
+ # define inflateInit2(strm, windowBits) \
1821
+ inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
1822
+ (int)sizeof(z_stream))
1823
+ # define inflateBackInit(strm, windowBits, window) \
1824
+ inflateBackInit_((strm), (windowBits), (window), \
1825
+ ZLIB_VERSION, (int)sizeof(z_stream))
1826
+ #endif
1827
+
1828
+ #ifndef Z_SOLO
1829
+
1830
+ /* gzgetc() macro and its supporting function and exposed data structure. Note
1831
+ * that the real internal state is much larger than the exposed structure.
1832
+ * This abbreviated structure exposes just enough for the gzgetc() macro. The
1833
+ * user should not mess with these exposed elements, since their names or
1834
+ * behavior could change in the future, perhaps even capriciously. They can
1835
+ * only be used by the gzgetc() macro. You have been warned.
1836
+ */
1837
+ struct gzFile_s {
1838
+ unsigned have;
1839
+ unsigned char *next;
1840
+ z_off64_t pos;
1841
+ };
1842
+ ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */
1843
+ #ifdef Z_PREFIX_SET
1844
+ # undef z_gzgetc
1845
+ # define z_gzgetc(g) \
1846
+ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g))
1847
+ #else
1848
+ # define gzgetc(g) \
1849
+ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g))
1850
+ #endif
1851
+
1852
+ /* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or
1853
+ * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
1854
+ * both are true, the application gets the *64 functions, and the regular
1855
+ * functions are changed to 64 bits) -- in case these are set on systems
1856
+ * without large file support, _LFS64_LARGEFILE must also be true
1857
+ */
1858
+ #ifdef Z_LARGE64
1859
+ ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *);
1860
+ ZEXTERN z_off64_t ZEXPORT gzseek64(gzFile, z_off64_t, int);
1861
+ ZEXTERN z_off64_t ZEXPORT gztell64(gzFile);
1862
+ ZEXTERN z_off64_t ZEXPORT gzoffset64(gzFile);
1863
+ ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off64_t);
1864
+ ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off64_t);
1865
+ ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off64_t);
1866
+ #endif
1867
+
1868
+ #if !defined(ZLIB_INTERNAL) && defined(Z_WANT64)
1869
+ # ifdef Z_PREFIX_SET
1870
+ # define z_gzopen z_gzopen64
1871
+ # define z_gzseek z_gzseek64
1872
+ # define z_gztell z_gztell64
1873
+ # define z_gzoffset z_gzoffset64
1874
+ # define z_adler32_combine z_adler32_combine64
1875
+ # define z_crc32_combine z_crc32_combine64
1876
+ # define z_crc32_combine_gen z_crc32_combine_gen64
1877
+ # else
1878
+ # define gzopen gzopen64
1879
+ # define gzseek gzseek64
1880
+ # define gztell gztell64
1881
+ # define gzoffset gzoffset64
1882
+ # define adler32_combine adler32_combine64
1883
+ # define crc32_combine crc32_combine64
1884
+ # define crc32_combine_gen crc32_combine_gen64
1885
+ # endif
1886
+ # ifndef Z_LARGE64
1887
+ ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *);
1888
+ ZEXTERN z_off_t ZEXPORT gzseek64(gzFile, z_off_t, int);
1889
+ ZEXTERN z_off_t ZEXPORT gztell64(gzFile);
1890
+ ZEXTERN z_off_t ZEXPORT gzoffset64(gzFile);
1891
+ ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off_t);
1892
+ ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off_t);
1893
+ ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off_t);
1894
+ # endif
1895
+ #else
1896
+ ZEXTERN gzFile ZEXPORT gzopen(const char *, const char *);
1897
+ ZEXTERN z_off_t ZEXPORT gzseek(gzFile, z_off_t, int);
1898
+ ZEXTERN z_off_t ZEXPORT gztell(gzFile);
1899
+ ZEXTERN z_off_t ZEXPORT gzoffset(gzFile);
1900
+ ZEXTERN uLong ZEXPORT adler32_combine(uLong, uLong, z_off_t);
1901
+ ZEXTERN uLong ZEXPORT crc32_combine(uLong, uLong, z_off_t);
1902
+ ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t);
1903
+ #endif
1904
+
1905
+ #else /* Z_SOLO */
1906
+
1907
+ ZEXTERN uLong ZEXPORT adler32_combine(uLong, uLong, z_off_t);
1908
+ ZEXTERN uLong ZEXPORT crc32_combine(uLong, uLong, z_off_t);
1909
+ ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t);
1910
+
1911
+ #endif /* !Z_SOLO */
1912
+
1913
+ /* undocumented functions */
1914
+ ZEXTERN const char * ZEXPORT zError(int);
1915
+ ZEXTERN int ZEXPORT inflateSyncPoint(z_streamp);
1916
+ ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void);
1917
+ ZEXTERN int ZEXPORT inflateUndermine(z_streamp, int);
1918
+ ZEXTERN int ZEXPORT inflateValidate(z_streamp, int);
1919
+ ZEXTERN unsigned long ZEXPORT inflateCodesUsed(z_streamp);
1920
+ ZEXTERN int ZEXPORT inflateResetKeep(z_streamp);
1921
+ ZEXTERN int ZEXPORT deflateResetKeep(z_streamp);
1922
+ #if defined(_WIN32) && !defined(Z_SOLO)
1923
+ ZEXTERN gzFile ZEXPORT gzopen_w(const wchar_t *path,
1924
+ const char *mode);
1925
+ #endif
1926
+ #if defined(STDC) || defined(Z_HAVE_STDARG_H)
1927
+ # ifndef Z_SOLO
1928
+ ZEXTERN int ZEXPORTVA gzvprintf(gzFile file,
1929
+ const char *format,
1930
+ va_list va);
1931
+ # endif
1932
+ #endif
1933
+
1934
+ #ifdef __cplusplus
1935
+ }
1936
+ #endif
1937
+
1938
+ #endif /* ZLIB_H */
deps/exla/cache/xla_extension/include/external/zlib/zutil.h ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* zutil.h -- internal interface and configuration of the compression library
2
+ * Copyright (C) 1995-2024 Jean-loup Gailly, Mark Adler
3
+ * For conditions of distribution and use, see copyright notice in zlib.h
4
+ */
5
+
6
+ /* WARNING: this file should *not* be used by applications. It is
7
+ part of the implementation of the compression library and is
8
+ subject to change. Applications should only use zlib.h.
9
+ */
10
+
11
+ /* @(#) $Id$ */
12
+
13
+ #ifndef ZUTIL_H
14
+ #define ZUTIL_H
15
+
16
+ #ifdef HAVE_HIDDEN
17
+ # define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
18
+ #else
19
+ # define ZLIB_INTERNAL
20
+ #endif
21
+
22
+ #include "zlib.h"
23
+
24
+ #if defined(STDC) && !defined(Z_SOLO)
25
+ # if !(defined(_WIN32_WCE) && defined(_MSC_VER))
26
+ # include <stddef.h>
27
+ # endif
28
+ # include <string.h>
29
+ # include <stdlib.h>
30
+ #endif
31
+
32
+ #ifndef local
33
+ # define local static
34
+ #endif
35
+ /* since "static" is used to mean two completely different things in C, we
36
+ define "local" for the non-static meaning of "static", for readability
37
+ (compile with -Dlocal if your debugger can't find static symbols) */
38
+
39
+ typedef unsigned char uch;
40
+ typedef uch FAR uchf;
41
+ typedef unsigned short ush;
42
+ typedef ush FAR ushf;
43
+ typedef unsigned long ulg;
44
+
45
+ #if !defined(Z_U8) && !defined(Z_SOLO) && defined(STDC)
46
+ # include <limits.h>
47
+ # if (ULONG_MAX == 0xffffffffffffffff)
48
+ # define Z_U8 unsigned long
49
+ # elif (ULLONG_MAX == 0xffffffffffffffff)
50
+ # define Z_U8 unsigned long long
51
+ # elif (UINT_MAX == 0xffffffffffffffff)
52
+ # define Z_U8 unsigned
53
+ # endif
54
+ #endif
55
+
56
+ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
57
+ /* (size given to avoid silly warnings with Visual C++) */
58
+
59
+ #define ERR_MSG(err) z_errmsg[(err) < -6 || (err) > 2 ? 9 : 2 - (err)]
60
+
61
+ #define ERR_RETURN(strm,err) \
62
+ return (strm->msg = ERR_MSG(err), (err))
63
+ /* To be used only when the state is known to be valid */
64
+
65
+ /* common constants */
66
+
67
+ #ifndef DEF_WBITS
68
+ # define DEF_WBITS MAX_WBITS
69
+ #endif
70
+ /* default windowBits for decompression. MAX_WBITS is for compression only */
71
+
72
+ #if MAX_MEM_LEVEL >= 8
73
+ # define DEF_MEM_LEVEL 8
74
+ #else
75
+ # define DEF_MEM_LEVEL MAX_MEM_LEVEL
76
+ #endif
77
+ /* default memLevel */
78
+
79
+ #define STORED_BLOCK 0
80
+ #define STATIC_TREES 1
81
+ #define DYN_TREES 2
82
+ /* The three kinds of block type */
83
+
84
+ #define MIN_MATCH 3
85
+ #define MAX_MATCH 258
86
+ /* The minimum and maximum match lengths */
87
+
88
+ #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
89
+
90
+ /* target dependencies */
91
+
92
+ #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
93
+ # define OS_CODE 0x00
94
+ # ifndef Z_SOLO
95
+ # if defined(__TURBOC__) || defined(__BORLANDC__)
96
+ # if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
97
+ /* Allow compilation with ANSI keywords only enabled */
98
+ void _Cdecl farfree( void *block );
99
+ void *_Cdecl farmalloc( unsigned long nbytes );
100
+ # else
101
+ # include <alloc.h>
102
+ # endif
103
+ # else /* MSC or DJGPP */
104
+ # include <malloc.h>
105
+ # endif
106
+ # endif
107
+ #endif
108
+
109
+ #ifdef AMIGA
110
+ # define OS_CODE 1
111
+ #endif
112
+
113
+ #if defined(VAXC) || defined(VMS)
114
+ # define OS_CODE 2
115
+ # define F_OPEN(name, mode) \
116
+ fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
117
+ #endif
118
+
119
+ #ifdef __370__
120
+ # if __TARGET_LIB__ < 0x20000000
121
+ # define OS_CODE 4
122
+ # elif __TARGET_LIB__ < 0x40000000
123
+ # define OS_CODE 11
124
+ # else
125
+ # define OS_CODE 8
126
+ # endif
127
+ #endif
128
+
129
+ #if defined(ATARI) || defined(atarist)
130
+ # define OS_CODE 5
131
+ #endif
132
+
133
+ #ifdef OS2
134
+ # define OS_CODE 6
135
+ # if defined(M_I86) && !defined(Z_SOLO)
136
+ # include <malloc.h>
137
+ # endif
138
+ #endif
139
+
140
+ #if defined(MACOS)
141
+ # define OS_CODE 7
142
+ #endif
143
+
144
+ #ifdef __acorn
145
+ # define OS_CODE 13
146
+ #endif
147
+
148
+ #if defined(WIN32) && !defined(__CYGWIN__)
149
+ # define OS_CODE 10
150
+ #endif
151
+
152
+ #ifdef _BEOS_
153
+ # define OS_CODE 16
154
+ #endif
155
+
156
+ #ifdef __TOS_OS400__
157
+ # define OS_CODE 18
158
+ #endif
159
+
160
+ #ifdef __APPLE__
161
+ # define OS_CODE 19
162
+ #endif
163
+
164
+ #if defined(__BORLANDC__) && !defined(MSDOS)
165
+ #pragma warn -8004
166
+ #pragma warn -8008
167
+ #pragma warn -8066
168
+ #endif
169
+
170
+ /* provide prototypes for these when building zlib without LFS */
171
+ #if !defined(_WIN32) && \
172
+ (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0)
173
+ ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off_t);
174
+ ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off_t);
175
+ ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off_t);
176
+ #endif
177
+
178
+ /* common defaults */
179
+
180
+ #ifndef OS_CODE
181
+ # define OS_CODE 3 /* assume Unix */
182
+ #endif
183
+
184
+ #ifndef F_OPEN
185
+ # define F_OPEN(name, mode) fopen((name), (mode))
186
+ #endif
187
+
188
+ /* functions */
189
+
190
+ #if defined(pyr) || defined(Z_SOLO)
191
+ # define NO_MEMCPY
192
+ #endif
193
+ #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
194
+ /* Use our own functions for small and medium model with MSC <= 5.0.
195
+ * You may have to use the same strategy for Borland C (untested).
196
+ * The __SC__ check is for Symantec.
197
+ */
198
+ # define NO_MEMCPY
199
+ #endif
200
+ #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
201
+ # define HAVE_MEMCPY
202
+ #endif
203
+ #ifdef HAVE_MEMCPY
204
+ # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
205
+ # define zmemcpy _fmemcpy
206
+ # define zmemcmp _fmemcmp
207
+ # define zmemzero(dest, len) _fmemset(dest, 0, len)
208
+ # else
209
+ # define zmemcpy memcpy
210
+ # define zmemcmp memcmp
211
+ # define zmemzero(dest, len) memset(dest, 0, len)
212
+ # endif
213
+ #else
214
+ void ZLIB_INTERNAL zmemcpy(Bytef* dest, const Bytef* source, uInt len);
215
+ int ZLIB_INTERNAL zmemcmp(const Bytef* s1, const Bytef* s2, uInt len);
216
+ void ZLIB_INTERNAL zmemzero(Bytef* dest, uInt len);
217
+ #endif
218
+
219
+ /* Diagnostic functions */
220
+ #ifdef ZLIB_DEBUG
221
+ # include <stdio.h>
222
+ extern int ZLIB_INTERNAL z_verbose;
223
+ extern void ZLIB_INTERNAL z_error(char *m);
224
+ # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
225
+ # define Trace(x) {if (z_verbose>=0) fprintf x ;}
226
+ # define Tracev(x) {if (z_verbose>0) fprintf x ;}
227
+ # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
228
+ # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
229
+ # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
230
+ #else
231
+ # define Assert(cond,msg)
232
+ # define Trace(x)
233
+ # define Tracev(x)
234
+ # define Tracevv(x)
235
+ # define Tracec(c,x)
236
+ # define Tracecv(c,x)
237
+ #endif
238
+
239
+ #ifndef Z_SOLO
240
+ voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items,
241
+ unsigned size);
242
+ void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr);
243
+ #endif
244
+
245
+ #define ZALLOC(strm, items, size) \
246
+ (*((strm)->zalloc))((strm)->opaque, (items), (size))
247
+ #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
248
+ #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
249
+
250
+ /* Reverse the bytes in a 32-bit value */
251
+ #define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
252
+ (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
253
+
254
+ #endif /* ZUTIL_H */
deps/exla/cache/xla_extension/include/farmhash.h ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2014 Google, Inc.
2
+ //
3
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ // of this software and associated documentation files (the "Software"), to deal
5
+ // in the Software without restriction, including without limitation the rights
6
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ // copies of the Software, and to permit persons to whom the Software is
8
+ // furnished to do so, subject to the following conditions:
9
+ //
10
+ // The above copyright notice and this permission notice shall be included in
11
+ // all copies or substantial portions of the Software.
12
+ //
13
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ // THE SOFTWARE.
20
+ //
21
+ // FarmHash, by Geoff Pike
22
+
23
+ //
24
+ // http://code.google.com/p/farmhash/
25
+ //
26
+ // This file provides a few functions for hashing strings and other
27
+ // data. All of them are high-quality functions in the sense that
28
+ // they do well on standard tests such as Austin Appleby's SMHasher.
29
+ // They're also fast. FarmHash is the successor to CityHash.
30
+ //
31
+ // Functions in the FarmHash family are not suitable for cryptography.
32
+ //
33
+ // WARNING: This code has been only lightly tested on big-endian platforms!
34
+ // It is known to work well on little-endian platforms that have a small penalty
35
+ // for unaligned reads, such as current Intel and AMD moderate-to-high-end CPUs.
36
+ // It should work on all 32-bit and 64-bit platforms that allow unaligned reads;
37
+ // bug reports are welcome.
38
+ //
39
+ // By the way, for some hash functions, given strings a and b, the hash
40
+ // of a+b is easily derived from the hashes of a and b. This property
41
+ // doesn't hold for any hash functions in this file.
42
+
43
+ #ifndef FARM_HASH_H_
44
+ #define FARM_HASH_H_
45
+
46
+ #include <assert.h>
47
+ #include <stdint.h>
48
+ #include <stdlib.h>
49
+ #include <string.h> // for memcpy and memset
50
+ #include <utility>
51
+
52
+ #ifndef NAMESPACE_FOR_HASH_FUNCTIONS
53
+ #define NAMESPACE_FOR_HASH_FUNCTIONS util
54
+ #endif
55
+
56
+ namespace NAMESPACE_FOR_HASH_FUNCTIONS {
57
+
58
+ #if defined(FARMHASH_UINT128_T_DEFINED)
59
+ #if defined(__clang__)
60
+ #if !defined(uint128_t)
61
+ #define uint128_t __uint128_t
62
+ #endif
63
+ #endif
64
+ inline uint64_t Uint128Low64(const uint128_t x) {
65
+ return static_cast<uint64_t>(x);
66
+ }
67
+ inline uint64_t Uint128High64(const uint128_t x) {
68
+ return static_cast<uint64_t>(x >> 64);
69
+ }
70
+ inline uint128_t Uint128(uint64_t lo, uint64_t hi) {
71
+ return lo + (((uint128_t)hi) << 64);
72
+ }
73
+ #else
74
+ typedef std::pair<uint64_t, uint64_t> uint128_t;
75
+ inline uint64_t Uint128Low64(const uint128_t x) { return x.first; }
76
+ inline uint64_t Uint128High64(const uint128_t x) { return x.second; }
77
+ inline uint128_t Uint128(uint64_t lo, uint64_t hi) { return uint128_t(lo, hi); }
78
+ #endif
79
+
80
+
81
+ // BASIC STRING HASHING
82
+
83
+ // Hash function for a byte array.
84
+ // May change from time to time, may differ on different platforms, may differ
85
+ // depending on NDEBUG.
86
+ size_t Hash(const char* s, size_t len);
87
+
88
+ // Hash function for a byte array. Most useful in 32-bit binaries.
89
+ // May change from time to time, may differ on different platforms, may differ
90
+ // depending on NDEBUG.
91
+ uint32_t Hash32(const char* s, size_t len);
92
+
93
+ // Hash function for a byte array. For convenience, a 32-bit seed is also
94
+ // hashed into the result.
95
+ // May change from time to time, may differ on different platforms, may differ
96
+ // depending on NDEBUG.
97
+ uint32_t Hash32WithSeed(const char* s, size_t len, uint32_t seed);
98
+
99
+ // Hash function for a byte array.
100
+ // May change from time to time, may differ on different platforms, may differ
101
+ // depending on NDEBUG.
102
+ uint64_t Hash64(const char* s, size_t len);
103
+
104
+ // Hash function for a byte array. For convenience, a 64-bit seed is also
105
+ // hashed into the result.
106
+ // May change from time to time, may differ on different platforms, may differ
107
+ // depending on NDEBUG.
108
+ uint64_t Hash64WithSeed(const char* s, size_t len, uint64_t seed);
109
+
110
+ // Hash function for a byte array. For convenience, two seeds are also
111
+ // hashed into the result.
112
+ // May change from time to time, may differ on different platforms, may differ
113
+ // depending on NDEBUG.
114
+ uint64_t Hash64WithSeeds(const char* s, size_t len,
115
+ uint64_t seed0, uint64_t seed1);
116
+
117
+ // Hash function for a byte array.
118
+ // May change from time to time, may differ on different platforms, may differ
119
+ // depending on NDEBUG.
120
+ uint128_t Hash128(const char* s, size_t len);
121
+
122
+ // Hash function for a byte array. For convenience, a 128-bit seed is also
123
+ // hashed into the result.
124
+ // May change from time to time, may differ on different platforms, may differ
125
+ // depending on NDEBUG.
126
+ uint128_t Hash128WithSeed(const char* s, size_t len, uint128_t seed);
127
+
128
+ // BASIC NON-STRING HASHING
129
+
130
+ // Hash 128 input bits down to 64 bits of output.
131
+ // This is intended to be a reasonably good hash function.
132
+ // May change from time to time, may differ on different platforms, may differ
133
+ // depending on NDEBUG.
134
+ inline uint64_t Hash128to64(uint128_t x) {
135
+ // Murmur-inspired hashing.
136
+ const uint64_t kMul = 0x9ddfea08eb382d69ULL;
137
+ uint64_t a = (Uint128Low64(x) ^ Uint128High64(x)) * kMul;
138
+ a ^= (a >> 47);
139
+ uint64_t b = (Uint128High64(x) ^ a) * kMul;
140
+ b ^= (b >> 47);
141
+ b *= kMul;
142
+ return b;
143
+ }
144
+
145
+ // FINGERPRINTING (i.e., good, portable, forever-fixed hash functions)
146
+
147
+ // Fingerprint function for a byte array. Most useful in 32-bit binaries.
148
+ uint32_t Fingerprint32(const char* s, size_t len);
149
+
150
+ // Fingerprint function for a byte array.
151
+ uint64_t Fingerprint64(const char* s, size_t len);
152
+
153
+ // Fingerprint function for a byte array.
154
+ uint128_t Fingerprint128(const char* s, size_t len);
155
+
156
+ // This is intended to be a good fingerprinting primitive.
157
+ // See below for more overloads.
158
+ inline uint64_t Fingerprint(uint128_t x) {
159
+ // Murmur-inspired hashing.
160
+ const uint64_t kMul = 0x9ddfea08eb382d69ULL;
161
+ uint64_t a = (Uint128Low64(x) ^ Uint128High64(x)) * kMul;
162
+ a ^= (a >> 47);
163
+ uint64_t b = (Uint128High64(x) ^ a) * kMul;
164
+ b ^= (b >> 44);
165
+ b *= kMul;
166
+ b ^= (b >> 41);
167
+ b *= kMul;
168
+ return b;
169
+ }
170
+
171
+ // This is intended to be a good fingerprinting primitive.
172
+ inline uint64_t Fingerprint(uint64_t x) {
173
+ // Murmur-inspired hashing.
174
+ const uint64_t kMul = 0x9ddfea08eb382d69ULL;
175
+ uint64_t b = x * kMul;
176
+ b ^= (b >> 44);
177
+ b *= kMul;
178
+ b ^= (b >> 41);
179
+ b *= kMul;
180
+ return b;
181
+ }
182
+
183
+ #ifndef FARMHASH_NO_CXX_STRING
184
+
185
+ // Convenience functions to hash or fingerprint C++ strings.
186
+ // These require that Str::data() return a pointer to the first char
187
+ // (as a const char*) and that Str::length() return the string's length;
188
+ // they work with std::string, for example.
189
+
190
+ // Hash function for a byte array.
191
+ // May change from time to time, may differ on different platforms, may differ
192
+ // depending on NDEBUG.
193
+ template <typename Str>
194
+ inline size_t Hash(const Str& s) {
195
+ assert(sizeof(s[0]) == 1);
196
+ return Hash(s.data(), s.length());
197
+ }
198
+
199
+ // Hash function for a byte array. Most useful in 32-bit binaries.
200
+ // May change from time to time, may differ on different platforms, may differ
201
+ // depending on NDEBUG.
202
+ template <typename Str>
203
+ inline uint32_t Hash32(const Str& s) {
204
+ assert(sizeof(s[0]) == 1);
205
+ return Hash32(s.data(), s.length());
206
+ }
207
+
208
+ // Hash function for a byte array. For convenience, a 32-bit seed is also
209
+ // hashed into the result.
210
+ // May change from time to time, may differ on different platforms, may differ
211
+ // depending on NDEBUG.
212
+ template <typename Str>
213
+ inline uint32_t Hash32WithSeed(const Str& s, uint32_t seed) {
214
+ assert(sizeof(s[0]) == 1);
215
+ return Hash32WithSeed(s.data(), s.length(), seed);
216
+ }
217
+
218
+ // Hash 128 input bits down to 64 bits of output.
219
+ // Hash function for a byte array.
220
+ // May change from time to time, may differ on different platforms, may differ
221
+ // depending on NDEBUG.
222
+ template <typename Str>
223
+ inline uint64_t Hash64(const Str& s) {
224
+ assert(sizeof(s[0]) == 1);
225
+ return Hash64(s.data(), s.length());
226
+ }
227
+
228
+ // Hash function for a byte array. For convenience, a 64-bit seed is also
229
+ // hashed into the result.
230
+ // May change from time to time, may differ on different platforms, may differ
231
+ // depending on NDEBUG.
232
+ template <typename Str>
233
+ inline uint64_t Hash64WithSeed(const Str& s, uint64_t seed) {
234
+ assert(sizeof(s[0]) == 1);
235
+ return Hash64WithSeed(s.data(), s.length(), seed);
236
+ }
237
+
238
+ // Hash function for a byte array. For convenience, two seeds are also
239
+ // hashed into the result.
240
+ // May change from time to time, may differ on different platforms, may differ
241
+ // depending on NDEBUG.
242
+ template <typename Str>
243
+ inline uint64_t Hash64WithSeeds(const Str& s, uint64_t seed0, uint64_t seed1) {
244
+ assert(sizeof(s[0]) == 1);
245
+ return Hash64WithSeeds(s.data(), s.length(), seed0, seed1);
246
+ }
247
+
248
+ // Hash function for a byte array.
249
+ // May change from time to time, may differ on different platforms, may differ
250
+ // depending on NDEBUG.
251
+ template <typename Str>
252
+ inline uint128_t Hash128(const Str& s) {
253
+ assert(sizeof(s[0]) == 1);
254
+ return Hash128(s.data(), s.length());
255
+ }
256
+
257
+ // Hash function for a byte array. For convenience, a 128-bit seed is also
258
+ // hashed into the result.
259
+ // May change from time to time, may differ on different platforms, may differ
260
+ // depending on NDEBUG.
261
+ template <typename Str>
262
+ inline uint128_t Hash128WithSeed(const Str& s, uint128_t seed) {
263
+ assert(sizeof(s[0]) == 1);
264
+ return Hash128(s.data(), s.length(), seed);
265
+ }
266
+
267
+ // FINGERPRINTING (i.e., good, portable, forever-fixed hash functions)
268
+
269
+ // Fingerprint function for a byte array. Most useful in 32-bit binaries.
270
+ template <typename Str>
271
+ inline uint32_t Fingerprint32(const Str& s) {
272
+ assert(sizeof(s[0]) == 1);
273
+ return Fingerprint32(s.data(), s.length());
274
+ }
275
+
276
+ // Fingerprint 128 input bits down to 64 bits of output.
277
+ // Fingerprint function for a byte array.
278
+ template <typename Str>
279
+ inline uint64_t Fingerprint64(const Str& s) {
280
+ assert(sizeof(s[0]) == 1);
281
+ return Fingerprint64(s.data(), s.length());
282
+ }
283
+
284
+ // Fingerprint function for a byte array.
285
+ template <typename Str>
286
+ inline uint128_t Fingerprint128(const Str& s) {
287
+ assert(sizeof(s[0]) == 1);
288
+ return Fingerprint128(s.data(), s.length());
289
+ }
290
+
291
+ #endif
292
+
293
+ } // namespace NAMESPACE_FOR_HASH_FUNCTIONS
294
+
295
+ /* gently define FARMHASH_BIG_ENDIAN when detected big-endian machine */
296
+ #if defined(__BIG_ENDIAN__)
297
+ #if !defined(FARMHASH_BIG_ENDIAN)
298
+ #define FARMHASH_BIG_ENDIAN
299
+ #endif
300
+ #elif defined(__LITTLE_ENDIAN__)
301
+ // nothing for little-endian
302
+ #elif defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && (__BYTE_ORDER == __ORDER_LITTLE_ENDIAN__)
303
+ // nothing for little-endian
304
+ #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && (__BYTE_ORDER == __ORDER_BIG_ENDIAN__)
305
+ #if !defined(FARMHASH_BIG_ENDIAN)
306
+ #define FARMHASH_BIG_ENDIAN
307
+ #endif
308
+ #elif defined(__linux__) || defined(__CYGWIN__) || defined( __GNUC__ ) && !defined(_WIN32) || defined( __GNU_LIBRARY__ )
309
+ #include <endian.h> // libc6-dev, GLIBC
310
+ #if BYTE_ORDER == BIG_ENDIAN
311
+ #if !defined(FARMHASH_BIG_ENDIAN)
312
+ #define FARMHASH_BIG_ENDIAN
313
+ #endif
314
+ #endif
315
+ #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) || defined(__s390x__)
316
+ #include <sys/endian.h>
317
+ #if BYTE_ORDER == BIG_ENDIAN
318
+ #if !defined(FARMHASH_BIG_ENDIAN)
319
+ #define FARMHASH_BIG_ENDIAN
320
+ #endif
321
+ #endif
322
+ #elif defined(_WIN32)
323
+ // Windows is (currently) little-endian
324
+ #else
325
+ #error "Unable to determine endianness!"
326
+ #endif /* __BIG_ENDIAN__ */
327
+
328
+ #endif // FARM_HASH_H_
deps/exla/cache/xla_extension/include/grpc++/alarm.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ *
3
+ * Copyright 2018 gRPC authors.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ *
17
+ */
18
+
19
+ // DEPRECATED: The headers in include/grpc++ are deprecated. Please include the
20
+ // headers in include/grpcpp instead. This header exists only for backwards
21
+ // compatibility.
22
+
23
+ #ifndef GRPCXX_ALARM_H
24
+ #define GRPCXX_ALARM_H
25
+
26
+ #include <grpcpp/alarm.h>
27
+
28
+ #endif // GRPCXX_ALARM_H
deps/exla/cache/xla_extension/include/grpc++/channel.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ *
3
+ * Copyright 2018 gRPC authors.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ *
17
+ */
18
+
19
+ // DEPRECATED: The headers in include/grpc++ are deprecated. Please include the
20
+ // headers in include/grpcpp instead. This header exists only for backwards
21
+ // compatibility.
22
+
23
+ #ifndef GRPCXX_CHANNEL_H
24
+ #define GRPCXX_CHANNEL_H
25
+
26
+ #include <grpcpp/channel.h>
27
+
28
+ #endif // GRPCXX_CHANNEL_H