18a91bc7bSHarrietAkot //===- SparseTensorUtils.cpp - Sparse Tensor Utils for MLIR execution -----===//
28a91bc7bSHarrietAkot //
38a91bc7bSHarrietAkot // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
48a91bc7bSHarrietAkot // See https://llvm.org/LICENSE.txt for license information.
58a91bc7bSHarrietAkot // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
68a91bc7bSHarrietAkot //
78a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
88a91bc7bSHarrietAkot //
98a91bc7bSHarrietAkot // This file implements a light-weight runtime support library that is useful
108a91bc7bSHarrietAkot // for sparse tensor manipulations. The functionality provided in this library
118a91bc7bSHarrietAkot // is meant to simplify benchmarking, testing, and debugging MLIR code that
128a91bc7bSHarrietAkot // operates on sparse tensors. The provided functionality is **not** part
138a91bc7bSHarrietAkot // of core MLIR, however.
148a91bc7bSHarrietAkot //
158a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
168a91bc7bSHarrietAkot 
17845561ecSwren romano #include "mlir/ExecutionEngine/SparseTensorUtils.h"
188a91bc7bSHarrietAkot #include "mlir/ExecutionEngine/CRunnerUtils.h"
198a91bc7bSHarrietAkot 
208a91bc7bSHarrietAkot #ifdef MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS
218a91bc7bSHarrietAkot 
228a91bc7bSHarrietAkot #include <algorithm>
238a91bc7bSHarrietAkot #include <cassert>
248a91bc7bSHarrietAkot #include <cctype>
258a91bc7bSHarrietAkot #include <cinttypes>
268a91bc7bSHarrietAkot #include <cstdio>
278a91bc7bSHarrietAkot #include <cstdlib>
288a91bc7bSHarrietAkot #include <cstring>
29efa15f41SAart Bik #include <fstream>
30efa15f41SAart Bik #include <iostream>
314d0a18d0Swren romano #include <limits>
328a91bc7bSHarrietAkot #include <numeric>
338a91bc7bSHarrietAkot #include <vector>
348a91bc7bSHarrietAkot 
358a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
368a91bc7bSHarrietAkot //
378a91bc7bSHarrietAkot // Internal support for storing and reading sparse tensors.
388a91bc7bSHarrietAkot //
398a91bc7bSHarrietAkot // The following memory-resident sparse storage schemes are supported:
408a91bc7bSHarrietAkot //
418a91bc7bSHarrietAkot // (a) A coordinate scheme for temporarily storing and lexicographically
428a91bc7bSHarrietAkot //     sorting a sparse tensor by index (SparseTensorCOO).
438a91bc7bSHarrietAkot //
448a91bc7bSHarrietAkot // (b) A "one-size-fits-all" sparse tensor storage scheme defined by
458a91bc7bSHarrietAkot //     per-dimension sparse/dense annnotations together with a dimension
468a91bc7bSHarrietAkot //     ordering used by MLIR compiler-generated code (SparseTensorStorage).
478a91bc7bSHarrietAkot //
488a91bc7bSHarrietAkot // The following external formats are supported:
498a91bc7bSHarrietAkot //
508a91bc7bSHarrietAkot // (1) Matrix Market Exchange (MME): *.mtx
518a91bc7bSHarrietAkot //     https://math.nist.gov/MatrixMarket/formats.html
528a91bc7bSHarrietAkot //
538a91bc7bSHarrietAkot // (2) Formidable Repository of Open Sparse Tensors and Tools (FROSTT): *.tns
548a91bc7bSHarrietAkot //     http://frostt.io/tensors/file-formats.html
558a91bc7bSHarrietAkot //
568a91bc7bSHarrietAkot // Two public APIs are supported:
578a91bc7bSHarrietAkot //
588a91bc7bSHarrietAkot // (I) Methods operating on MLIR buffers (memrefs) to interact with sparse
598a91bc7bSHarrietAkot //     tensors. These methods should be used exclusively by MLIR
608a91bc7bSHarrietAkot //     compiler-generated code.
618a91bc7bSHarrietAkot //
628a91bc7bSHarrietAkot // (II) Methods that accept C-style data structures to interact with sparse
638a91bc7bSHarrietAkot //      tensors. These methods can be used by any external runtime that wants
648a91bc7bSHarrietAkot //      to interact with MLIR compiler-generated code.
658a91bc7bSHarrietAkot //
668a91bc7bSHarrietAkot // In both cases (I) and (II), the SparseTensorStorage format is externally
678a91bc7bSHarrietAkot // only visible as an opaque pointer.
688a91bc7bSHarrietAkot //
698a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
708a91bc7bSHarrietAkot 
718a91bc7bSHarrietAkot namespace {
728a91bc7bSHarrietAkot 
7303fe15ceSAart Bik static constexpr int kColWidth = 1025;
7403fe15ceSAart Bik 
75*72ec2f76Swren romano /// A version of `operator*` on `uint64_t` which checks for overflows.
76*72ec2f76Swren romano static inline uint64_t checkedMul(uint64_t lhs, uint64_t rhs) {
77*72ec2f76Swren romano   assert((lhs == 0 || rhs <= std::numeric_limits<uint64_t>::max() / lhs) &&
78*72ec2f76Swren romano          "Integer overflow");
79*72ec2f76Swren romano   return lhs * rhs;
80*72ec2f76Swren romano }
81*72ec2f76Swren romano 
828a91bc7bSHarrietAkot /// A sparse tensor element in coordinate scheme (value and indices).
838a91bc7bSHarrietAkot /// For example, a rank-1 vector element would look like
848a91bc7bSHarrietAkot ///   ({i}, a[i])
858a91bc7bSHarrietAkot /// and a rank-5 tensor element like
868a91bc7bSHarrietAkot ///   ({i,j,k,l,m}, a[i,j,k,l,m])
878a91bc7bSHarrietAkot template <typename V>
888a91bc7bSHarrietAkot struct Element {
898a91bc7bSHarrietAkot   Element(const std::vector<uint64_t> &ind, V val) : indices(ind), value(val){};
908a91bc7bSHarrietAkot   std::vector<uint64_t> indices;
918a91bc7bSHarrietAkot   V value;
92110295ebSwren romano   /// Returns true if indices of e1 < indices of e2.
93110295ebSwren romano   static bool lexOrder(const Element<V> &e1, const Element<V> &e2) {
94110295ebSwren romano     uint64_t rank = e1.indices.size();
95110295ebSwren romano     assert(rank == e2.indices.size());
96110295ebSwren romano     for (uint64_t r = 0; r < rank; r++) {
97110295ebSwren romano       if (e1.indices[r] == e2.indices[r])
98110295ebSwren romano         continue;
99110295ebSwren romano       return e1.indices[r] < e2.indices[r];
100110295ebSwren romano     }
101110295ebSwren romano     return false;
102110295ebSwren romano   }
1038a91bc7bSHarrietAkot };
1048a91bc7bSHarrietAkot 
1058a91bc7bSHarrietAkot /// A memory-resident sparse tensor in coordinate scheme (collection of
1068a91bc7bSHarrietAkot /// elements). This data structure is used to read a sparse tensor from
1078a91bc7bSHarrietAkot /// any external format into memory and sort the elements lexicographically
1088a91bc7bSHarrietAkot /// by indices before passing it back to the client (most packed storage
1098a91bc7bSHarrietAkot /// formats require the elements to appear in lexicographic index order).
1108a91bc7bSHarrietAkot template <typename V>
1118a91bc7bSHarrietAkot struct SparseTensorCOO {
1128a91bc7bSHarrietAkot public:
1138a91bc7bSHarrietAkot   SparseTensorCOO(const std::vector<uint64_t> &szs, uint64_t capacity)
1148a91bc7bSHarrietAkot       : sizes(szs), iteratorLocked(false), iteratorPos(0) {
1158a91bc7bSHarrietAkot     if (capacity)
1168a91bc7bSHarrietAkot       elements.reserve(capacity);
1178a91bc7bSHarrietAkot   }
1188a91bc7bSHarrietAkot   /// Adds element as indices and value.
1198a91bc7bSHarrietAkot   void add(const std::vector<uint64_t> &ind, V val) {
1208a91bc7bSHarrietAkot     assert(!iteratorLocked && "Attempt to add() after startIterator()");
1218a91bc7bSHarrietAkot     uint64_t rank = getRank();
1228a91bc7bSHarrietAkot     assert(rank == ind.size());
1238a91bc7bSHarrietAkot     for (uint64_t r = 0; r < rank; r++)
1248a91bc7bSHarrietAkot       assert(ind[r] < sizes[r]); // within bounds
1258a91bc7bSHarrietAkot     elements.emplace_back(ind, val);
1268a91bc7bSHarrietAkot   }
1278a91bc7bSHarrietAkot   /// Sorts elements lexicographically by index.
1288a91bc7bSHarrietAkot   void sort() {
1298a91bc7bSHarrietAkot     assert(!iteratorLocked && "Attempt to sort() after startIterator()");
130cf358253Swren romano     // TODO: we may want to cache an `isSorted` bit, to avoid
131cf358253Swren romano     // unnecessary/redundant sorting.
132110295ebSwren romano     std::sort(elements.begin(), elements.end(), Element<V>::lexOrder);
1338a91bc7bSHarrietAkot   }
1348a91bc7bSHarrietAkot   /// Returns rank.
1358a91bc7bSHarrietAkot   uint64_t getRank() const { return sizes.size(); }
1368a91bc7bSHarrietAkot   /// Getter for sizes array.
1378a91bc7bSHarrietAkot   const std::vector<uint64_t> &getSizes() const { return sizes; }
1388a91bc7bSHarrietAkot   /// Getter for elements array.
1398a91bc7bSHarrietAkot   const std::vector<Element<V>> &getElements() const { return elements; }
1408a91bc7bSHarrietAkot 
1418a91bc7bSHarrietAkot   /// Switch into iterator mode.
1428a91bc7bSHarrietAkot   void startIterator() {
1438a91bc7bSHarrietAkot     iteratorLocked = true;
1448a91bc7bSHarrietAkot     iteratorPos = 0;
1458a91bc7bSHarrietAkot   }
1468a91bc7bSHarrietAkot   /// Get the next element.
1478a91bc7bSHarrietAkot   const Element<V> *getNext() {
1488a91bc7bSHarrietAkot     assert(iteratorLocked && "Attempt to getNext() before startIterator()");
1498a91bc7bSHarrietAkot     if (iteratorPos < elements.size())
1508a91bc7bSHarrietAkot       return &(elements[iteratorPos++]);
1518a91bc7bSHarrietAkot     iteratorLocked = false;
1528a91bc7bSHarrietAkot     return nullptr;
1538a91bc7bSHarrietAkot   }
1548a91bc7bSHarrietAkot 
1558a91bc7bSHarrietAkot   /// Factory method. Permutes the original dimensions according to
1568a91bc7bSHarrietAkot   /// the given ordering and expects subsequent add() calls to honor
1578a91bc7bSHarrietAkot   /// that same ordering for the given indices. The result is a
1588a91bc7bSHarrietAkot   /// fully permuted coordinate scheme.
1598a91bc7bSHarrietAkot   static SparseTensorCOO<V> *newSparseTensorCOO(uint64_t rank,
1608a91bc7bSHarrietAkot                                                 const uint64_t *sizes,
1618a91bc7bSHarrietAkot                                                 const uint64_t *perm,
1628a91bc7bSHarrietAkot                                                 uint64_t capacity = 0) {
1638a91bc7bSHarrietAkot     std::vector<uint64_t> permsz(rank);
164d83a7068Swren romano     for (uint64_t r = 0; r < rank; r++) {
165d83a7068Swren romano       assert(sizes[r] > 0 && "Dimension size zero has trivial storage");
1668a91bc7bSHarrietAkot       permsz[perm[r]] = sizes[r];
167d83a7068Swren romano     }
1688a91bc7bSHarrietAkot     return new SparseTensorCOO<V>(permsz, capacity);
1698a91bc7bSHarrietAkot   }
1708a91bc7bSHarrietAkot 
1718a91bc7bSHarrietAkot private:
1728a91bc7bSHarrietAkot   const std::vector<uint64_t> sizes; // per-dimension sizes
1738a91bc7bSHarrietAkot   std::vector<Element<V>> elements;
1748a91bc7bSHarrietAkot   bool iteratorLocked;
1758a91bc7bSHarrietAkot   unsigned iteratorPos;
1768a91bc7bSHarrietAkot };
1778a91bc7bSHarrietAkot 
1788a91bc7bSHarrietAkot /// Abstract base class of sparse tensor storage. Note that we use
1798a91bc7bSHarrietAkot /// function overloading to implement "partial" method specialization.
1808a91bc7bSHarrietAkot class SparseTensorStorageBase {
1818a91bc7bSHarrietAkot public:
1824f2ec7f9SAart Bik   /// Dimension size query.
18346bdacaaSwren romano   virtual uint64_t getDimSize(uint64_t) const = 0;
1848a91bc7bSHarrietAkot 
1854f2ec7f9SAart Bik   /// Overhead storage.
1868a91bc7bSHarrietAkot   virtual void getPointers(std::vector<uint64_t> **, uint64_t) { fatal("p64"); }
1878a91bc7bSHarrietAkot   virtual void getPointers(std::vector<uint32_t> **, uint64_t) { fatal("p32"); }
1888a91bc7bSHarrietAkot   virtual void getPointers(std::vector<uint16_t> **, uint64_t) { fatal("p16"); }
1898a91bc7bSHarrietAkot   virtual void getPointers(std::vector<uint8_t> **, uint64_t) { fatal("p8"); }
1908a91bc7bSHarrietAkot   virtual void getIndices(std::vector<uint64_t> **, uint64_t) { fatal("i64"); }
1918a91bc7bSHarrietAkot   virtual void getIndices(std::vector<uint32_t> **, uint64_t) { fatal("i32"); }
1928a91bc7bSHarrietAkot   virtual void getIndices(std::vector<uint16_t> **, uint64_t) { fatal("i16"); }
1938a91bc7bSHarrietAkot   virtual void getIndices(std::vector<uint8_t> **, uint64_t) { fatal("i8"); }
1948a91bc7bSHarrietAkot 
1954f2ec7f9SAart Bik   /// Primary storage.
1968a91bc7bSHarrietAkot   virtual void getValues(std::vector<double> **) { fatal("valf64"); }
1978a91bc7bSHarrietAkot   virtual void getValues(std::vector<float> **) { fatal("valf32"); }
1988a91bc7bSHarrietAkot   virtual void getValues(std::vector<int64_t> **) { fatal("vali64"); }
1998a91bc7bSHarrietAkot   virtual void getValues(std::vector<int32_t> **) { fatal("vali32"); }
2008a91bc7bSHarrietAkot   virtual void getValues(std::vector<int16_t> **) { fatal("vali16"); }
2018a91bc7bSHarrietAkot   virtual void getValues(std::vector<int8_t> **) { fatal("vali8"); }
2028a91bc7bSHarrietAkot 
2034f2ec7f9SAart Bik   /// Element-wise insertion in lexicographic index order.
204c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, double) { fatal("insf64"); }
205c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, float) { fatal("insf32"); }
206c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, int64_t) { fatal("insi64"); }
207c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, int32_t) { fatal("insi32"); }
208c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, int16_t) { fatal("ins16"); }
209c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, int8_t) { fatal("insi8"); }
2104f2ec7f9SAart Bik 
2114f2ec7f9SAart Bik   /// Expanded insertion.
2124f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, double *, bool *, uint64_t *, uint64_t) {
2134f2ec7f9SAart Bik     fatal("expf64");
2144f2ec7f9SAart Bik   }
2154f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, float *, bool *, uint64_t *, uint64_t) {
2164f2ec7f9SAart Bik     fatal("expf32");
2174f2ec7f9SAart Bik   }
2184f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, int64_t *, bool *, uint64_t *, uint64_t) {
2194f2ec7f9SAart Bik     fatal("expi64");
2204f2ec7f9SAart Bik   }
2214f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, int32_t *, bool *, uint64_t *, uint64_t) {
2224f2ec7f9SAart Bik     fatal("expi32");
2234f2ec7f9SAart Bik   }
2244f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, int16_t *, bool *, uint64_t *, uint64_t) {
2254f2ec7f9SAart Bik     fatal("expi16");
2264f2ec7f9SAart Bik   }
2274f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, int8_t *, bool *, uint64_t *, uint64_t) {
2284f2ec7f9SAart Bik     fatal("expi8");
2294f2ec7f9SAart Bik   }
2304f2ec7f9SAart Bik 
2314f2ec7f9SAart Bik   /// Finishes insertion.
232f66e5769SAart Bik   virtual void endInsert() = 0;
233f66e5769SAart Bik 
234e5639b3fSMehdi Amini   virtual ~SparseTensorStorageBase() = default;
2358a91bc7bSHarrietAkot 
2368a91bc7bSHarrietAkot private:
23746bdacaaSwren romano   static void fatal(const char *tp) {
2388a91bc7bSHarrietAkot     fprintf(stderr, "unsupported %s\n", tp);
2398a91bc7bSHarrietAkot     exit(1);
2408a91bc7bSHarrietAkot   }
2418a91bc7bSHarrietAkot };
2428a91bc7bSHarrietAkot 
2438a91bc7bSHarrietAkot /// A memory-resident sparse tensor using a storage scheme based on
2448a91bc7bSHarrietAkot /// per-dimension sparse/dense annotations. This data structure provides a
2458a91bc7bSHarrietAkot /// bufferized form of a sparse tensor type. In contrast to generating setup
2468a91bc7bSHarrietAkot /// methods for each differently annotated sparse tensor, this method provides
2478a91bc7bSHarrietAkot /// a convenient "one-size-fits-all" solution that simply takes an input tensor
2488a91bc7bSHarrietAkot /// and annotations to implement all required setup in a general manner.
2498a91bc7bSHarrietAkot template <typename P, typename I, typename V>
2508a91bc7bSHarrietAkot class SparseTensorStorage : public SparseTensorStorageBase {
2518a91bc7bSHarrietAkot public:
2528a91bc7bSHarrietAkot   /// Constructs a sparse tensor storage scheme with the given dimensions,
2538a91bc7bSHarrietAkot   /// permutation, and per-dimension dense/sparse annotations, using
2548a91bc7bSHarrietAkot   /// the coordinate scheme tensor for the initial contents if provided.
2558a91bc7bSHarrietAkot   SparseTensorStorage(const std::vector<uint64_t> &szs, const uint64_t *perm,
256f66e5769SAart Bik                       const DimLevelType *sparsity,
257f66e5769SAart Bik                       SparseTensorCOO<V> *tensor = nullptr)
258f66e5769SAart Bik       : sizes(szs), rev(getRank()), idx(getRank()), pointers(getRank()),
259f66e5769SAart Bik         indices(getRank()) {
2608a91bc7bSHarrietAkot     uint64_t rank = getRank();
2618a91bc7bSHarrietAkot     // Store "reverse" permutation.
2628a91bc7bSHarrietAkot     for (uint64_t r = 0; r < rank; r++)
2638a91bc7bSHarrietAkot       rev[perm[r]] = r;
2648a91bc7bSHarrietAkot     // Provide hints on capacity of pointers and indices.
2658a91bc7bSHarrietAkot     // TODO: needs fine-tuning based on sparsity
266f66e5769SAart Bik     bool allDense = true;
267f66e5769SAart Bik     uint64_t sz = 1;
268f66e5769SAart Bik     for (uint64_t r = 0; r < rank; r++) {
2694d0a18d0Swren romano       assert(sizes[r] > 0 && "Dimension size zero has trivial storage");
270*72ec2f76Swren romano       sz = checkedMul(sz, sizes[r]);
271845561ecSwren romano       if (sparsity[r] == DimLevelType::kCompressed) {
272f66e5769SAart Bik         pointers[r].reserve(sz + 1);
273f66e5769SAart Bik         indices[r].reserve(sz);
274f66e5769SAart Bik         sz = 1;
275f66e5769SAart Bik         allDense = false;
276289f84a4Swren romano         // Prepare the pointer structure.  We cannot use `appendPointer`
2774d0a18d0Swren romano         // here, because `isCompressedDim` won't work until after this
2784d0a18d0Swren romano         // preparation has been done.
2794d0a18d0Swren romano         pointers[r].push_back(0);
2808a91bc7bSHarrietAkot       } else {
281845561ecSwren romano         assert(sparsity[r] == DimLevelType::kDense &&
282845561ecSwren romano                "singleton not yet supported");
2838a91bc7bSHarrietAkot       }
2848a91bc7bSHarrietAkot     }
2858a91bc7bSHarrietAkot     // Then assign contents from coordinate scheme tensor if provided.
2868a91bc7bSHarrietAkot     if (tensor) {
2874d0a18d0Swren romano       // Ensure both preconditions of `fromCOO`.
2884d0a18d0Swren romano       assert(tensor->getSizes() == sizes && "Tensor size mismatch");
289cf358253Swren romano       tensor->sort();
2904d0a18d0Swren romano       // Now actually insert the `elements`.
291ceda1ae9Swren romano       const std::vector<Element<V>> &elements = tensor->getElements();
292ceda1ae9Swren romano       uint64_t nnz = elements.size();
2938a91bc7bSHarrietAkot       values.reserve(nnz);
294ceda1ae9Swren romano       fromCOO(elements, 0, nnz, 0);
2951ce77b56SAart Bik     } else if (allDense) {
296f66e5769SAart Bik       values.resize(sz, 0);
2978a91bc7bSHarrietAkot     }
2988a91bc7bSHarrietAkot   }
2998a91bc7bSHarrietAkot 
3000ae2e958SMehdi Amini   ~SparseTensorStorage() override = default;
3018a91bc7bSHarrietAkot 
3028a91bc7bSHarrietAkot   /// Get the rank of the tensor.
3038a91bc7bSHarrietAkot   uint64_t getRank() const { return sizes.size(); }
3048a91bc7bSHarrietAkot 
30546bdacaaSwren romano   /// Get the size of the given dimension of the tensor.
30646bdacaaSwren romano   uint64_t getDimSize(uint64_t d) const override {
3078a91bc7bSHarrietAkot     assert(d < getRank());
3088a91bc7bSHarrietAkot     return sizes[d];
3098a91bc7bSHarrietAkot   }
3108a91bc7bSHarrietAkot 
311f66e5769SAart Bik   /// Partially specialize these getter methods based on template types.
3128a91bc7bSHarrietAkot   void getPointers(std::vector<P> **out, uint64_t d) override {
3138a91bc7bSHarrietAkot     assert(d < getRank());
3148a91bc7bSHarrietAkot     *out = &pointers[d];
3158a91bc7bSHarrietAkot   }
3168a91bc7bSHarrietAkot   void getIndices(std::vector<I> **out, uint64_t d) override {
3178a91bc7bSHarrietAkot     assert(d < getRank());
3188a91bc7bSHarrietAkot     *out = &indices[d];
3198a91bc7bSHarrietAkot   }
3208a91bc7bSHarrietAkot   void getValues(std::vector<V> **out) override { *out = &values; }
3218a91bc7bSHarrietAkot 
32203fe15ceSAart Bik   /// Partially specialize lexicographical insertions based on template types.
323c03fd1e6Swren romano   void lexInsert(const uint64_t *cursor, V val) override {
3241ce77b56SAart Bik     // First, wrap up pending insertion path.
3251ce77b56SAart Bik     uint64_t diff = 0;
3261ce77b56SAart Bik     uint64_t top = 0;
3271ce77b56SAart Bik     if (!values.empty()) {
3281ce77b56SAart Bik       diff = lexDiff(cursor);
3291ce77b56SAart Bik       endPath(diff + 1);
3301ce77b56SAart Bik       top = idx[diff] + 1;
3311ce77b56SAart Bik     }
3321ce77b56SAart Bik     // Then continue with insertion path.
3331ce77b56SAart Bik     insPath(cursor, diff, top, val);
334f66e5769SAart Bik   }
335f66e5769SAart Bik 
3364f2ec7f9SAart Bik   /// Partially specialize expanded insertions based on template types.
3374f2ec7f9SAart Bik   /// Note that this method resets the values/filled-switch array back
3384f2ec7f9SAart Bik   /// to all-zero/false while only iterating over the nonzero elements.
3394f2ec7f9SAart Bik   void expInsert(uint64_t *cursor, V *values, bool *filled, uint64_t *added,
3404f2ec7f9SAart Bik                  uint64_t count) override {
3414f2ec7f9SAart Bik     if (count == 0)
3424f2ec7f9SAart Bik       return;
3434f2ec7f9SAart Bik     // Sort.
3444f2ec7f9SAart Bik     std::sort(added, added + count);
3454f2ec7f9SAart Bik     // Restore insertion path for first insert.
3463bf2ba3bSwren romano     const uint64_t lastDim = getRank() - 1;
3474f2ec7f9SAart Bik     uint64_t index = added[0];
3483bf2ba3bSwren romano     cursor[lastDim] = index;
3494f2ec7f9SAart Bik     lexInsert(cursor, values[index]);
3504f2ec7f9SAart Bik     assert(filled[index]);
3514f2ec7f9SAart Bik     values[index] = 0;
3524f2ec7f9SAart Bik     filled[index] = false;
3534f2ec7f9SAart Bik     // Subsequent insertions are quick.
3544f2ec7f9SAart Bik     for (uint64_t i = 1; i < count; i++) {
3554f2ec7f9SAart Bik       assert(index < added[i] && "non-lexicographic insertion");
3564f2ec7f9SAart Bik       index = added[i];
3573bf2ba3bSwren romano       cursor[lastDim] = index;
3583bf2ba3bSwren romano       insPath(cursor, lastDim, added[i - 1] + 1, values[index]);
3594f2ec7f9SAart Bik       assert(filled[index]);
3603bf2ba3bSwren romano       values[index] = 0;
3614f2ec7f9SAart Bik       filled[index] = false;
3624f2ec7f9SAart Bik     }
3634f2ec7f9SAart Bik   }
3644f2ec7f9SAart Bik 
365f66e5769SAart Bik   /// Finalizes lexicographic insertions.
3661ce77b56SAart Bik   void endInsert() override {
3671ce77b56SAart Bik     if (values.empty())
368*72ec2f76Swren romano       finalizeSegment(0);
3691ce77b56SAart Bik     else
3701ce77b56SAart Bik       endPath(0);
3711ce77b56SAart Bik   }
372f66e5769SAart Bik 
3738a91bc7bSHarrietAkot   /// Returns this sparse tensor storage scheme as a new memory-resident
3748a91bc7bSHarrietAkot   /// sparse tensor in coordinate scheme with the given dimension order.
3758a91bc7bSHarrietAkot   SparseTensorCOO<V> *toCOO(const uint64_t *perm) {
3768a91bc7bSHarrietAkot     // Restore original order of the dimension sizes and allocate coordinate
3778a91bc7bSHarrietAkot     // scheme with desired new ordering specified in perm.
3788a91bc7bSHarrietAkot     uint64_t rank = getRank();
3798a91bc7bSHarrietAkot     std::vector<uint64_t> orgsz(rank);
3808a91bc7bSHarrietAkot     for (uint64_t r = 0; r < rank; r++)
3818a91bc7bSHarrietAkot       orgsz[rev[r]] = sizes[r];
3828a91bc7bSHarrietAkot     SparseTensorCOO<V> *tensor = SparseTensorCOO<V>::newSparseTensorCOO(
3838a91bc7bSHarrietAkot         rank, orgsz.data(), perm, values.size());
3848a91bc7bSHarrietAkot     // Populate coordinate scheme restored from old ordering and changed with
3858a91bc7bSHarrietAkot     // new ordering. Rather than applying both reorderings during the recursion,
3868a91bc7bSHarrietAkot     // we compute the combine permutation in advance.
3878a91bc7bSHarrietAkot     std::vector<uint64_t> reord(rank);
3888a91bc7bSHarrietAkot     for (uint64_t r = 0; r < rank; r++)
3898a91bc7bSHarrietAkot       reord[r] = perm[rev[r]];
390ceda1ae9Swren romano     toCOO(*tensor, reord, 0, 0);
3918a91bc7bSHarrietAkot     assert(tensor->getElements().size() == values.size());
3928a91bc7bSHarrietAkot     return tensor;
3938a91bc7bSHarrietAkot   }
3948a91bc7bSHarrietAkot 
3958a91bc7bSHarrietAkot   /// Factory method. Constructs a sparse tensor storage scheme with the given
3968a91bc7bSHarrietAkot   /// dimensions, permutation, and per-dimension dense/sparse annotations,
3978a91bc7bSHarrietAkot   /// using the coordinate scheme tensor for the initial contents if provided.
3988a91bc7bSHarrietAkot   /// In the latter case, the coordinate scheme must respect the same
3998a91bc7bSHarrietAkot   /// permutation as is desired for the new sparse tensor storage.
4008a91bc7bSHarrietAkot   static SparseTensorStorage<P, I, V> *
401d83a7068Swren romano   newSparseTensor(uint64_t rank, const uint64_t *shape, const uint64_t *perm,
402845561ecSwren romano                   const DimLevelType *sparsity, SparseTensorCOO<V> *tensor) {
4038a91bc7bSHarrietAkot     SparseTensorStorage<P, I, V> *n = nullptr;
4048a91bc7bSHarrietAkot     if (tensor) {
4058a91bc7bSHarrietAkot       assert(tensor->getRank() == rank);
4068a91bc7bSHarrietAkot       for (uint64_t r = 0; r < rank; r++)
407d83a7068Swren romano         assert(shape[r] == 0 || shape[r] == tensor->getSizes()[perm[r]]);
4088a91bc7bSHarrietAkot       n = new SparseTensorStorage<P, I, V>(tensor->getSizes(), perm, sparsity,
4098a91bc7bSHarrietAkot                                            tensor);
4108a91bc7bSHarrietAkot     } else {
4118a91bc7bSHarrietAkot       std::vector<uint64_t> permsz(rank);
412d83a7068Swren romano       for (uint64_t r = 0; r < rank; r++) {
413d83a7068Swren romano         assert(shape[r] > 0 && "Dimension size zero has trivial storage");
414d83a7068Swren romano         permsz[perm[r]] = shape[r];
415d83a7068Swren romano       }
416f66e5769SAart Bik       n = new SparseTensorStorage<P, I, V>(permsz, perm, sparsity);
4178a91bc7bSHarrietAkot     }
4188a91bc7bSHarrietAkot     return n;
4198a91bc7bSHarrietAkot   }
4208a91bc7bSHarrietAkot 
4218a91bc7bSHarrietAkot private:
422*72ec2f76Swren romano   /// Appends an arbitrary new position to `pointers[d]`.  This method
423*72ec2f76Swren romano   /// checks that `pos` is representable in the `P` type; however, it
424*72ec2f76Swren romano   /// does not check that `pos` is semantically valid (i.e., larger than
425*72ec2f76Swren romano   /// the previous position and smaller than `indices[d].capacity()`).
426*72ec2f76Swren romano   inline void appendPointer(uint64_t d, uint64_t pos, uint64_t count = 1) {
427*72ec2f76Swren romano     assert(isCompressedDim(d));
428*72ec2f76Swren romano     assert(pos <= std::numeric_limits<P>::max() &&
4294d0a18d0Swren romano            "Pointer value is too large for the P-type");
430*72ec2f76Swren romano     pointers[d].insert(pointers[d].end(), count, static_cast<P>(pos));
4314d0a18d0Swren romano   }
4324d0a18d0Swren romano 
433*72ec2f76Swren romano   /// Appends index `i` to dimension `d`, in the semantically general
434*72ec2f76Swren romano   /// sense.  For non-dense dimensions, that means appending to the
435*72ec2f76Swren romano   /// `indices[d]` array, checking that `i` is representable in the `I`
436*72ec2f76Swren romano   /// type; however, we do not verify other semantic requirements (e.g.,
437*72ec2f76Swren romano   /// that `i` is in bounds for `sizes[d]`, and not previously occurring
438*72ec2f76Swren romano   /// in the same segment).  For dense dimensions, this method instead
439*72ec2f76Swren romano   /// appends the appropriate number of zeros to the `values` array,
440*72ec2f76Swren romano   /// where `full` is the number of "entries" already written to `values`
441*72ec2f76Swren romano   /// for this segment (aka one after the highest index previously appended).
442*72ec2f76Swren romano   void appendIndex(uint64_t d, uint64_t full, uint64_t i) {
443*72ec2f76Swren romano     if (isCompressedDim(d)) {
4444d0a18d0Swren romano       assert(i <= std::numeric_limits<I>::max() &&
4454d0a18d0Swren romano              "Index value is too large for the I-type");
446*72ec2f76Swren romano       indices[d].push_back(static_cast<I>(i));
447*72ec2f76Swren romano     } else { // Dense dimension.
448*72ec2f76Swren romano       assert(i >= full && "Index was already filled");
449*72ec2f76Swren romano       if (i == full)
450*72ec2f76Swren romano         return; // Short-circuit, since it'll be a nop.
451*72ec2f76Swren romano       if (d + 1 == getRank())
452*72ec2f76Swren romano         values.insert(values.end(), i - full, 0);
453*72ec2f76Swren romano       else
454*72ec2f76Swren romano         finalizeSegment(d + 1, 0, i - full);
455*72ec2f76Swren romano     }
4564d0a18d0Swren romano   }
4574d0a18d0Swren romano 
4588a91bc7bSHarrietAkot   /// Initializes sparse tensor storage scheme from a memory-resident sparse
4598a91bc7bSHarrietAkot   /// tensor in coordinate scheme. This method prepares the pointers and
4608a91bc7bSHarrietAkot   /// indices arrays under the given per-dimension dense/sparse annotations.
4614d0a18d0Swren romano   ///
4624d0a18d0Swren romano   /// Preconditions:
4634d0a18d0Swren romano   /// (1) the `elements` must be lexicographically sorted.
4644d0a18d0Swren romano   /// (2) the indices of every element are valid for `sizes` (equal rank
4654d0a18d0Swren romano   ///     and pointwise less-than).
466ceda1ae9Swren romano   void fromCOO(const std::vector<Element<V>> &elements, uint64_t lo,
467ceda1ae9Swren romano                uint64_t hi, uint64_t d) {
4688a91bc7bSHarrietAkot     // Once dimensions are exhausted, insert the numerical values.
469c4017f9dSwren romano     assert(d <= getRank() && hi <= elements.size());
4708a91bc7bSHarrietAkot     if (d == getRank()) {
471c4017f9dSwren romano       assert(lo < hi);
4721ce77b56SAart Bik       values.push_back(elements[lo].value);
4738a91bc7bSHarrietAkot       return;
4748a91bc7bSHarrietAkot     }
4758a91bc7bSHarrietAkot     // Visit all elements in this interval.
4768a91bc7bSHarrietAkot     uint64_t full = 0;
477c4017f9dSwren romano     while (lo < hi) { // If `hi` is unchanged, then `lo < elements.size()`.
4788a91bc7bSHarrietAkot       // Find segment in interval with same index elements in this dimension.
479f66e5769SAart Bik       uint64_t i = elements[lo].indices[d];
4808a91bc7bSHarrietAkot       uint64_t seg = lo + 1;
481f66e5769SAart Bik       while (seg < hi && elements[seg].indices[d] == i)
4828a91bc7bSHarrietAkot         seg++;
4838a91bc7bSHarrietAkot       // Handle segment in interval for sparse or dense dimension.
484*72ec2f76Swren romano       appendIndex(d, full, i);
485*72ec2f76Swren romano       full = i + 1;
486ceda1ae9Swren romano       fromCOO(elements, lo, seg, d + 1);
4878a91bc7bSHarrietAkot       // And move on to next segment in interval.
4888a91bc7bSHarrietAkot       lo = seg;
4898a91bc7bSHarrietAkot     }
4908a91bc7bSHarrietAkot     // Finalize the sparse pointer structure at this dimension.
491*72ec2f76Swren romano     finalizeSegment(d, full);
4928a91bc7bSHarrietAkot   }
4938a91bc7bSHarrietAkot 
4948a91bc7bSHarrietAkot   /// Stores the sparse tensor storage scheme into a memory-resident sparse
4958a91bc7bSHarrietAkot   /// tensor in coordinate scheme.
496ceda1ae9Swren romano   void toCOO(SparseTensorCOO<V> &tensor, std::vector<uint64_t> &reord,
497f66e5769SAart Bik              uint64_t pos, uint64_t d) {
4988a91bc7bSHarrietAkot     assert(d <= getRank());
4998a91bc7bSHarrietAkot     if (d == getRank()) {
5008a91bc7bSHarrietAkot       assert(pos < values.size());
501ceda1ae9Swren romano       tensor.add(idx, values[pos]);
5021ce77b56SAart Bik     } else if (isCompressedDim(d)) {
5038a91bc7bSHarrietAkot       // Sparse dimension.
5048a91bc7bSHarrietAkot       for (uint64_t ii = pointers[d][pos]; ii < pointers[d][pos + 1]; ii++) {
5058a91bc7bSHarrietAkot         idx[reord[d]] = indices[d][ii];
506f66e5769SAart Bik         toCOO(tensor, reord, ii, d + 1);
5078a91bc7bSHarrietAkot       }
5081ce77b56SAart Bik     } else {
5091ce77b56SAart Bik       // Dense dimension.
5101ce77b56SAart Bik       for (uint64_t i = 0, sz = sizes[d], off = pos * sz; i < sz; i++) {
5111ce77b56SAart Bik         idx[reord[d]] = i;
5121ce77b56SAart Bik         toCOO(tensor, reord, off + i, d + 1);
5138a91bc7bSHarrietAkot       }
5148a91bc7bSHarrietAkot     }
5151ce77b56SAart Bik   }
5161ce77b56SAart Bik 
517*72ec2f76Swren romano   /// Finalize the sparse pointer structure at this dimension.
518*72ec2f76Swren romano   void finalizeSegment(uint64_t d, uint64_t full = 0, uint64_t count = 1) {
519*72ec2f76Swren romano     if (count == 0)
520*72ec2f76Swren romano       return; // Short-circuit, since it'll be a nop.
521*72ec2f76Swren romano     if (isCompressedDim(d)) {
522*72ec2f76Swren romano       appendPointer(d, indices[d].size(), count);
523*72ec2f76Swren romano     } else { // Dense dimension.
524*72ec2f76Swren romano       const uint64_t sz = sizes[d];
525*72ec2f76Swren romano       assert(sz >= full && "Segment is overfull");
526*72ec2f76Swren romano       // Assuming we checked for overflows in the constructor, then this
527*72ec2f76Swren romano       // multiply will never overflow.
528*72ec2f76Swren romano       count *= (sz - full);
529*72ec2f76Swren romano       // For dense storage we must enumerate all the remaining coordinates
530*72ec2f76Swren romano       // in this dimension (i.e., coordinates after the last non-zero
531*72ec2f76Swren romano       // element), and either fill in their zero values or else recurse
532*72ec2f76Swren romano       // to finalize some deeper dimension.
533*72ec2f76Swren romano       if (d + 1 == getRank())
534*72ec2f76Swren romano         values.insert(values.end(), count, 0);
535*72ec2f76Swren romano       else
536*72ec2f76Swren romano         finalizeSegment(d + 1, 0, count);
5371ce77b56SAart Bik     }
5381ce77b56SAart Bik   }
5391ce77b56SAart Bik 
5401ce77b56SAart Bik   /// Wraps up a single insertion path, inner to outer.
5411ce77b56SAart Bik   void endPath(uint64_t diff) {
5421ce77b56SAart Bik     uint64_t rank = getRank();
5431ce77b56SAart Bik     assert(diff <= rank);
5441ce77b56SAart Bik     for (uint64_t i = 0; i < rank - diff; i++) {
545*72ec2f76Swren romano       const uint64_t d = rank - i - 1;
546*72ec2f76Swren romano       finalizeSegment(d, idx[d] + 1);
5471ce77b56SAart Bik     }
5481ce77b56SAart Bik   }
5491ce77b56SAart Bik 
5501ce77b56SAart Bik   /// Continues a single insertion path, outer to inner.
551c03fd1e6Swren romano   void insPath(const uint64_t *cursor, uint64_t diff, uint64_t top, V val) {
5521ce77b56SAart Bik     uint64_t rank = getRank();
5531ce77b56SAart Bik     assert(diff < rank);
5541ce77b56SAart Bik     for (uint64_t d = diff; d < rank; d++) {
5551ce77b56SAart Bik       uint64_t i = cursor[d];
556*72ec2f76Swren romano       appendIndex(d, top, i);
5571ce77b56SAart Bik       top = 0;
5581ce77b56SAart Bik       idx[d] = i;
5591ce77b56SAart Bik     }
5601ce77b56SAart Bik     values.push_back(val);
5611ce77b56SAart Bik   }
5621ce77b56SAart Bik 
5631ce77b56SAart Bik   /// Finds the lexicographic differing dimension.
56446bdacaaSwren romano   uint64_t lexDiff(const uint64_t *cursor) const {
5651ce77b56SAart Bik     for (uint64_t r = 0, rank = getRank(); r < rank; r++)
5661ce77b56SAart Bik       if (cursor[r] > idx[r])
5671ce77b56SAart Bik         return r;
5681ce77b56SAart Bik       else
5691ce77b56SAart Bik         assert(cursor[r] == idx[r] && "non-lexicographic insertion");
5701ce77b56SAart Bik     assert(0 && "duplication insertion");
5711ce77b56SAart Bik     return -1u;
5721ce77b56SAart Bik   }
5731ce77b56SAart Bik 
5741ce77b56SAart Bik   /// Returns true if dimension is compressed.
5751ce77b56SAart Bik   inline bool isCompressedDim(uint64_t d) const {
5764d0a18d0Swren romano     assert(d < getRank());
5771ce77b56SAart Bik     return (!pointers[d].empty());
5781ce77b56SAart Bik   }
5798a91bc7bSHarrietAkot 
5808a91bc7bSHarrietAkot private:
58146bdacaaSwren romano   const std::vector<uint64_t> sizes; // per-dimension sizes
5828a91bc7bSHarrietAkot   std::vector<uint64_t> rev;   // "reverse" permutation
583f66e5769SAart Bik   std::vector<uint64_t> idx;   // index cursor
5848a91bc7bSHarrietAkot   std::vector<std::vector<P>> pointers;
5858a91bc7bSHarrietAkot   std::vector<std::vector<I>> indices;
5868a91bc7bSHarrietAkot   std::vector<V> values;
5878a91bc7bSHarrietAkot };
5888a91bc7bSHarrietAkot 
5898a91bc7bSHarrietAkot /// Helper to convert string to lower case.
5908a91bc7bSHarrietAkot static char *toLower(char *token) {
5918a91bc7bSHarrietAkot   for (char *c = token; *c; c++)
5928a91bc7bSHarrietAkot     *c = tolower(*c);
5938a91bc7bSHarrietAkot   return token;
5948a91bc7bSHarrietAkot }
5958a91bc7bSHarrietAkot 
5968a91bc7bSHarrietAkot /// Read the MME header of a general sparse matrix of type real.
59703fe15ceSAart Bik static void readMMEHeader(FILE *file, char *filename, char *line,
598bb56c2b3SMehdi Amini                           uint64_t *idata, bool *isSymmetric) {
5998a91bc7bSHarrietAkot   char header[64];
6008a91bc7bSHarrietAkot   char object[64];
6018a91bc7bSHarrietAkot   char format[64];
6028a91bc7bSHarrietAkot   char field[64];
6038a91bc7bSHarrietAkot   char symmetry[64];
6048a91bc7bSHarrietAkot   // Read header line.
6058a91bc7bSHarrietAkot   if (fscanf(file, "%63s %63s %63s %63s %63s\n", header, object, format, field,
6068a91bc7bSHarrietAkot              symmetry) != 5) {
60703fe15ceSAart Bik     fprintf(stderr, "Corrupt header in %s\n", filename);
6088a91bc7bSHarrietAkot     exit(1);
6098a91bc7bSHarrietAkot   }
610bb56c2b3SMehdi Amini   *isSymmetric = (strcmp(toLower(symmetry), "symmetric") == 0);
6118a91bc7bSHarrietAkot   // Make sure this is a general sparse matrix.
6128a91bc7bSHarrietAkot   if (strcmp(toLower(header), "%%matrixmarket") ||
6138a91bc7bSHarrietAkot       strcmp(toLower(object), "matrix") ||
6148a91bc7bSHarrietAkot       strcmp(toLower(format), "coordinate") || strcmp(toLower(field), "real") ||
615bb56c2b3SMehdi Amini       (strcmp(toLower(symmetry), "general") && !(*isSymmetric))) {
6168a91bc7bSHarrietAkot     fprintf(stderr,
61703fe15ceSAart Bik             "Cannot find a general sparse matrix with type real in %s\n",
61803fe15ceSAart Bik             filename);
6198a91bc7bSHarrietAkot     exit(1);
6208a91bc7bSHarrietAkot   }
6218a91bc7bSHarrietAkot   // Skip comments.
622e5639b3fSMehdi Amini   while (true) {
62303fe15ceSAart Bik     if (!fgets(line, kColWidth, file)) {
62403fe15ceSAart Bik       fprintf(stderr, "Cannot find data in %s\n", filename);
6258a91bc7bSHarrietAkot       exit(1);
6268a91bc7bSHarrietAkot     }
6278a91bc7bSHarrietAkot     if (line[0] != '%')
6288a91bc7bSHarrietAkot       break;
6298a91bc7bSHarrietAkot   }
6308a91bc7bSHarrietAkot   // Next line contains M N NNZ.
6318a91bc7bSHarrietAkot   idata[0] = 2; // rank
6328a91bc7bSHarrietAkot   if (sscanf(line, "%" PRIu64 "%" PRIu64 "%" PRIu64 "\n", idata + 2, idata + 3,
6338a91bc7bSHarrietAkot              idata + 1) != 3) {
63403fe15ceSAart Bik     fprintf(stderr, "Cannot find size in %s\n", filename);
6358a91bc7bSHarrietAkot     exit(1);
6368a91bc7bSHarrietAkot   }
6378a91bc7bSHarrietAkot }
6388a91bc7bSHarrietAkot 
6398a91bc7bSHarrietAkot /// Read the "extended" FROSTT header. Although not part of the documented
6408a91bc7bSHarrietAkot /// format, we assume that the file starts with optional comments followed
6418a91bc7bSHarrietAkot /// by two lines that define the rank, the number of nonzeros, and the
6428a91bc7bSHarrietAkot /// dimensions sizes (one per rank) of the sparse tensor.
64303fe15ceSAart Bik static void readExtFROSTTHeader(FILE *file, char *filename, char *line,
64403fe15ceSAart Bik                                 uint64_t *idata) {
6458a91bc7bSHarrietAkot   // Skip comments.
646e5639b3fSMehdi Amini   while (true) {
64703fe15ceSAart Bik     if (!fgets(line, kColWidth, file)) {
64803fe15ceSAart Bik       fprintf(stderr, "Cannot find data in %s\n", filename);
6498a91bc7bSHarrietAkot       exit(1);
6508a91bc7bSHarrietAkot     }
6518a91bc7bSHarrietAkot     if (line[0] != '#')
6528a91bc7bSHarrietAkot       break;
6538a91bc7bSHarrietAkot   }
6548a91bc7bSHarrietAkot   // Next line contains RANK and NNZ.
6558a91bc7bSHarrietAkot   if (sscanf(line, "%" PRIu64 "%" PRIu64 "\n", idata, idata + 1) != 2) {
65603fe15ceSAart Bik     fprintf(stderr, "Cannot find metadata in %s\n", filename);
6578a91bc7bSHarrietAkot     exit(1);
6588a91bc7bSHarrietAkot   }
6598a91bc7bSHarrietAkot   // Followed by a line with the dimension sizes (one per rank).
6608a91bc7bSHarrietAkot   for (uint64_t r = 0; r < idata[0]; r++) {
6618a91bc7bSHarrietAkot     if (fscanf(file, "%" PRIu64, idata + 2 + r) != 1) {
66203fe15ceSAart Bik       fprintf(stderr, "Cannot find dimension size %s\n", filename);
6638a91bc7bSHarrietAkot       exit(1);
6648a91bc7bSHarrietAkot     }
6658a91bc7bSHarrietAkot   }
66603fe15ceSAart Bik   fgets(line, kColWidth, file); // end of line
6678a91bc7bSHarrietAkot }
6688a91bc7bSHarrietAkot 
6698a91bc7bSHarrietAkot /// Reads a sparse tensor with the given filename into a memory-resident
6708a91bc7bSHarrietAkot /// sparse tensor in coordinate scheme.
6718a91bc7bSHarrietAkot template <typename V>
6728a91bc7bSHarrietAkot static SparseTensorCOO<V> *openSparseTensorCOO(char *filename, uint64_t rank,
673d83a7068Swren romano                                                const uint64_t *shape,
6748a91bc7bSHarrietAkot                                                const uint64_t *perm) {
6758a91bc7bSHarrietAkot   // Open the file.
6768a91bc7bSHarrietAkot   FILE *file = fopen(filename, "r");
6778a91bc7bSHarrietAkot   if (!file) {
6783734c078Swren romano     assert(filename && "Received nullptr for filename");
6793734c078Swren romano     fprintf(stderr, "Cannot find file %s\n", filename);
6808a91bc7bSHarrietAkot     exit(1);
6818a91bc7bSHarrietAkot   }
6828a91bc7bSHarrietAkot   // Perform some file format dependent set up.
68303fe15ceSAart Bik   char line[kColWidth];
6848a91bc7bSHarrietAkot   uint64_t idata[512];
685bb56c2b3SMehdi Amini   bool isSymmetric = false;
6868a91bc7bSHarrietAkot   if (strstr(filename, ".mtx")) {
687bb56c2b3SMehdi Amini     readMMEHeader(file, filename, line, idata, &isSymmetric);
6888a91bc7bSHarrietAkot   } else if (strstr(filename, ".tns")) {
68903fe15ceSAart Bik     readExtFROSTTHeader(file, filename, line, idata);
6908a91bc7bSHarrietAkot   } else {
6918a91bc7bSHarrietAkot     fprintf(stderr, "Unknown format %s\n", filename);
6928a91bc7bSHarrietAkot     exit(1);
6938a91bc7bSHarrietAkot   }
6948a91bc7bSHarrietAkot   // Prepare sparse tensor object with per-dimension sizes
6958a91bc7bSHarrietAkot   // and the number of nonzeros as initial capacity.
6968a91bc7bSHarrietAkot   assert(rank == idata[0] && "rank mismatch");
6978a91bc7bSHarrietAkot   uint64_t nnz = idata[1];
6988a91bc7bSHarrietAkot   for (uint64_t r = 0; r < rank; r++)
699d83a7068Swren romano     assert((shape[r] == 0 || shape[r] == idata[2 + r]) &&
7008a91bc7bSHarrietAkot            "dimension size mismatch");
7018a91bc7bSHarrietAkot   SparseTensorCOO<V> *tensor =
7028a91bc7bSHarrietAkot       SparseTensorCOO<V>::newSparseTensorCOO(rank, idata + 2, perm, nnz);
7038a91bc7bSHarrietAkot   //  Read all nonzero elements.
7048a91bc7bSHarrietAkot   std::vector<uint64_t> indices(rank);
7058a91bc7bSHarrietAkot   for (uint64_t k = 0; k < nnz; k++) {
70603fe15ceSAart Bik     if (!fgets(line, kColWidth, file)) {
70703fe15ceSAart Bik       fprintf(stderr, "Cannot find next line of data in %s\n", filename);
7088a91bc7bSHarrietAkot       exit(1);
7098a91bc7bSHarrietAkot     }
71003fe15ceSAart Bik     char *linePtr = line;
71103fe15ceSAart Bik     for (uint64_t r = 0; r < rank; r++) {
71203fe15ceSAart Bik       uint64_t idx = strtoul(linePtr, &linePtr, 10);
7138a91bc7bSHarrietAkot       // Add 0-based index.
7148a91bc7bSHarrietAkot       indices[perm[r]] = idx - 1;
7158a91bc7bSHarrietAkot     }
7168a91bc7bSHarrietAkot     // The external formats always store the numerical values with the type
7178a91bc7bSHarrietAkot     // double, but we cast these values to the sparse tensor object type.
71803fe15ceSAart Bik     double value = strtod(linePtr, &linePtr);
7198a91bc7bSHarrietAkot     tensor->add(indices, value);
72002710413SBixia Zheng     // We currently chose to deal with symmetric matrices by fully constructing
72102710413SBixia Zheng     // them. In the future, we may want to make symmetry implicit for storage
72202710413SBixia Zheng     // reasons.
723bb56c2b3SMehdi Amini     if (isSymmetric && indices[0] != indices[1])
72402710413SBixia Zheng       tensor->add({indices[1], indices[0]}, value);
7258a91bc7bSHarrietAkot   }
7268a91bc7bSHarrietAkot   // Close the file and return tensor.
7278a91bc7bSHarrietAkot   fclose(file);
7288a91bc7bSHarrietAkot   return tensor;
7298a91bc7bSHarrietAkot }
7308a91bc7bSHarrietAkot 
731efa15f41SAart Bik /// Writes the sparse tensor to extended FROSTT format.
732efa15f41SAart Bik template <typename V>
73346bdacaaSwren romano static void outSparseTensor(void *tensor, void *dest, bool sort) {
7346438783fSAart Bik   assert(tensor && dest);
7356438783fSAart Bik   auto coo = static_cast<SparseTensorCOO<V> *>(tensor);
7366438783fSAart Bik   if (sort)
7376438783fSAart Bik     coo->sort();
7386438783fSAart Bik   char *filename = static_cast<char *>(dest);
7396438783fSAart Bik   auto &sizes = coo->getSizes();
7406438783fSAart Bik   auto &elements = coo->getElements();
7416438783fSAart Bik   uint64_t rank = coo->getRank();
742efa15f41SAart Bik   uint64_t nnz = elements.size();
743efa15f41SAart Bik   std::fstream file;
744efa15f41SAart Bik   file.open(filename, std::ios_base::out | std::ios_base::trunc);
745efa15f41SAart Bik   assert(file.is_open());
746efa15f41SAart Bik   file << "; extended FROSTT format\n" << rank << " " << nnz << std::endl;
747efa15f41SAart Bik   for (uint64_t r = 0; r < rank - 1; r++)
748efa15f41SAart Bik     file << sizes[r] << " ";
749efa15f41SAart Bik   file << sizes[rank - 1] << std::endl;
750efa15f41SAart Bik   for (uint64_t i = 0; i < nnz; i++) {
751efa15f41SAart Bik     auto &idx = elements[i].indices;
752efa15f41SAart Bik     for (uint64_t r = 0; r < rank; r++)
753efa15f41SAart Bik       file << (idx[r] + 1) << " ";
754efa15f41SAart Bik     file << elements[i].value << std::endl;
755efa15f41SAart Bik   }
756efa15f41SAart Bik   file.flush();
757efa15f41SAart Bik   file.close();
758efa15f41SAart Bik   assert(file.good());
7596438783fSAart Bik }
7606438783fSAart Bik 
7616438783fSAart Bik /// Initializes sparse tensor from an external COO-flavored format.
7626438783fSAart Bik template <typename V>
76346bdacaaSwren romano static SparseTensorStorage<uint64_t, uint64_t, V> *
7646438783fSAart Bik toMLIRSparseTensor(uint64_t rank, uint64_t nse, uint64_t *shape, V *values,
76520eaa88fSBixia Zheng                    uint64_t *indices, uint64_t *perm, uint8_t *sparse) {
76620eaa88fSBixia Zheng   const DimLevelType *sparsity = (DimLevelType *)(sparse);
76720eaa88fSBixia Zheng #ifndef NDEBUG
76820eaa88fSBixia Zheng   // Verify that perm is a permutation of 0..(rank-1).
76920eaa88fSBixia Zheng   std::vector<uint64_t> order(perm, perm + rank);
77020eaa88fSBixia Zheng   std::sort(order.begin(), order.end());
7711e47888dSAart Bik   for (uint64_t i = 0; i < rank; ++i) {
77220eaa88fSBixia Zheng     if (i != order[i]) {
773988d4b0dSAart Bik       fprintf(stderr, "Not a permutation of 0..%" PRIu64 "\n", rank);
77420eaa88fSBixia Zheng       exit(1);
77520eaa88fSBixia Zheng     }
77620eaa88fSBixia Zheng   }
77720eaa88fSBixia Zheng 
77820eaa88fSBixia Zheng   // Verify that the sparsity values are supported.
7791e47888dSAart Bik   for (uint64_t i = 0; i < rank; ++i) {
78020eaa88fSBixia Zheng     if (sparsity[i] != DimLevelType::kDense &&
78120eaa88fSBixia Zheng         sparsity[i] != DimLevelType::kCompressed) {
78220eaa88fSBixia Zheng       fprintf(stderr, "Unsupported sparsity value %d\n",
78320eaa88fSBixia Zheng               static_cast<int>(sparsity[i]));
78420eaa88fSBixia Zheng       exit(1);
78520eaa88fSBixia Zheng     }
78620eaa88fSBixia Zheng   }
78720eaa88fSBixia Zheng #endif
78820eaa88fSBixia Zheng 
7896438783fSAart Bik   // Convert external format to internal COO.
79063bdcaf9Swren romano   auto *coo = SparseTensorCOO<V>::newSparseTensorCOO(rank, shape, perm, nse);
7916438783fSAart Bik   std::vector<uint64_t> idx(rank);
7926438783fSAart Bik   for (uint64_t i = 0, base = 0; i < nse; i++) {
7936438783fSAart Bik     for (uint64_t r = 0; r < rank; r++)
794d8b229a1SAart Bik       idx[perm[r]] = indices[base + r];
79563bdcaf9Swren romano     coo->add(idx, values[i]);
7966438783fSAart Bik     base += rank;
7976438783fSAart Bik   }
7986438783fSAart Bik   // Return sparse tensor storage format as opaque pointer.
79963bdcaf9Swren romano   auto *tensor = SparseTensorStorage<uint64_t, uint64_t, V>::newSparseTensor(
80063bdcaf9Swren romano       rank, shape, perm, sparsity, coo);
80163bdcaf9Swren romano   delete coo;
80263bdcaf9Swren romano   return tensor;
8036438783fSAart Bik }
8046438783fSAart Bik 
8056438783fSAart Bik /// Converts a sparse tensor to an external COO-flavored format.
8066438783fSAart Bik template <typename V>
80746bdacaaSwren romano static void fromMLIRSparseTensor(void *tensor, uint64_t *pRank, uint64_t *pNse,
80846bdacaaSwren romano                                  uint64_t **pShape, V **pValues,
80946bdacaaSwren romano                                  uint64_t **pIndices) {
8106438783fSAart Bik   auto sparseTensor =
8116438783fSAart Bik       static_cast<SparseTensorStorage<uint64_t, uint64_t, V> *>(tensor);
8126438783fSAart Bik   uint64_t rank = sparseTensor->getRank();
8136438783fSAart Bik   std::vector<uint64_t> perm(rank);
8146438783fSAart Bik   std::iota(perm.begin(), perm.end(), 0);
8156438783fSAart Bik   SparseTensorCOO<V> *coo = sparseTensor->toCOO(perm.data());
8166438783fSAart Bik 
8176438783fSAart Bik   const std::vector<Element<V>> &elements = coo->getElements();
8186438783fSAart Bik   uint64_t nse = elements.size();
8196438783fSAart Bik 
8206438783fSAart Bik   uint64_t *shape = new uint64_t[rank];
8216438783fSAart Bik   for (uint64_t i = 0; i < rank; i++)
8226438783fSAart Bik     shape[i] = coo->getSizes()[i];
8236438783fSAart Bik 
8246438783fSAart Bik   V *values = new V[nse];
8256438783fSAart Bik   uint64_t *indices = new uint64_t[rank * nse];
8266438783fSAart Bik 
8276438783fSAart Bik   for (uint64_t i = 0, base = 0; i < nse; i++) {
8286438783fSAart Bik     values[i] = elements[i].value;
8296438783fSAart Bik     for (uint64_t j = 0; j < rank; j++)
8306438783fSAart Bik       indices[base + j] = elements[i].indices[j];
8316438783fSAart Bik     base += rank;
8326438783fSAart Bik   }
8336438783fSAart Bik 
8346438783fSAart Bik   delete coo;
8356438783fSAart Bik   *pRank = rank;
8366438783fSAart Bik   *pNse = nse;
8376438783fSAart Bik   *pShape = shape;
8386438783fSAart Bik   *pValues = values;
8396438783fSAart Bik   *pIndices = indices;
840efa15f41SAart Bik }
841efa15f41SAart Bik 
842be0a7e9fSMehdi Amini } // namespace
8438a91bc7bSHarrietAkot 
8448a91bc7bSHarrietAkot extern "C" {
8458a91bc7bSHarrietAkot 
8468a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
8478a91bc7bSHarrietAkot //
8488a91bc7bSHarrietAkot // Public API with methods that operate on MLIR buffers (memrefs) to interact
8498a91bc7bSHarrietAkot // with sparse tensors, which are only visible as opaque pointers externally.
8508a91bc7bSHarrietAkot // These methods should be used exclusively by MLIR compiler-generated code.
8518a91bc7bSHarrietAkot //
8528a91bc7bSHarrietAkot // Some macro magic is used to generate implementations for all required type
8538a91bc7bSHarrietAkot // combinations that can be called from MLIR compiler-generated code.
8548a91bc7bSHarrietAkot //
8558a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
8568a91bc7bSHarrietAkot 
8578a91bc7bSHarrietAkot #define CASE(p, i, v, P, I, V)                                                 \
8588a91bc7bSHarrietAkot   if (ptrTp == (p) && indTp == (i) && valTp == (v)) {                          \
85963bdcaf9Swren romano     SparseTensorCOO<V> *coo = nullptr;                                         \
860845561ecSwren romano     if (action <= Action::kFromCOO) {                                          \
861845561ecSwren romano       if (action == Action::kFromFile) {                                       \
8628a91bc7bSHarrietAkot         char *filename = static_cast<char *>(ptr);                             \
86363bdcaf9Swren romano         coo = openSparseTensorCOO<V>(filename, rank, shape, perm);             \
864845561ecSwren romano       } else if (action == Action::kFromCOO) {                                 \
86563bdcaf9Swren romano         coo = static_cast<SparseTensorCOO<V> *>(ptr);                          \
8668a91bc7bSHarrietAkot       } else {                                                                 \
867845561ecSwren romano         assert(action == Action::kEmpty);                                      \
8688a91bc7bSHarrietAkot       }                                                                        \
86963bdcaf9Swren romano       auto *tensor = SparseTensorStorage<P, I, V>::newSparseTensor(            \
87063bdcaf9Swren romano           rank, shape, perm, sparsity, coo);                                   \
87163bdcaf9Swren romano       if (action == Action::kFromFile)                                         \
87263bdcaf9Swren romano         delete coo;                                                            \
87363bdcaf9Swren romano       return tensor;                                                           \
874bb56c2b3SMehdi Amini     }                                                                          \
875bb56c2b3SMehdi Amini     if (action == Action::kEmptyCOO)                                           \
876d83a7068Swren romano       return SparseTensorCOO<V>::newSparseTensorCOO(rank, shape, perm);        \
87763bdcaf9Swren romano     coo = static_cast<SparseTensorStorage<P, I, V> *>(ptr)->toCOO(perm);       \
878845561ecSwren romano     if (action == Action::kToIterator) {                                       \
87963bdcaf9Swren romano       coo->startIterator();                                                    \
8808a91bc7bSHarrietAkot     } else {                                                                   \
881845561ecSwren romano       assert(action == Action::kToCOO);                                        \
8828a91bc7bSHarrietAkot     }                                                                          \
88363bdcaf9Swren romano     return coo;                                                                \
8848a91bc7bSHarrietAkot   }
8858a91bc7bSHarrietAkot 
886845561ecSwren romano #define CASE_SECSAME(p, v, P, V) CASE(p, p, v, P, P, V)
887845561ecSwren romano 
8888a91bc7bSHarrietAkot #define IMPL_SPARSEVALUES(NAME, TYPE, LIB)                                     \
8898a91bc7bSHarrietAkot   void _mlir_ciface_##NAME(StridedMemRefType<TYPE, 1> *ref, void *tensor) {    \
8904f2ec7f9SAart Bik     assert(ref &&tensor);                                                      \
8918a91bc7bSHarrietAkot     std::vector<TYPE> *v;                                                      \
8928a91bc7bSHarrietAkot     static_cast<SparseTensorStorageBase *>(tensor)->LIB(&v);                   \
8938a91bc7bSHarrietAkot     ref->basePtr = ref->data = v->data();                                      \
8948a91bc7bSHarrietAkot     ref->offset = 0;                                                           \
8958a91bc7bSHarrietAkot     ref->sizes[0] = v->size();                                                 \
8968a91bc7bSHarrietAkot     ref->strides[0] = 1;                                                       \
8978a91bc7bSHarrietAkot   }
8988a91bc7bSHarrietAkot 
8998a91bc7bSHarrietAkot #define IMPL_GETOVERHEAD(NAME, TYPE, LIB)                                      \
9008a91bc7bSHarrietAkot   void _mlir_ciface_##NAME(StridedMemRefType<TYPE, 1> *ref, void *tensor,      \
901d2215e79SRainer Orth                            index_type d) {                                     \
9024f2ec7f9SAart Bik     assert(ref &&tensor);                                                      \
9038a91bc7bSHarrietAkot     std::vector<TYPE> *v;                                                      \
9048a91bc7bSHarrietAkot     static_cast<SparseTensorStorageBase *>(tensor)->LIB(&v, d);                \
9058a91bc7bSHarrietAkot     ref->basePtr = ref->data = v->data();                                      \
9068a91bc7bSHarrietAkot     ref->offset = 0;                                                           \
9078a91bc7bSHarrietAkot     ref->sizes[0] = v->size();                                                 \
9088a91bc7bSHarrietAkot     ref->strides[0] = 1;                                                       \
9098a91bc7bSHarrietAkot   }
9108a91bc7bSHarrietAkot 
9118a91bc7bSHarrietAkot #define IMPL_ADDELT(NAME, TYPE)                                                \
9128a91bc7bSHarrietAkot   void *_mlir_ciface_##NAME(void *tensor, TYPE value,                          \
913d2215e79SRainer Orth                             StridedMemRefType<index_type, 1> *iref,            \
914d2215e79SRainer Orth                             StridedMemRefType<index_type, 1> *pref) {          \
9154f2ec7f9SAart Bik     assert(tensor &&iref &&pref);                                              \
9168a91bc7bSHarrietAkot     assert(iref->strides[0] == 1 && pref->strides[0] == 1);                    \
9178a91bc7bSHarrietAkot     assert(iref->sizes[0] == pref->sizes[0]);                                  \
918d2215e79SRainer Orth     const index_type *indx = iref->data + iref->offset;                        \
919d2215e79SRainer Orth     const index_type *perm = pref->data + pref->offset;                        \
9208a91bc7bSHarrietAkot     uint64_t isize = iref->sizes[0];                                           \
921d2215e79SRainer Orth     std::vector<index_type> indices(isize);                                    \
9228a91bc7bSHarrietAkot     for (uint64_t r = 0; r < isize; r++)                                       \
9238a91bc7bSHarrietAkot       indices[perm[r]] = indx[r];                                              \
9248a91bc7bSHarrietAkot     static_cast<SparseTensorCOO<TYPE> *>(tensor)->add(indices, value);         \
9258a91bc7bSHarrietAkot     return tensor;                                                             \
9268a91bc7bSHarrietAkot   }
9278a91bc7bSHarrietAkot 
9288a91bc7bSHarrietAkot #define IMPL_GETNEXT(NAME, V)                                                  \
929d2215e79SRainer Orth   bool _mlir_ciface_##NAME(void *tensor,                                       \
930d2215e79SRainer Orth                            StridedMemRefType<index_type, 1> *iref,             \
9318a91bc7bSHarrietAkot                            StridedMemRefType<V, 0> *vref) {                    \
9324f2ec7f9SAart Bik     assert(tensor &&iref &&vref);                                              \
9338a91bc7bSHarrietAkot     assert(iref->strides[0] == 1);                                             \
934d2215e79SRainer Orth     index_type *indx = iref->data + iref->offset;                              \
935c9f2beffSMehdi Amini     V *value = vref->data + vref->offset;                                      \
9368a91bc7bSHarrietAkot     const uint64_t isize = iref->sizes[0];                                     \
9378a91bc7bSHarrietAkot     auto iter = static_cast<SparseTensorCOO<V> *>(tensor);                     \
9388a91bc7bSHarrietAkot     const Element<V> *elem = iter->getNext();                                  \
93963bdcaf9Swren romano     if (elem == nullptr)                                                       \
9408a91bc7bSHarrietAkot       return false;                                                            \
9418a91bc7bSHarrietAkot     for (uint64_t r = 0; r < isize; r++)                                       \
9428a91bc7bSHarrietAkot       indx[r] = elem->indices[r];                                              \
9438a91bc7bSHarrietAkot     *value = elem->value;                                                      \
9448a91bc7bSHarrietAkot     return true;                                                               \
9458a91bc7bSHarrietAkot   }
9468a91bc7bSHarrietAkot 
947f66e5769SAart Bik #define IMPL_LEXINSERT(NAME, V)                                                \
948d2215e79SRainer Orth   void _mlir_ciface_##NAME(void *tensor,                                       \
949d2215e79SRainer Orth                            StridedMemRefType<index_type, 1> *cref, V val) {    \
9504f2ec7f9SAart Bik     assert(tensor &&cref);                                                     \
951f66e5769SAart Bik     assert(cref->strides[0] == 1);                                             \
952d2215e79SRainer Orth     index_type *cursor = cref->data + cref->offset;                            \
953f66e5769SAart Bik     assert(cursor);                                                            \
954f66e5769SAart Bik     static_cast<SparseTensorStorageBase *>(tensor)->lexInsert(cursor, val);    \
955f66e5769SAart Bik   }
956f66e5769SAart Bik 
9574f2ec7f9SAart Bik #define IMPL_EXPINSERT(NAME, V)                                                \
9584f2ec7f9SAart Bik   void _mlir_ciface_##NAME(                                                    \
959d2215e79SRainer Orth       void *tensor, StridedMemRefType<index_type, 1> *cref,                    \
9604f2ec7f9SAart Bik       StridedMemRefType<V, 1> *vref, StridedMemRefType<bool, 1> *fref,         \
961d2215e79SRainer Orth       StridedMemRefType<index_type, 1> *aref, index_type count) {              \
9624f2ec7f9SAart Bik     assert(tensor &&cref &&vref &&fref &&aref);                                \
9634f2ec7f9SAart Bik     assert(cref->strides[0] == 1);                                             \
9644f2ec7f9SAart Bik     assert(vref->strides[0] == 1);                                             \
9654f2ec7f9SAart Bik     assert(fref->strides[0] == 1);                                             \
9664f2ec7f9SAart Bik     assert(aref->strides[0] == 1);                                             \
9674f2ec7f9SAart Bik     assert(vref->sizes[0] == fref->sizes[0]);                                  \
968d2215e79SRainer Orth     index_type *cursor = cref->data + cref->offset;                            \
969c9f2beffSMehdi Amini     V *values = vref->data + vref->offset;                                     \
9704f2ec7f9SAart Bik     bool *filled = fref->data + fref->offset;                                  \
971d2215e79SRainer Orth     index_type *added = aref->data + aref->offset;                             \
9724f2ec7f9SAart Bik     static_cast<SparseTensorStorageBase *>(tensor)->expInsert(                 \
9734f2ec7f9SAart Bik         cursor, values, filled, added, count);                                 \
9744f2ec7f9SAart Bik   }
9754f2ec7f9SAart Bik 
976d2215e79SRainer Orth // Assume index_type is in fact uint64_t, so that _mlir_ciface_newSparseTensor
977bc04a470Swren romano // can safely rewrite kIndex to kU64.  We make this assertion to guarantee
978bc04a470Swren romano // that this file cannot get out of sync with its header.
979d2215e79SRainer Orth static_assert(std::is_same<index_type, uint64_t>::value,
980d2215e79SRainer Orth               "Expected index_type == uint64_t");
981bc04a470Swren romano 
9828a91bc7bSHarrietAkot /// Constructs a new sparse tensor. This is the "swiss army knife"
9838a91bc7bSHarrietAkot /// method for materializing sparse tensors into the computation.
9848a91bc7bSHarrietAkot ///
985845561ecSwren romano /// Action:
9868a91bc7bSHarrietAkot /// kEmpty = returns empty storage to fill later
9878a91bc7bSHarrietAkot /// kFromFile = returns storage, where ptr contains filename to read
9888a91bc7bSHarrietAkot /// kFromCOO = returns storage, where ptr contains coordinate scheme to assign
9898a91bc7bSHarrietAkot /// kEmptyCOO = returns empty coordinate scheme to fill and use with kFromCOO
9908a91bc7bSHarrietAkot /// kToCOO = returns coordinate scheme from storage in ptr to use with kFromCOO
991845561ecSwren romano /// kToIterator = returns iterator from storage in ptr (call getNext() to use)
9928a91bc7bSHarrietAkot void *
993845561ecSwren romano _mlir_ciface_newSparseTensor(StridedMemRefType<DimLevelType, 1> *aref, // NOLINT
994d2215e79SRainer Orth                              StridedMemRefType<index_type, 1> *sref,
995d2215e79SRainer Orth                              StridedMemRefType<index_type, 1> *pref,
996845561ecSwren romano                              OverheadType ptrTp, OverheadType indTp,
997845561ecSwren romano                              PrimaryType valTp, Action action, void *ptr) {
9988a91bc7bSHarrietAkot   assert(aref && sref && pref);
9998a91bc7bSHarrietAkot   assert(aref->strides[0] == 1 && sref->strides[0] == 1 &&
10008a91bc7bSHarrietAkot          pref->strides[0] == 1);
10018a91bc7bSHarrietAkot   assert(aref->sizes[0] == sref->sizes[0] && sref->sizes[0] == pref->sizes[0]);
1002845561ecSwren romano   const DimLevelType *sparsity = aref->data + aref->offset;
1003d83a7068Swren romano   const index_type *shape = sref->data + sref->offset;
1004d2215e79SRainer Orth   const index_type *perm = pref->data + pref->offset;
10058a91bc7bSHarrietAkot   uint64_t rank = aref->sizes[0];
10068a91bc7bSHarrietAkot 
1007bc04a470Swren romano   // Rewrite kIndex to kU64, to avoid introducing a bunch of new cases.
1008bc04a470Swren romano   // This is safe because of the static_assert above.
1009bc04a470Swren romano   if (ptrTp == OverheadType::kIndex)
1010bc04a470Swren romano     ptrTp = OverheadType::kU64;
1011bc04a470Swren romano   if (indTp == OverheadType::kIndex)
1012bc04a470Swren romano     indTp = OverheadType::kU64;
1013bc04a470Swren romano 
10148a91bc7bSHarrietAkot   // Double matrices with all combinations of overhead storage.
1015845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU64, PrimaryType::kF64, uint64_t,
1016845561ecSwren romano        uint64_t, double);
1017845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU32, PrimaryType::kF64, uint64_t,
1018845561ecSwren romano        uint32_t, double);
1019845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU16, PrimaryType::kF64, uint64_t,
1020845561ecSwren romano        uint16_t, double);
1021845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU8, PrimaryType::kF64, uint64_t,
1022845561ecSwren romano        uint8_t, double);
1023845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU64, PrimaryType::kF64, uint32_t,
1024845561ecSwren romano        uint64_t, double);
1025845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU32, PrimaryType::kF64, uint32_t,
1026845561ecSwren romano        uint32_t, double);
1027845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU16, PrimaryType::kF64, uint32_t,
1028845561ecSwren romano        uint16_t, double);
1029845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU8, PrimaryType::kF64, uint32_t,
1030845561ecSwren romano        uint8_t, double);
1031845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU64, PrimaryType::kF64, uint16_t,
1032845561ecSwren romano        uint64_t, double);
1033845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU32, PrimaryType::kF64, uint16_t,
1034845561ecSwren romano        uint32_t, double);
1035845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU16, PrimaryType::kF64, uint16_t,
1036845561ecSwren romano        uint16_t, double);
1037845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU8, PrimaryType::kF64, uint16_t,
1038845561ecSwren romano        uint8_t, double);
1039845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU64, PrimaryType::kF64, uint8_t,
1040845561ecSwren romano        uint64_t, double);
1041845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU32, PrimaryType::kF64, uint8_t,
1042845561ecSwren romano        uint32_t, double);
1043845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU16, PrimaryType::kF64, uint8_t,
1044845561ecSwren romano        uint16_t, double);
1045845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU8, PrimaryType::kF64, uint8_t,
1046845561ecSwren romano        uint8_t, double);
10478a91bc7bSHarrietAkot 
10488a91bc7bSHarrietAkot   // Float matrices with all combinations of overhead storage.
1049845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU64, PrimaryType::kF32, uint64_t,
1050845561ecSwren romano        uint64_t, float);
1051845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU32, PrimaryType::kF32, uint64_t,
1052845561ecSwren romano        uint32_t, float);
1053845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU16, PrimaryType::kF32, uint64_t,
1054845561ecSwren romano        uint16_t, float);
1055845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU8, PrimaryType::kF32, uint64_t,
1056845561ecSwren romano        uint8_t, float);
1057845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU64, PrimaryType::kF32, uint32_t,
1058845561ecSwren romano        uint64_t, float);
1059845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU32, PrimaryType::kF32, uint32_t,
1060845561ecSwren romano        uint32_t, float);
1061845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU16, PrimaryType::kF32, uint32_t,
1062845561ecSwren romano        uint16_t, float);
1063845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU8, PrimaryType::kF32, uint32_t,
1064845561ecSwren romano        uint8_t, float);
1065845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU64, PrimaryType::kF32, uint16_t,
1066845561ecSwren romano        uint64_t, float);
1067845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU32, PrimaryType::kF32, uint16_t,
1068845561ecSwren romano        uint32_t, float);
1069845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU16, PrimaryType::kF32, uint16_t,
1070845561ecSwren romano        uint16_t, float);
1071845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU8, PrimaryType::kF32, uint16_t,
1072845561ecSwren romano        uint8_t, float);
1073845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU64, PrimaryType::kF32, uint8_t,
1074845561ecSwren romano        uint64_t, float);
1075845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU32, PrimaryType::kF32, uint8_t,
1076845561ecSwren romano        uint32_t, float);
1077845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU16, PrimaryType::kF32, uint8_t,
1078845561ecSwren romano        uint16_t, float);
1079845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU8, PrimaryType::kF32, uint8_t,
1080845561ecSwren romano        uint8_t, float);
10818a91bc7bSHarrietAkot 
1082845561ecSwren romano   // Integral matrices with both overheads of the same type.
1083845561ecSwren romano   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI64, uint64_t, int64_t);
1084845561ecSwren romano   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI32, uint64_t, int32_t);
1085845561ecSwren romano   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI16, uint64_t, int16_t);
1086845561ecSwren romano   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI8, uint64_t, int8_t);
1087845561ecSwren romano   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI32, uint32_t, int32_t);
1088845561ecSwren romano   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI16, uint32_t, int16_t);
1089845561ecSwren romano   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI8, uint32_t, int8_t);
1090845561ecSwren romano   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI32, uint16_t, int32_t);
1091845561ecSwren romano   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI16, uint16_t, int16_t);
1092845561ecSwren romano   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI8, uint16_t, int8_t);
1093845561ecSwren romano   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI32, uint8_t, int32_t);
1094845561ecSwren romano   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI16, uint8_t, int16_t);
1095845561ecSwren romano   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI8, uint8_t, int8_t);
10968a91bc7bSHarrietAkot 
10978a91bc7bSHarrietAkot   // Unsupported case (add above if needed).
10988a91bc7bSHarrietAkot   fputs("unsupported combination of types\n", stderr);
10998a91bc7bSHarrietAkot   exit(1);
11008a91bc7bSHarrietAkot }
11018a91bc7bSHarrietAkot 
11028a91bc7bSHarrietAkot /// Methods that provide direct access to pointers.
1103d2215e79SRainer Orth IMPL_GETOVERHEAD(sparsePointers, index_type, getPointers)
11048a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparsePointers64, uint64_t, getPointers)
11058a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparsePointers32, uint32_t, getPointers)
11068a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparsePointers16, uint16_t, getPointers)
11078a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparsePointers8, uint8_t, getPointers)
11088a91bc7bSHarrietAkot 
11098a91bc7bSHarrietAkot /// Methods that provide direct access to indices.
1110d2215e79SRainer Orth IMPL_GETOVERHEAD(sparseIndices, index_type, getIndices)
11118a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparseIndices64, uint64_t, getIndices)
11128a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparseIndices32, uint32_t, getIndices)
11138a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparseIndices16, uint16_t, getIndices)
11148a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparseIndices8, uint8_t, getIndices)
11158a91bc7bSHarrietAkot 
11168a91bc7bSHarrietAkot /// Methods that provide direct access to values.
11178a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesF64, double, getValues)
11188a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesF32, float, getValues)
11198a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesI64, int64_t, getValues)
11208a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesI32, int32_t, getValues)
11218a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesI16, int16_t, getValues)
11228a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesI8, int8_t, getValues)
11238a91bc7bSHarrietAkot 
11248a91bc7bSHarrietAkot /// Helper to add value to coordinate scheme, one per value type.
11258a91bc7bSHarrietAkot IMPL_ADDELT(addEltF64, double)
11268a91bc7bSHarrietAkot IMPL_ADDELT(addEltF32, float)
11278a91bc7bSHarrietAkot IMPL_ADDELT(addEltI64, int64_t)
11288a91bc7bSHarrietAkot IMPL_ADDELT(addEltI32, int32_t)
11298a91bc7bSHarrietAkot IMPL_ADDELT(addEltI16, int16_t)
11308a91bc7bSHarrietAkot IMPL_ADDELT(addEltI8, int8_t)
11318a91bc7bSHarrietAkot 
11328a91bc7bSHarrietAkot /// Helper to enumerate elements of coordinate scheme, one per value type.
11338a91bc7bSHarrietAkot IMPL_GETNEXT(getNextF64, double)
11348a91bc7bSHarrietAkot IMPL_GETNEXT(getNextF32, float)
11358a91bc7bSHarrietAkot IMPL_GETNEXT(getNextI64, int64_t)
11368a91bc7bSHarrietAkot IMPL_GETNEXT(getNextI32, int32_t)
11378a91bc7bSHarrietAkot IMPL_GETNEXT(getNextI16, int16_t)
11388a91bc7bSHarrietAkot IMPL_GETNEXT(getNextI8, int8_t)
11398a91bc7bSHarrietAkot 
11406438783fSAart Bik /// Insert elements in lexicographical index order, one per value type.
1141f66e5769SAart Bik IMPL_LEXINSERT(lexInsertF64, double)
1142f66e5769SAart Bik IMPL_LEXINSERT(lexInsertF32, float)
1143f66e5769SAart Bik IMPL_LEXINSERT(lexInsertI64, int64_t)
1144f66e5769SAart Bik IMPL_LEXINSERT(lexInsertI32, int32_t)
1145f66e5769SAart Bik IMPL_LEXINSERT(lexInsertI16, int16_t)
1146f66e5769SAart Bik IMPL_LEXINSERT(lexInsertI8, int8_t)
1147f66e5769SAart Bik 
11486438783fSAart Bik /// Insert using expansion, one per value type.
11494f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertF64, double)
11504f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertF32, float)
11514f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertI64, int64_t)
11524f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertI32, int32_t)
11534f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertI16, int16_t)
11544f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertI8, int8_t)
11554f2ec7f9SAart Bik 
11568a91bc7bSHarrietAkot #undef CASE
11578a91bc7bSHarrietAkot #undef IMPL_SPARSEVALUES
11588a91bc7bSHarrietAkot #undef IMPL_GETOVERHEAD
11598a91bc7bSHarrietAkot #undef IMPL_ADDELT
11608a91bc7bSHarrietAkot #undef IMPL_GETNEXT
11614f2ec7f9SAart Bik #undef IMPL_LEXINSERT
11624f2ec7f9SAart Bik #undef IMPL_EXPINSERT
11636438783fSAart Bik 
11646438783fSAart Bik /// Output a sparse tensor, one per value type.
11656438783fSAart Bik void outSparseTensorF64(void *tensor, void *dest, bool sort) {
11666438783fSAart Bik   return outSparseTensor<double>(tensor, dest, sort);
11676438783fSAart Bik }
11686438783fSAart Bik void outSparseTensorF32(void *tensor, void *dest, bool sort) {
11696438783fSAart Bik   return outSparseTensor<float>(tensor, dest, sort);
11706438783fSAart Bik }
11716438783fSAart Bik void outSparseTensorI64(void *tensor, void *dest, bool sort) {
11726438783fSAart Bik   return outSparseTensor<int64_t>(tensor, dest, sort);
11736438783fSAart Bik }
11746438783fSAart Bik void outSparseTensorI32(void *tensor, void *dest, bool sort) {
11756438783fSAart Bik   return outSparseTensor<int32_t>(tensor, dest, sort);
11766438783fSAart Bik }
11776438783fSAart Bik void outSparseTensorI16(void *tensor, void *dest, bool sort) {
11786438783fSAart Bik   return outSparseTensor<int16_t>(tensor, dest, sort);
11796438783fSAart Bik }
11806438783fSAart Bik void outSparseTensorI8(void *tensor, void *dest, bool sort) {
11816438783fSAart Bik   return outSparseTensor<int8_t>(tensor, dest, sort);
11826438783fSAart Bik }
11838a91bc7bSHarrietAkot 
11848a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
11858a91bc7bSHarrietAkot //
11868a91bc7bSHarrietAkot // Public API with methods that accept C-style data structures to interact
11878a91bc7bSHarrietAkot // with sparse tensors, which are only visible as opaque pointers externally.
11888a91bc7bSHarrietAkot // These methods can be used both by MLIR compiler-generated code as well as by
11898a91bc7bSHarrietAkot // an external runtime that wants to interact with MLIR compiler-generated code.
11908a91bc7bSHarrietAkot //
11918a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
11928a91bc7bSHarrietAkot 
11938a91bc7bSHarrietAkot /// Helper method to read a sparse tensor filename from the environment,
11948a91bc7bSHarrietAkot /// defined with the naming convention ${TENSOR0}, ${TENSOR1}, etc.
1195d2215e79SRainer Orth char *getTensorFilename(index_type id) {
11968a91bc7bSHarrietAkot   char var[80];
11978a91bc7bSHarrietAkot   sprintf(var, "TENSOR%" PRIu64, id);
11988a91bc7bSHarrietAkot   char *env = getenv(var);
11993734c078Swren romano   if (!env) {
12003734c078Swren romano     fprintf(stderr, "Environment variable %s is not set\n", var);
12013734c078Swren romano     exit(1);
12023734c078Swren romano   }
12038a91bc7bSHarrietAkot   return env;
12048a91bc7bSHarrietAkot }
12058a91bc7bSHarrietAkot 
12068a91bc7bSHarrietAkot /// Returns size of sparse tensor in given dimension.
1207d2215e79SRainer Orth index_type sparseDimSize(void *tensor, index_type d) {
12088a91bc7bSHarrietAkot   return static_cast<SparseTensorStorageBase *>(tensor)->getDimSize(d);
12098a91bc7bSHarrietAkot }
12108a91bc7bSHarrietAkot 
1211f66e5769SAart Bik /// Finalizes lexicographic insertions.
1212f66e5769SAart Bik void endInsert(void *tensor) {
1213f66e5769SAart Bik   return static_cast<SparseTensorStorageBase *>(tensor)->endInsert();
1214f66e5769SAart Bik }
1215f66e5769SAart Bik 
12168a91bc7bSHarrietAkot /// Releases sparse tensor storage.
12178a91bc7bSHarrietAkot void delSparseTensor(void *tensor) {
12188a91bc7bSHarrietAkot   delete static_cast<SparseTensorStorageBase *>(tensor);
12198a91bc7bSHarrietAkot }
12208a91bc7bSHarrietAkot 
122163bdcaf9Swren romano /// Releases sparse tensor coordinate scheme.
122263bdcaf9Swren romano #define IMPL_DELCOO(VNAME, V)                                                  \
122363bdcaf9Swren romano   void delSparseTensorCOO##VNAME(void *coo) {                                  \
122463bdcaf9Swren romano     delete static_cast<SparseTensorCOO<V> *>(coo);                             \
122563bdcaf9Swren romano   }
122663bdcaf9Swren romano IMPL_DELCOO(F64, double)
122763bdcaf9Swren romano IMPL_DELCOO(F32, float)
122863bdcaf9Swren romano IMPL_DELCOO(I64, int64_t)
122963bdcaf9Swren romano IMPL_DELCOO(I32, int32_t)
123063bdcaf9Swren romano IMPL_DELCOO(I16, int16_t)
123163bdcaf9Swren romano IMPL_DELCOO(I8, int8_t)
123263bdcaf9Swren romano #undef IMPL_DELCOO
123363bdcaf9Swren romano 
12348a91bc7bSHarrietAkot /// Initializes sparse tensor from a COO-flavored format expressed using C-style
12358a91bc7bSHarrietAkot /// data structures. The expected parameters are:
12368a91bc7bSHarrietAkot ///
12378a91bc7bSHarrietAkot ///   rank:    rank of tensor
12388a91bc7bSHarrietAkot ///   nse:     number of specified elements (usually the nonzeros)
12398a91bc7bSHarrietAkot ///   shape:   array with dimension size for each rank
12408a91bc7bSHarrietAkot ///   values:  a "nse" array with values for all specified elements
12418a91bc7bSHarrietAkot ///   indices: a flat "nse x rank" array with indices for all specified elements
124220eaa88fSBixia Zheng ///   perm:    the permutation of the dimensions in the storage
124320eaa88fSBixia Zheng ///   sparse:  the sparsity for the dimensions
12448a91bc7bSHarrietAkot ///
12458a91bc7bSHarrietAkot /// For example, the sparse matrix
12468a91bc7bSHarrietAkot ///     | 1.0 0.0 0.0 |
12478a91bc7bSHarrietAkot ///     | 0.0 5.0 3.0 |
12488a91bc7bSHarrietAkot /// can be passed as
12498a91bc7bSHarrietAkot ///      rank    = 2
12508a91bc7bSHarrietAkot ///      nse     = 3
12518a91bc7bSHarrietAkot ///      shape   = [2, 3]
12528a91bc7bSHarrietAkot ///      values  = [1.0, 5.0, 3.0]
12538a91bc7bSHarrietAkot ///      indices = [ 0, 0,  1, 1,  1, 2]
12548a91bc7bSHarrietAkot //
125520eaa88fSBixia Zheng // TODO: generalize beyond 64-bit indices.
12568a91bc7bSHarrietAkot //
12576438783fSAart Bik void *convertToMLIRSparseTensorF64(uint64_t rank, uint64_t nse, uint64_t *shape,
125820eaa88fSBixia Zheng                                    double *values, uint64_t *indices,
125920eaa88fSBixia Zheng                                    uint64_t *perm, uint8_t *sparse) {
126020eaa88fSBixia Zheng   return toMLIRSparseTensor<double>(rank, nse, shape, values, indices, perm,
126120eaa88fSBixia Zheng                                     sparse);
12628a91bc7bSHarrietAkot }
12636438783fSAart Bik void *convertToMLIRSparseTensorF32(uint64_t rank, uint64_t nse, uint64_t *shape,
126420eaa88fSBixia Zheng                                    float *values, uint64_t *indices,
126520eaa88fSBixia Zheng                                    uint64_t *perm, uint8_t *sparse) {
126620eaa88fSBixia Zheng   return toMLIRSparseTensor<float>(rank, nse, shape, values, indices, perm,
126720eaa88fSBixia Zheng                                    sparse);
12688a91bc7bSHarrietAkot }
12698a91bc7bSHarrietAkot 
12702f49e6b0SBixia Zheng /// Converts a sparse tensor to COO-flavored format expressed using C-style
12712f49e6b0SBixia Zheng /// data structures. The expected output parameters are pointers for these
12722f49e6b0SBixia Zheng /// values:
12732f49e6b0SBixia Zheng ///
12742f49e6b0SBixia Zheng ///   rank:    rank of tensor
12752f49e6b0SBixia Zheng ///   nse:     number of specified elements (usually the nonzeros)
12762f49e6b0SBixia Zheng ///   shape:   array with dimension size for each rank
12772f49e6b0SBixia Zheng ///   values:  a "nse" array with values for all specified elements
12782f49e6b0SBixia Zheng ///   indices: a flat "nse x rank" array with indices for all specified elements
12792f49e6b0SBixia Zheng ///
12802f49e6b0SBixia Zheng /// The input is a pointer to SparseTensorStorage<P, I, V>, typically returned
12812f49e6b0SBixia Zheng /// from convertToMLIRSparseTensor.
12822f49e6b0SBixia Zheng ///
12832f49e6b0SBixia Zheng //  TODO: Currently, values are copied from SparseTensorStorage to
12842f49e6b0SBixia Zheng //  SparseTensorCOO, then to the output. We may want to reduce the number of
12852f49e6b0SBixia Zheng //  copies.
12862f49e6b0SBixia Zheng //
12876438783fSAart Bik // TODO: generalize beyond 64-bit indices, no dim ordering, all dimensions
12886438783fSAart Bik // compressed
12892f49e6b0SBixia Zheng //
12906438783fSAart Bik void convertFromMLIRSparseTensorF64(void *tensor, uint64_t *pRank,
12916438783fSAart Bik                                     uint64_t *pNse, uint64_t **pShape,
12926438783fSAart Bik                                     double **pValues, uint64_t **pIndices) {
12936438783fSAart Bik   fromMLIRSparseTensor<double>(tensor, pRank, pNse, pShape, pValues, pIndices);
12942f49e6b0SBixia Zheng }
12956438783fSAart Bik void convertFromMLIRSparseTensorF32(void *tensor, uint64_t *pRank,
12966438783fSAart Bik                                     uint64_t *pNse, uint64_t **pShape,
12976438783fSAart Bik                                     float **pValues, uint64_t **pIndices) {
12986438783fSAart Bik   fromMLIRSparseTensor<float>(tensor, pRank, pNse, pShape, pValues, pIndices);
12992f49e6b0SBixia Zheng }
1300efa15f41SAart Bik 
13018a91bc7bSHarrietAkot } // extern "C"
13028a91bc7bSHarrietAkot 
13038a91bc7bSHarrietAkot #endif // MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS
1304