1 //===- SparseTensorUtils.cpp - Sparse Tensor Utils for MLIR execution -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a light-weight runtime support library that is useful
10 // for sparse tensor manipulations. The functionality provided in this library
11 // is meant to simplify benchmarking, testing, and debugging MLIR code that
12 // operates on sparse tensors. The provided functionality is **not** part
13 // of core MLIR, however.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "mlir/ExecutionEngine/SparseTensorUtils.h"
18 #include "mlir/ExecutionEngine/CRunnerUtils.h"
19 
20 #ifdef MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS
21 
22 #include <algorithm>
23 #include <cassert>
24 #include <cctype>
25 #include <cinttypes>
26 #include <cstdio>
27 #include <cstdlib>
28 #include <cstring>
29 #include <numeric>
30 #include <vector>
31 
32 //===----------------------------------------------------------------------===//
33 //
34 // Internal support for storing and reading sparse tensors.
35 //
36 // The following memory-resident sparse storage schemes are supported:
37 //
38 // (a) A coordinate scheme for temporarily storing and lexicographically
39 //     sorting a sparse tensor by index (SparseTensorCOO).
40 //
41 // (b) A "one-size-fits-all" sparse tensor storage scheme defined by
42 //     per-dimension sparse/dense annnotations together with a dimension
43 //     ordering used by MLIR compiler-generated code (SparseTensorStorage).
44 //
45 // The following external formats are supported:
46 //
47 // (1) Matrix Market Exchange (MME): *.mtx
48 //     https://math.nist.gov/MatrixMarket/formats.html
49 //
50 // (2) Formidable Repository of Open Sparse Tensors and Tools (FROSTT): *.tns
51 //     http://frostt.io/tensors/file-formats.html
52 //
53 // Two public APIs are supported:
54 //
55 // (I) Methods operating on MLIR buffers (memrefs) to interact with sparse
56 //     tensors. These methods should be used exclusively by MLIR
57 //     compiler-generated code.
58 //
59 // (II) Methods that accept C-style data structures to interact with sparse
60 //      tensors. These methods can be used by any external runtime that wants
61 //      to interact with MLIR compiler-generated code.
62 //
63 // In both cases (I) and (II), the SparseTensorStorage format is externally
64 // only visible as an opaque pointer.
65 //
66 //===----------------------------------------------------------------------===//
67 
68 namespace {
69 
70 static constexpr int kColWidth = 1025;
71 
72 /// A sparse tensor element in coordinate scheme (value and indices).
73 /// For example, a rank-1 vector element would look like
74 ///   ({i}, a[i])
75 /// and a rank-5 tensor element like
76 ///   ({i,j,k,l,m}, a[i,j,k,l,m])
77 template <typename V>
78 struct Element {
79   Element(const std::vector<uint64_t> &ind, V val) : indices(ind), value(val){};
80   std::vector<uint64_t> indices;
81   V value;
82 };
83 
84 /// A memory-resident sparse tensor in coordinate scheme (collection of
85 /// elements). This data structure is used to read a sparse tensor from
86 /// any external format into memory and sort the elements lexicographically
87 /// by indices before passing it back to the client (most packed storage
88 /// formats require the elements to appear in lexicographic index order).
89 template <typename V>
90 struct SparseTensorCOO {
91 public:
92   SparseTensorCOO(const std::vector<uint64_t> &szs, uint64_t capacity)
93       : sizes(szs), iteratorLocked(false), iteratorPos(0) {
94     if (capacity)
95       elements.reserve(capacity);
96   }
97   /// Adds element as indices and value.
98   void add(const std::vector<uint64_t> &ind, V val) {
99     assert(!iteratorLocked && "Attempt to add() after startIterator()");
100     uint64_t rank = getRank();
101     assert(rank == ind.size());
102     for (uint64_t r = 0; r < rank; r++)
103       assert(ind[r] < sizes[r]); // within bounds
104     elements.emplace_back(ind, val);
105   }
106   /// Sorts elements lexicographically by index.
107   void sort() {
108     assert(!iteratorLocked && "Attempt to sort() after startIterator()");
109     std::sort(elements.begin(), elements.end(), lexOrder);
110   }
111   /// Returns rank.
112   uint64_t getRank() const { return sizes.size(); }
113   /// Getter for sizes array.
114   const std::vector<uint64_t> &getSizes() const { return sizes; }
115   /// Getter for elements array.
116   const std::vector<Element<V>> &getElements() const { return elements; }
117 
118   /// Switch into iterator mode.
119   void startIterator() {
120     iteratorLocked = true;
121     iteratorPos = 0;
122   }
123   /// Get the next element.
124   const Element<V> *getNext() {
125     assert(iteratorLocked && "Attempt to getNext() before startIterator()");
126     if (iteratorPos < elements.size())
127       return &(elements[iteratorPos++]);
128     iteratorLocked = false;
129     return nullptr;
130   }
131 
132   /// Factory method. Permutes the original dimensions according to
133   /// the given ordering and expects subsequent add() calls to honor
134   /// that same ordering for the given indices. The result is a
135   /// fully permuted coordinate scheme.
136   static SparseTensorCOO<V> *newSparseTensorCOO(uint64_t rank,
137                                                 const uint64_t *sizes,
138                                                 const uint64_t *perm,
139                                                 uint64_t capacity = 0) {
140     std::vector<uint64_t> permsz(rank);
141     for (uint64_t r = 0; r < rank; r++)
142       permsz[perm[r]] = sizes[r];
143     return new SparseTensorCOO<V>(permsz, capacity);
144   }
145 
146 private:
147   /// Returns true if indices of e1 < indices of e2.
148   static bool lexOrder(const Element<V> &e1, const Element<V> &e2) {
149     uint64_t rank = e1.indices.size();
150     assert(rank == e2.indices.size());
151     for (uint64_t r = 0; r < rank; r++) {
152       if (e1.indices[r] == e2.indices[r])
153         continue;
154       return e1.indices[r] < e2.indices[r];
155     }
156     return false;
157   }
158   const std::vector<uint64_t> sizes; // per-dimension sizes
159   std::vector<Element<V>> elements;
160   bool iteratorLocked;
161   unsigned iteratorPos;
162 };
163 
164 /// Abstract base class of sparse tensor storage. Note that we use
165 /// function overloading to implement "partial" method specialization.
166 class SparseTensorStorageBase {
167 public:
168   /// Dimension size query.
169   virtual uint64_t getDimSize(uint64_t) = 0;
170 
171   /// Overhead storage.
172   virtual void getPointers(std::vector<uint64_t> **, uint64_t) { fatal("p64"); }
173   virtual void getPointers(std::vector<uint32_t> **, uint64_t) { fatal("p32"); }
174   virtual void getPointers(std::vector<uint16_t> **, uint64_t) { fatal("p16"); }
175   virtual void getPointers(std::vector<uint8_t> **, uint64_t) { fatal("p8"); }
176   virtual void getIndices(std::vector<uint64_t> **, uint64_t) { fatal("i64"); }
177   virtual void getIndices(std::vector<uint32_t> **, uint64_t) { fatal("i32"); }
178   virtual void getIndices(std::vector<uint16_t> **, uint64_t) { fatal("i16"); }
179   virtual void getIndices(std::vector<uint8_t> **, uint64_t) { fatal("i8"); }
180 
181   /// Primary storage.
182   virtual void getValues(std::vector<double> **) { fatal("valf64"); }
183   virtual void getValues(std::vector<float> **) { fatal("valf32"); }
184   virtual void getValues(std::vector<int64_t> **) { fatal("vali64"); }
185   virtual void getValues(std::vector<int32_t> **) { fatal("vali32"); }
186   virtual void getValues(std::vector<int16_t> **) { fatal("vali16"); }
187   virtual void getValues(std::vector<int8_t> **) { fatal("vali8"); }
188 
189   /// Element-wise insertion in lexicographic index order.
190   virtual void lexInsert(const uint64_t *, double) { fatal("insf64"); }
191   virtual void lexInsert(const uint64_t *, float) { fatal("insf32"); }
192   virtual void lexInsert(const uint64_t *, int64_t) { fatal("insi64"); }
193   virtual void lexInsert(const uint64_t *, int32_t) { fatal("insi32"); }
194   virtual void lexInsert(const uint64_t *, int16_t) { fatal("ins16"); }
195   virtual void lexInsert(const uint64_t *, int8_t) { fatal("insi8"); }
196 
197   /// Expanded insertion.
198   virtual void expInsert(uint64_t *, double *, bool *, uint64_t *, uint64_t) {
199     fatal("expf64");
200   }
201   virtual void expInsert(uint64_t *, float *, bool *, uint64_t *, uint64_t) {
202     fatal("expf32");
203   }
204   virtual void expInsert(uint64_t *, int64_t *, bool *, uint64_t *, uint64_t) {
205     fatal("expi64");
206   }
207   virtual void expInsert(uint64_t *, int32_t *, bool *, uint64_t *, uint64_t) {
208     fatal("expi32");
209   }
210   virtual void expInsert(uint64_t *, int16_t *, bool *, uint64_t *, uint64_t) {
211     fatal("expi16");
212   }
213   virtual void expInsert(uint64_t *, int8_t *, bool *, uint64_t *, uint64_t) {
214     fatal("expi8");
215   }
216 
217   /// Finishes insertion.
218   virtual void endInsert() = 0;
219 
220   virtual ~SparseTensorStorageBase() = default;
221 
222 private:
223   void fatal(const char *tp) {
224     fprintf(stderr, "unsupported %s\n", tp);
225     exit(1);
226   }
227 };
228 
229 /// A memory-resident sparse tensor using a storage scheme based on
230 /// per-dimension sparse/dense annotations. This data structure provides a
231 /// bufferized form of a sparse tensor type. In contrast to generating setup
232 /// methods for each differently annotated sparse tensor, this method provides
233 /// a convenient "one-size-fits-all" solution that simply takes an input tensor
234 /// and annotations to implement all required setup in a general manner.
235 template <typename P, typename I, typename V>
236 class SparseTensorStorage : public SparseTensorStorageBase {
237 public:
238   /// Constructs a sparse tensor storage scheme with the given dimensions,
239   /// permutation, and per-dimension dense/sparse annotations, using
240   /// the coordinate scheme tensor for the initial contents if provided.
241   SparseTensorStorage(const std::vector<uint64_t> &szs, const uint64_t *perm,
242                       const DimLevelType *sparsity,
243                       SparseTensorCOO<V> *tensor = nullptr)
244       : sizes(szs), rev(getRank()), idx(getRank()), pointers(getRank()),
245         indices(getRank()) {
246     uint64_t rank = getRank();
247     // Store "reverse" permutation.
248     for (uint64_t r = 0; r < rank; r++)
249       rev[perm[r]] = r;
250     // Provide hints on capacity of pointers and indices.
251     // TODO: needs fine-tuning based on sparsity
252     bool allDense = true;
253     uint64_t sz = 1;
254     for (uint64_t r = 0; r < rank; r++) {
255       sz *= sizes[r];
256       if (sparsity[r] == DimLevelType::kCompressed) {
257         pointers[r].reserve(sz + 1);
258         indices[r].reserve(sz);
259         sz = 1;
260         allDense = false;
261       } else {
262         assert(sparsity[r] == DimLevelType::kDense &&
263                "singleton not yet supported");
264       }
265     }
266     // Prepare sparse pointer structures for all dimensions.
267     for (uint64_t r = 0; r < rank; r++)
268       if (sparsity[r] == DimLevelType::kCompressed)
269         pointers[r].push_back(0);
270     // Then assign contents from coordinate scheme tensor if provided.
271     if (tensor) {
272       const std::vector<Element<V>> &elements = tensor->getElements();
273       uint64_t nnz = elements.size();
274       values.reserve(nnz);
275       fromCOO(elements, 0, nnz, 0);
276     } else if (allDense) {
277       values.resize(sz, 0);
278     }
279   }
280 
281   ~SparseTensorStorage() override = default;
282 
283   /// Get the rank of the tensor.
284   uint64_t getRank() const { return sizes.size(); }
285 
286   /// Get the size in the given dimension of the tensor.
287   uint64_t getDimSize(uint64_t d) override {
288     assert(d < getRank());
289     return sizes[d];
290   }
291 
292   /// Partially specialize these getter methods based on template types.
293   void getPointers(std::vector<P> **out, uint64_t d) override {
294     assert(d < getRank());
295     *out = &pointers[d];
296   }
297   void getIndices(std::vector<I> **out, uint64_t d) override {
298     assert(d < getRank());
299     *out = &indices[d];
300   }
301   void getValues(std::vector<V> **out) override { *out = &values; }
302 
303   /// Partially specialize lexicographical insertions based on template types.
304   void lexInsert(const uint64_t *cursor, V val) override {
305     // First, wrap up pending insertion path.
306     uint64_t diff = 0;
307     uint64_t top = 0;
308     if (!values.empty()) {
309       diff = lexDiff(cursor);
310       endPath(diff + 1);
311       top = idx[diff] + 1;
312     }
313     // Then continue with insertion path.
314     insPath(cursor, diff, top, val);
315   }
316 
317   /// Partially specialize expanded insertions based on template types.
318   /// Note that this method resets the values/filled-switch array back
319   /// to all-zero/false while only iterating over the nonzero elements.
320   void expInsert(uint64_t *cursor, V *values, bool *filled, uint64_t *added,
321                  uint64_t count) override {
322     if (count == 0)
323       return;
324     // Sort.
325     std::sort(added, added + count);
326     // Restore insertion path for first insert.
327     uint64_t rank = getRank();
328     uint64_t index = added[0];
329     cursor[rank - 1] = index;
330     lexInsert(cursor, values[index]);
331     assert(filled[index]);
332     values[index] = 0;
333     filled[index] = false;
334     // Subsequent insertions are quick.
335     for (uint64_t i = 1; i < count; i++) {
336       assert(index < added[i] && "non-lexicographic insertion");
337       index = added[i];
338       cursor[rank - 1] = index;
339       insPath(cursor, rank - 1, added[i - 1] + 1, values[index]);
340       assert(filled[index]);
341       values[index] = 0.0;
342       filled[index] = false;
343     }
344   }
345 
346   /// Finalizes lexicographic insertions.
347   void endInsert() override {
348     if (values.empty())
349       endDim(0);
350     else
351       endPath(0);
352   }
353 
354   /// Returns this sparse tensor storage scheme as a new memory-resident
355   /// sparse tensor in coordinate scheme with the given dimension order.
356   SparseTensorCOO<V> *toCOO(const uint64_t *perm) {
357     // Restore original order of the dimension sizes and allocate coordinate
358     // scheme with desired new ordering specified in perm.
359     uint64_t rank = getRank();
360     std::vector<uint64_t> orgsz(rank);
361     for (uint64_t r = 0; r < rank; r++)
362       orgsz[rev[r]] = sizes[r];
363     SparseTensorCOO<V> *tensor = SparseTensorCOO<V>::newSparseTensorCOO(
364         rank, orgsz.data(), perm, values.size());
365     // Populate coordinate scheme restored from old ordering and changed with
366     // new ordering. Rather than applying both reorderings during the recursion,
367     // we compute the combine permutation in advance.
368     std::vector<uint64_t> reord(rank);
369     for (uint64_t r = 0; r < rank; r++)
370       reord[r] = perm[rev[r]];
371     toCOO(*tensor, reord, 0, 0);
372     assert(tensor->getElements().size() == values.size());
373     return tensor;
374   }
375 
376   /// Factory method. Constructs a sparse tensor storage scheme with the given
377   /// dimensions, permutation, and per-dimension dense/sparse annotations,
378   /// using the coordinate scheme tensor for the initial contents if provided.
379   /// In the latter case, the coordinate scheme must respect the same
380   /// permutation as is desired for the new sparse tensor storage.
381   static SparseTensorStorage<P, I, V> *
382   newSparseTensor(uint64_t rank, const uint64_t *sizes, const uint64_t *perm,
383                   const DimLevelType *sparsity, SparseTensorCOO<V> *tensor) {
384     SparseTensorStorage<P, I, V> *n = nullptr;
385     if (tensor) {
386       assert(tensor->getRank() == rank);
387       for (uint64_t r = 0; r < rank; r++)
388         assert(sizes[r] == 0 || tensor->getSizes()[perm[r]] == sizes[r]);
389       tensor->sort(); // sort lexicographically
390       n = new SparseTensorStorage<P, I, V>(tensor->getSizes(), perm, sparsity,
391                                            tensor);
392       delete tensor;
393     } else {
394       std::vector<uint64_t> permsz(rank);
395       for (uint64_t r = 0; r < rank; r++)
396         permsz[perm[r]] = sizes[r];
397       n = new SparseTensorStorage<P, I, V>(permsz, perm, sparsity);
398     }
399     return n;
400   }
401 
402 private:
403   /// Initializes sparse tensor storage scheme from a memory-resident sparse
404   /// tensor in coordinate scheme. This method prepares the pointers and
405   /// indices arrays under the given per-dimension dense/sparse annotations.
406   void fromCOO(const std::vector<Element<V>> &elements, uint64_t lo,
407                uint64_t hi, uint64_t d) {
408     // Once dimensions are exhausted, insert the numerical values.
409     assert(d <= getRank());
410     if (d == getRank()) {
411       assert(lo < hi && hi <= elements.size());
412       values.push_back(elements[lo].value);
413       return;
414     }
415     // Visit all elements in this interval.
416     uint64_t full = 0;
417     while (lo < hi) {
418       assert(lo < elements.size() && hi <= elements.size());
419       // Find segment in interval with same index elements in this dimension.
420       uint64_t i = elements[lo].indices[d];
421       uint64_t seg = lo + 1;
422       while (seg < hi && elements[seg].indices[d] == i)
423         seg++;
424       // Handle segment in interval for sparse or dense dimension.
425       if (isCompressedDim(d)) {
426         indices[d].push_back(i);
427       } else {
428         // For dense storage we must fill in all the zero values between
429         // the previous element (when last we ran this for-loop) and the
430         // current element.
431         for (; full < i; full++)
432           endDim(d + 1);
433         full++;
434       }
435       fromCOO(elements, lo, seg, d + 1);
436       // And move on to next segment in interval.
437       lo = seg;
438     }
439     // Finalize the sparse pointer structure at this dimension.
440     if (isCompressedDim(d)) {
441       pointers[d].push_back(indices[d].size());
442     } else {
443       // For dense storage we must fill in all the zero values after
444       // the last element.
445       for (uint64_t sz = sizes[d]; full < sz; full++)
446         endDim(d + 1);
447     }
448   }
449 
450   /// Stores the sparse tensor storage scheme into a memory-resident sparse
451   /// tensor in coordinate scheme.
452   void toCOO(SparseTensorCOO<V> &tensor, std::vector<uint64_t> &reord,
453              uint64_t pos, uint64_t d) {
454     assert(d <= getRank());
455     if (d == getRank()) {
456       assert(pos < values.size());
457       tensor.add(idx, values[pos]);
458     } else if (isCompressedDim(d)) {
459       // Sparse dimension.
460       for (uint64_t ii = pointers[d][pos]; ii < pointers[d][pos + 1]; ii++) {
461         idx[reord[d]] = indices[d][ii];
462         toCOO(tensor, reord, ii, d + 1);
463       }
464     } else {
465       // Dense dimension.
466       for (uint64_t i = 0, sz = sizes[d], off = pos * sz; i < sz; i++) {
467         idx[reord[d]] = i;
468         toCOO(tensor, reord, off + i, d + 1);
469       }
470     }
471   }
472 
473   /// Ends a deeper, never seen before dimension.
474   void endDim(uint64_t d) {
475     assert(d <= getRank());
476     if (d == getRank()) {
477       values.push_back(0);
478     } else if (isCompressedDim(d)) {
479       pointers[d].push_back(indices[d].size());
480     } else {
481       for (uint64_t full = 0, sz = sizes[d]; full < sz; full++)
482         endDim(d + 1);
483     }
484   }
485 
486   /// Wraps up a single insertion path, inner to outer.
487   void endPath(uint64_t diff) {
488     uint64_t rank = getRank();
489     assert(diff <= rank);
490     for (uint64_t i = 0; i < rank - diff; i++) {
491       uint64_t d = rank - i - 1;
492       if (isCompressedDim(d)) {
493         pointers[d].push_back(indices[d].size());
494       } else {
495         for (uint64_t full = idx[d] + 1, sz = sizes[d]; full < sz; full++)
496           endDim(d + 1);
497       }
498     }
499   }
500 
501   /// Continues a single insertion path, outer to inner.
502   void insPath(const uint64_t *cursor, uint64_t diff, uint64_t top, V val) {
503     uint64_t rank = getRank();
504     assert(diff < rank);
505     for (uint64_t d = diff; d < rank; d++) {
506       uint64_t i = cursor[d];
507       if (isCompressedDim(d)) {
508         indices[d].push_back(i);
509       } else {
510         for (uint64_t full = top; full < i; full++)
511           endDim(d + 1);
512       }
513       top = 0;
514       idx[d] = i;
515     }
516     values.push_back(val);
517   }
518 
519   /// Finds the lexicographic differing dimension.
520   uint64_t lexDiff(const uint64_t *cursor) {
521     for (uint64_t r = 0, rank = getRank(); r < rank; r++)
522       if (cursor[r] > idx[r])
523         return r;
524       else
525         assert(cursor[r] == idx[r] && "non-lexicographic insertion");
526     assert(0 && "duplication insertion");
527     return -1u;
528   }
529 
530   /// Returns true if dimension is compressed.
531   inline bool isCompressedDim(uint64_t d) const {
532     return (!pointers[d].empty());
533   }
534 
535 private:
536   std::vector<uint64_t> sizes; // per-dimension sizes
537   std::vector<uint64_t> rev;   // "reverse" permutation
538   std::vector<uint64_t> idx;   // index cursor
539   std::vector<std::vector<P>> pointers;
540   std::vector<std::vector<I>> indices;
541   std::vector<V> values;
542 };
543 
544 /// Helper to convert string to lower case.
545 static char *toLower(char *token) {
546   for (char *c = token; *c; c++)
547     *c = tolower(*c);
548   return token;
549 }
550 
551 /// Read the MME header of a general sparse matrix of type real.
552 static void readMMEHeader(FILE *file, char *filename, char *line,
553                           uint64_t *idata, bool *isSymmetric) {
554   char header[64];
555   char object[64];
556   char format[64];
557   char field[64];
558   char symmetry[64];
559   // Read header line.
560   if (fscanf(file, "%63s %63s %63s %63s %63s\n", header, object, format, field,
561              symmetry) != 5) {
562     fprintf(stderr, "Corrupt header in %s\n", filename);
563     exit(1);
564   }
565   *isSymmetric = (strcmp(toLower(symmetry), "symmetric") == 0);
566   // Make sure this is a general sparse matrix.
567   if (strcmp(toLower(header), "%%matrixmarket") ||
568       strcmp(toLower(object), "matrix") ||
569       strcmp(toLower(format), "coordinate") || strcmp(toLower(field), "real") ||
570       (strcmp(toLower(symmetry), "general") && !(*isSymmetric))) {
571     fprintf(stderr,
572             "Cannot find a general sparse matrix with type real in %s\n",
573             filename);
574     exit(1);
575   }
576   // Skip comments.
577   while (true) {
578     if (!fgets(line, kColWidth, file)) {
579       fprintf(stderr, "Cannot find data in %s\n", filename);
580       exit(1);
581     }
582     if (line[0] != '%')
583       break;
584   }
585   // Next line contains M N NNZ.
586   idata[0] = 2; // rank
587   if (sscanf(line, "%" PRIu64 "%" PRIu64 "%" PRIu64 "\n", idata + 2, idata + 3,
588              idata + 1) != 3) {
589     fprintf(stderr, "Cannot find size in %s\n", filename);
590     exit(1);
591   }
592 }
593 
594 /// Read the "extended" FROSTT header. Although not part of the documented
595 /// format, we assume that the file starts with optional comments followed
596 /// by two lines that define the rank, the number of nonzeros, and the
597 /// dimensions sizes (one per rank) of the sparse tensor.
598 static void readExtFROSTTHeader(FILE *file, char *filename, char *line,
599                                 uint64_t *idata) {
600   // Skip comments.
601   while (true) {
602     if (!fgets(line, kColWidth, file)) {
603       fprintf(stderr, "Cannot find data in %s\n", filename);
604       exit(1);
605     }
606     if (line[0] != '#')
607       break;
608   }
609   // Next line contains RANK and NNZ.
610   if (sscanf(line, "%" PRIu64 "%" PRIu64 "\n", idata, idata + 1) != 2) {
611     fprintf(stderr, "Cannot find metadata in %s\n", filename);
612     exit(1);
613   }
614   // Followed by a line with the dimension sizes (one per rank).
615   for (uint64_t r = 0; r < idata[0]; r++) {
616     if (fscanf(file, "%" PRIu64, idata + 2 + r) != 1) {
617       fprintf(stderr, "Cannot find dimension size %s\n", filename);
618       exit(1);
619     }
620   }
621   fgets(line, kColWidth, file); // end of line
622 }
623 
624 /// Reads a sparse tensor with the given filename into a memory-resident
625 /// sparse tensor in coordinate scheme.
626 template <typename V>
627 static SparseTensorCOO<V> *openSparseTensorCOO(char *filename, uint64_t rank,
628                                                const uint64_t *sizes,
629                                                const uint64_t *perm) {
630   // Open the file.
631   FILE *file = fopen(filename, "r");
632   if (!file) {
633     fprintf(stderr, "Cannot find %s\n", filename);
634     exit(1);
635   }
636   // Perform some file format dependent set up.
637   char line[kColWidth];
638   uint64_t idata[512];
639   bool isSymmetric = false;
640   if (strstr(filename, ".mtx")) {
641     readMMEHeader(file, filename, line, idata, &isSymmetric);
642   } else if (strstr(filename, ".tns")) {
643     readExtFROSTTHeader(file, filename, line, idata);
644   } else {
645     fprintf(stderr, "Unknown format %s\n", filename);
646     exit(1);
647   }
648   // Prepare sparse tensor object with per-dimension sizes
649   // and the number of nonzeros as initial capacity.
650   assert(rank == idata[0] && "rank mismatch");
651   uint64_t nnz = idata[1];
652   for (uint64_t r = 0; r < rank; r++)
653     assert((sizes[r] == 0 || sizes[r] == idata[2 + r]) &&
654            "dimension size mismatch");
655   SparseTensorCOO<V> *tensor =
656       SparseTensorCOO<V>::newSparseTensorCOO(rank, idata + 2, perm, nnz);
657   //  Read all nonzero elements.
658   std::vector<uint64_t> indices(rank);
659   for (uint64_t k = 0; k < nnz; k++) {
660     if (!fgets(line, kColWidth, file)) {
661       fprintf(stderr, "Cannot find next line of data in %s\n", filename);
662       exit(1);
663     }
664     char *linePtr = line;
665     for (uint64_t r = 0; r < rank; r++) {
666       uint64_t idx = strtoul(linePtr, &linePtr, 10);
667       // Add 0-based index.
668       indices[perm[r]] = idx - 1;
669     }
670     // The external formats always store the numerical values with the type
671     // double, but we cast these values to the sparse tensor object type.
672     double value = strtod(linePtr, &linePtr);
673     tensor->add(indices, value);
674     // We currently chose to deal with symmetric matrices by fully constructing
675     // them. In the future, we may want to make symmetry implicit for storage
676     // reasons.
677     if (isSymmetric && indices[0] != indices[1])
678       tensor->add({indices[1], indices[0]}, value);
679   }
680   // Close the file and return tensor.
681   fclose(file);
682   return tensor;
683 }
684 
685 } // namespace
686 
687 extern "C" {
688 
689 //===----------------------------------------------------------------------===//
690 //
691 // Public API with methods that operate on MLIR buffers (memrefs) to interact
692 // with sparse tensors, which are only visible as opaque pointers externally.
693 // These methods should be used exclusively by MLIR compiler-generated code.
694 //
695 // Some macro magic is used to generate implementations for all required type
696 // combinations that can be called from MLIR compiler-generated code.
697 //
698 //===----------------------------------------------------------------------===//
699 
700 #define CASE(p, i, v, P, I, V)                                                 \
701   if (ptrTp == (p) && indTp == (i) && valTp == (v)) {                          \
702     SparseTensorCOO<V> *tensor = nullptr;                                      \
703     if (action <= Action::kFromCOO) {                                          \
704       if (action == Action::kFromFile) {                                       \
705         char *filename = static_cast<char *>(ptr);                             \
706         tensor = openSparseTensorCOO<V>(filename, rank, sizes, perm);          \
707       } else if (action == Action::kFromCOO) {                                 \
708         tensor = static_cast<SparseTensorCOO<V> *>(ptr);                       \
709       } else {                                                                 \
710         assert(action == Action::kEmpty);                                      \
711       }                                                                        \
712       return SparseTensorStorage<P, I, V>::newSparseTensor(rank, sizes, perm,  \
713                                                            sparsity, tensor);  \
714     }                                                                          \
715     if (action == Action::kEmptyCOO)                                           \
716       return SparseTensorCOO<V>::newSparseTensorCOO(rank, sizes, perm);        \
717     tensor = static_cast<SparseTensorStorage<P, I, V> *>(ptr)->toCOO(perm);    \
718     if (action == Action::kToIterator) {                                       \
719       tensor->startIterator();                                                 \
720     } else {                                                                   \
721       assert(action == Action::kToCOO);                                        \
722     }                                                                          \
723     return tensor;                                                             \
724   }
725 
726 #define CASE_SECSAME(p, v, P, V) CASE(p, p, v, P, P, V)
727 
728 #define IMPL_SPARSEVALUES(NAME, TYPE, LIB)                                     \
729   void _mlir_ciface_##NAME(StridedMemRefType<TYPE, 1> *ref, void *tensor) {    \
730     assert(ref &&tensor);                                                      \
731     std::vector<TYPE> *v;                                                      \
732     static_cast<SparseTensorStorageBase *>(tensor)->LIB(&v);                   \
733     ref->basePtr = ref->data = v->data();                                      \
734     ref->offset = 0;                                                           \
735     ref->sizes[0] = v->size();                                                 \
736     ref->strides[0] = 1;                                                       \
737   }
738 
739 #define IMPL_GETOVERHEAD(NAME, TYPE, LIB)                                      \
740   void _mlir_ciface_##NAME(StridedMemRefType<TYPE, 1> *ref, void *tensor,      \
741                            index_t d) {                                        \
742     assert(ref &&tensor);                                                      \
743     std::vector<TYPE> *v;                                                      \
744     static_cast<SparseTensorStorageBase *>(tensor)->LIB(&v, d);                \
745     ref->basePtr = ref->data = v->data();                                      \
746     ref->offset = 0;                                                           \
747     ref->sizes[0] = v->size();                                                 \
748     ref->strides[0] = 1;                                                       \
749   }
750 
751 #define IMPL_ADDELT(NAME, TYPE)                                                \
752   void *_mlir_ciface_##NAME(void *tensor, TYPE value,                          \
753                             StridedMemRefType<index_t, 1> *iref,               \
754                             StridedMemRefType<index_t, 1> *pref) {             \
755     assert(tensor &&iref &&pref);                                              \
756     assert(iref->strides[0] == 1 && pref->strides[0] == 1);                    \
757     assert(iref->sizes[0] == pref->sizes[0]);                                  \
758     const index_t *indx = iref->data + iref->offset;                           \
759     const index_t *perm = pref->data + pref->offset;                           \
760     uint64_t isize = iref->sizes[0];                                           \
761     std::vector<index_t> indices(isize);                                       \
762     for (uint64_t r = 0; r < isize; r++)                                       \
763       indices[perm[r]] = indx[r];                                              \
764     static_cast<SparseTensorCOO<TYPE> *>(tensor)->add(indices, value);         \
765     return tensor;                                                             \
766   }
767 
768 #define IMPL_GETNEXT(NAME, V)                                                  \
769   bool _mlir_ciface_##NAME(void *tensor, StridedMemRefType<index_t, 1> *iref,  \
770                            StridedMemRefType<V, 0> *vref) {                    \
771     assert(tensor &&iref &&vref);                                              \
772     assert(iref->strides[0] == 1);                                             \
773     index_t *indx = iref->data + iref->offset;                                 \
774     V *value = vref->data + vref->offset;                                      \
775     const uint64_t isize = iref->sizes[0];                                     \
776     auto iter = static_cast<SparseTensorCOO<V> *>(tensor);                     \
777     const Element<V> *elem = iter->getNext();                                  \
778     if (elem == nullptr) {                                                     \
779       delete iter;                                                             \
780       return false;                                                            \
781     }                                                                          \
782     for (uint64_t r = 0; r < isize; r++)                                       \
783       indx[r] = elem->indices[r];                                              \
784     *value = elem->value;                                                      \
785     return true;                                                               \
786   }
787 
788 #define IMPL_LEXINSERT(NAME, V)                                                \
789   void _mlir_ciface_##NAME(void *tensor, StridedMemRefType<index_t, 1> *cref,  \
790                            V val) {                                            \
791     assert(tensor &&cref);                                                     \
792     assert(cref->strides[0] == 1);                                             \
793     index_t *cursor = cref->data + cref->offset;                               \
794     assert(cursor);                                                            \
795     static_cast<SparseTensorStorageBase *>(tensor)->lexInsert(cursor, val);    \
796   }
797 
798 #define IMPL_EXPINSERT(NAME, V)                                                \
799   void _mlir_ciface_##NAME(                                                    \
800       void *tensor, StridedMemRefType<index_t, 1> *cref,                       \
801       StridedMemRefType<V, 1> *vref, StridedMemRefType<bool, 1> *fref,         \
802       StridedMemRefType<index_t, 1> *aref, index_t count) {                    \
803     assert(tensor &&cref &&vref &&fref &&aref);                                \
804     assert(cref->strides[0] == 1);                                             \
805     assert(vref->strides[0] == 1);                                             \
806     assert(fref->strides[0] == 1);                                             \
807     assert(aref->strides[0] == 1);                                             \
808     assert(vref->sizes[0] == fref->sizes[0]);                                  \
809     index_t *cursor = cref->data + cref->offset;                               \
810     V *values = vref->data + vref->offset;                                     \
811     bool *filled = fref->data + fref->offset;                                  \
812     index_t *added = aref->data + aref->offset;                                \
813     static_cast<SparseTensorStorageBase *>(tensor)->expInsert(                 \
814         cursor, values, filled, added, count);                                 \
815   }
816 
817 // Assume index_t is in fact uint64_t, so that _mlir_ciface_newSparseTensor
818 // can safely rewrite kIndex to kU64.  We make this assertion to guarantee
819 // that this file cannot get out of sync with its header.
820 static_assert(std::is_same<index_t, uint64_t>::value,
821               "Expected index_t == uint64_t");
822 
823 /// Constructs a new sparse tensor. This is the "swiss army knife"
824 /// method for materializing sparse tensors into the computation.
825 ///
826 /// Action:
827 /// kEmpty = returns empty storage to fill later
828 /// kFromFile = returns storage, where ptr contains filename to read
829 /// kFromCOO = returns storage, where ptr contains coordinate scheme to assign
830 /// kEmptyCOO = returns empty coordinate scheme to fill and use with kFromCOO
831 /// kToCOO = returns coordinate scheme from storage in ptr to use with kFromCOO
832 /// kToIterator = returns iterator from storage in ptr (call getNext() to use)
833 void *
834 _mlir_ciface_newSparseTensor(StridedMemRefType<DimLevelType, 1> *aref, // NOLINT
835                              StridedMemRefType<index_t, 1> *sref,
836                              StridedMemRefType<index_t, 1> *pref,
837                              OverheadType ptrTp, OverheadType indTp,
838                              PrimaryType valTp, Action action, void *ptr) {
839   assert(aref && sref && pref);
840   assert(aref->strides[0] == 1 && sref->strides[0] == 1 &&
841          pref->strides[0] == 1);
842   assert(aref->sizes[0] == sref->sizes[0] && sref->sizes[0] == pref->sizes[0]);
843   const DimLevelType *sparsity = aref->data + aref->offset;
844   const index_t *sizes = sref->data + sref->offset;
845   const index_t *perm = pref->data + pref->offset;
846   uint64_t rank = aref->sizes[0];
847 
848   // Rewrite kIndex to kU64, to avoid introducing a bunch of new cases.
849   // This is safe because of the static_assert above.
850   if (ptrTp == OverheadType::kIndex)
851     ptrTp = OverheadType::kU64;
852   if (indTp == OverheadType::kIndex)
853     indTp = OverheadType::kU64;
854 
855   // Double matrices with all combinations of overhead storage.
856   CASE(OverheadType::kU64, OverheadType::kU64, PrimaryType::kF64, uint64_t,
857        uint64_t, double);
858   CASE(OverheadType::kU64, OverheadType::kU32, PrimaryType::kF64, uint64_t,
859        uint32_t, double);
860   CASE(OverheadType::kU64, OverheadType::kU16, PrimaryType::kF64, uint64_t,
861        uint16_t, double);
862   CASE(OverheadType::kU64, OverheadType::kU8, PrimaryType::kF64, uint64_t,
863        uint8_t, double);
864   CASE(OverheadType::kU32, OverheadType::kU64, PrimaryType::kF64, uint32_t,
865        uint64_t, double);
866   CASE(OverheadType::kU32, OverheadType::kU32, PrimaryType::kF64, uint32_t,
867        uint32_t, double);
868   CASE(OverheadType::kU32, OverheadType::kU16, PrimaryType::kF64, uint32_t,
869        uint16_t, double);
870   CASE(OverheadType::kU32, OverheadType::kU8, PrimaryType::kF64, uint32_t,
871        uint8_t, double);
872   CASE(OverheadType::kU16, OverheadType::kU64, PrimaryType::kF64, uint16_t,
873        uint64_t, double);
874   CASE(OverheadType::kU16, OverheadType::kU32, PrimaryType::kF64, uint16_t,
875        uint32_t, double);
876   CASE(OverheadType::kU16, OverheadType::kU16, PrimaryType::kF64, uint16_t,
877        uint16_t, double);
878   CASE(OverheadType::kU16, OverheadType::kU8, PrimaryType::kF64, uint16_t,
879        uint8_t, double);
880   CASE(OverheadType::kU8, OverheadType::kU64, PrimaryType::kF64, uint8_t,
881        uint64_t, double);
882   CASE(OverheadType::kU8, OverheadType::kU32, PrimaryType::kF64, uint8_t,
883        uint32_t, double);
884   CASE(OverheadType::kU8, OverheadType::kU16, PrimaryType::kF64, uint8_t,
885        uint16_t, double);
886   CASE(OverheadType::kU8, OverheadType::kU8, PrimaryType::kF64, uint8_t,
887        uint8_t, double);
888 
889   // Float matrices with all combinations of overhead storage.
890   CASE(OverheadType::kU64, OverheadType::kU64, PrimaryType::kF32, uint64_t,
891        uint64_t, float);
892   CASE(OverheadType::kU64, OverheadType::kU32, PrimaryType::kF32, uint64_t,
893        uint32_t, float);
894   CASE(OverheadType::kU64, OverheadType::kU16, PrimaryType::kF32, uint64_t,
895        uint16_t, float);
896   CASE(OverheadType::kU64, OverheadType::kU8, PrimaryType::kF32, uint64_t,
897        uint8_t, float);
898   CASE(OverheadType::kU32, OverheadType::kU64, PrimaryType::kF32, uint32_t,
899        uint64_t, float);
900   CASE(OverheadType::kU32, OverheadType::kU32, PrimaryType::kF32, uint32_t,
901        uint32_t, float);
902   CASE(OverheadType::kU32, OverheadType::kU16, PrimaryType::kF32, uint32_t,
903        uint16_t, float);
904   CASE(OverheadType::kU32, OverheadType::kU8, PrimaryType::kF32, uint32_t,
905        uint8_t, float);
906   CASE(OverheadType::kU16, OverheadType::kU64, PrimaryType::kF32, uint16_t,
907        uint64_t, float);
908   CASE(OverheadType::kU16, OverheadType::kU32, PrimaryType::kF32, uint16_t,
909        uint32_t, float);
910   CASE(OverheadType::kU16, OverheadType::kU16, PrimaryType::kF32, uint16_t,
911        uint16_t, float);
912   CASE(OverheadType::kU16, OverheadType::kU8, PrimaryType::kF32, uint16_t,
913        uint8_t, float);
914   CASE(OverheadType::kU8, OverheadType::kU64, PrimaryType::kF32, uint8_t,
915        uint64_t, float);
916   CASE(OverheadType::kU8, OverheadType::kU32, PrimaryType::kF32, uint8_t,
917        uint32_t, float);
918   CASE(OverheadType::kU8, OverheadType::kU16, PrimaryType::kF32, uint8_t,
919        uint16_t, float);
920   CASE(OverheadType::kU8, OverheadType::kU8, PrimaryType::kF32, uint8_t,
921        uint8_t, float);
922 
923   // Integral matrices with both overheads of the same type.
924   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI64, uint64_t, int64_t);
925   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI32, uint64_t, int32_t);
926   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI16, uint64_t, int16_t);
927   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI8, uint64_t, int8_t);
928   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI32, uint32_t, int32_t);
929   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI16, uint32_t, int16_t);
930   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI8, uint32_t, int8_t);
931   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI32, uint16_t, int32_t);
932   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI16, uint16_t, int16_t);
933   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI8, uint16_t, int8_t);
934   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI32, uint8_t, int32_t);
935   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI16, uint8_t, int16_t);
936   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI8, uint8_t, int8_t);
937 
938   // Unsupported case (add above if needed).
939   fputs("unsupported combination of types\n", stderr);
940   exit(1);
941 }
942 
943 /// Methods that provide direct access to pointers.
944 IMPL_GETOVERHEAD(sparsePointers, index_t, getPointers)
945 IMPL_GETOVERHEAD(sparsePointers64, uint64_t, getPointers)
946 IMPL_GETOVERHEAD(sparsePointers32, uint32_t, getPointers)
947 IMPL_GETOVERHEAD(sparsePointers16, uint16_t, getPointers)
948 IMPL_GETOVERHEAD(sparsePointers8, uint8_t, getPointers)
949 
950 /// Methods that provide direct access to indices.
951 IMPL_GETOVERHEAD(sparseIndices, index_t, getIndices)
952 IMPL_GETOVERHEAD(sparseIndices64, uint64_t, getIndices)
953 IMPL_GETOVERHEAD(sparseIndices32, uint32_t, getIndices)
954 IMPL_GETOVERHEAD(sparseIndices16, uint16_t, getIndices)
955 IMPL_GETOVERHEAD(sparseIndices8, uint8_t, getIndices)
956 
957 /// Methods that provide direct access to values.
958 IMPL_SPARSEVALUES(sparseValuesF64, double, getValues)
959 IMPL_SPARSEVALUES(sparseValuesF32, float, getValues)
960 IMPL_SPARSEVALUES(sparseValuesI64, int64_t, getValues)
961 IMPL_SPARSEVALUES(sparseValuesI32, int32_t, getValues)
962 IMPL_SPARSEVALUES(sparseValuesI16, int16_t, getValues)
963 IMPL_SPARSEVALUES(sparseValuesI8, int8_t, getValues)
964 
965 /// Helper to add value to coordinate scheme, one per value type.
966 IMPL_ADDELT(addEltF64, double)
967 IMPL_ADDELT(addEltF32, float)
968 IMPL_ADDELT(addEltI64, int64_t)
969 IMPL_ADDELT(addEltI32, int32_t)
970 IMPL_ADDELT(addEltI16, int16_t)
971 IMPL_ADDELT(addEltI8, int8_t)
972 
973 /// Helper to enumerate elements of coordinate scheme, one per value type.
974 IMPL_GETNEXT(getNextF64, double)
975 IMPL_GETNEXT(getNextF32, float)
976 IMPL_GETNEXT(getNextI64, int64_t)
977 IMPL_GETNEXT(getNextI32, int32_t)
978 IMPL_GETNEXT(getNextI16, int16_t)
979 IMPL_GETNEXT(getNextI8, int8_t)
980 
981 /// Helper to insert elements in lexicographical index order, one per value
982 /// type.
983 IMPL_LEXINSERT(lexInsertF64, double)
984 IMPL_LEXINSERT(lexInsertF32, float)
985 IMPL_LEXINSERT(lexInsertI64, int64_t)
986 IMPL_LEXINSERT(lexInsertI32, int32_t)
987 IMPL_LEXINSERT(lexInsertI16, int16_t)
988 IMPL_LEXINSERT(lexInsertI8, int8_t)
989 
990 /// Helper to insert using expansion, one per value type.
991 IMPL_EXPINSERT(expInsertF64, double)
992 IMPL_EXPINSERT(expInsertF32, float)
993 IMPL_EXPINSERT(expInsertI64, int64_t)
994 IMPL_EXPINSERT(expInsertI32, int32_t)
995 IMPL_EXPINSERT(expInsertI16, int16_t)
996 IMPL_EXPINSERT(expInsertI8, int8_t)
997 
998 #undef CASE
999 #undef IMPL_SPARSEVALUES
1000 #undef IMPL_GETOVERHEAD
1001 #undef IMPL_ADDELT
1002 #undef IMPL_GETNEXT
1003 #undef IMPL_LEXINSERT
1004 #undef IMPL_EXPINSERT
1005 
1006 //===----------------------------------------------------------------------===//
1007 //
1008 // Public API with methods that accept C-style data structures to interact
1009 // with sparse tensors, which are only visible as opaque pointers externally.
1010 // These methods can be used both by MLIR compiler-generated code as well as by
1011 // an external runtime that wants to interact with MLIR compiler-generated code.
1012 //
1013 //===----------------------------------------------------------------------===//
1014 
1015 /// Helper method to read a sparse tensor filename from the environment,
1016 /// defined with the naming convention ${TENSOR0}, ${TENSOR1}, etc.
1017 char *getTensorFilename(index_t id) {
1018   char var[80];
1019   sprintf(var, "TENSOR%" PRIu64, id);
1020   char *env = getenv(var);
1021   return env;
1022 }
1023 
1024 /// Returns size of sparse tensor in given dimension.
1025 index_t sparseDimSize(void *tensor, index_t d) {
1026   return static_cast<SparseTensorStorageBase *>(tensor)->getDimSize(d);
1027 }
1028 
1029 /// Finalizes lexicographic insertions.
1030 void endInsert(void *tensor) {
1031   return static_cast<SparseTensorStorageBase *>(tensor)->endInsert();
1032 }
1033 
1034 /// Releases sparse tensor storage.
1035 void delSparseTensor(void *tensor) {
1036   delete static_cast<SparseTensorStorageBase *>(tensor);
1037 }
1038 
1039 /// Initializes sparse tensor from a COO-flavored format expressed using C-style
1040 /// data structures. The expected parameters are:
1041 ///
1042 ///   rank:    rank of tensor
1043 ///   nse:     number of specified elements (usually the nonzeros)
1044 ///   shape:   array with dimension size for each rank
1045 ///   values:  a "nse" array with values for all specified elements
1046 ///   indices: a flat "nse x rank" array with indices for all specified elements
1047 ///
1048 /// For example, the sparse matrix
1049 ///     | 1.0 0.0 0.0 |
1050 ///     | 0.0 5.0 3.0 |
1051 /// can be passed as
1052 ///      rank    = 2
1053 ///      nse     = 3
1054 ///      shape   = [2, 3]
1055 ///      values  = [1.0, 5.0, 3.0]
1056 ///      indices = [ 0, 0,  1, 1,  1, 2]
1057 //
1058 // TODO: for now f64 tensors only, no dim ordering, all dimensions compressed
1059 //
1060 void *convertToMLIRSparseTensor(uint64_t rank, uint64_t nse, uint64_t *shape,
1061                                 double *values, uint64_t *indices) {
1062   // Setup all-dims compressed and default ordering.
1063   std::vector<DimLevelType> sparse(rank, DimLevelType::kCompressed);
1064   std::vector<uint64_t> perm(rank);
1065   std::iota(perm.begin(), perm.end(), 0);
1066   // Convert external format to internal COO.
1067   SparseTensorCOO<double> *tensor = SparseTensorCOO<double>::newSparseTensorCOO(
1068       rank, shape, perm.data(), nse);
1069   std::vector<uint64_t> idx(rank);
1070   for (uint64_t i = 0, base = 0; i < nse; i++) {
1071     for (uint64_t r = 0; r < rank; r++)
1072       idx[r] = indices[base + r];
1073     tensor->add(idx, values[i]);
1074     base += rank;
1075   }
1076   // Return sparse tensor storage format as opaque pointer.
1077   return SparseTensorStorage<uint64_t, uint64_t, double>::newSparseTensor(
1078       rank, shape, perm.data(), sparse.data(), tensor);
1079 }
1080 
1081 /// Converts a sparse tensor to COO-flavored format expressed using C-style
1082 /// data structures. The expected output parameters are pointers for these
1083 /// values:
1084 ///
1085 ///   rank:    rank of tensor
1086 ///   nse:     number of specified elements (usually the nonzeros)
1087 ///   shape:   array with dimension size for each rank
1088 ///   values:  a "nse" array with values for all specified elements
1089 ///   indices: a flat "nse x rank" array with indices for all specified elements
1090 ///
1091 /// The input is a pointer to SparseTensorStorage<P, I, V>, typically returned
1092 /// from convertToMLIRSparseTensor.
1093 ///
1094 //  TODO: Currently, values are copied from SparseTensorStorage to
1095 //  SparseTensorCOO, then to the output. We may want to reduce the number of
1096 //  copies.
1097 //
1098 //  TODO: for now f64 tensors only, no dim ordering, all dimensions compressed
1099 //
1100 void convertFromMLIRSparseTensor(void *tensor, uint64_t *pRank, uint64_t *pNse,
1101                                  uint64_t **pShape, double **pValues,
1102                                  uint64_t **pIndices) {
1103   SparseTensorStorage<uint64_t, uint64_t, double> *sparseTensor =
1104       static_cast<SparseTensorStorage<uint64_t, uint64_t, double> *>(tensor);
1105   uint64_t rank = sparseTensor->getRank();
1106   std::vector<uint64_t> perm(rank);
1107   std::iota(perm.begin(), perm.end(), 0);
1108   SparseTensorCOO<double> *coo = sparseTensor->toCOO(perm.data());
1109 
1110   const std::vector<Element<double>> &elements = coo->getElements();
1111   uint64_t nse = elements.size();
1112 
1113   uint64_t *shape = new uint64_t[rank];
1114   for (uint64_t i = 0; i < rank; i++)
1115     shape[i] = coo->getSizes()[i];
1116 
1117   double *values = new double[nse];
1118   uint64_t *indices = new uint64_t[rank * nse];
1119 
1120   for (uint64_t i = 0, base = 0; i < nse; i++) {
1121     values[i] = elements[i].value;
1122     for (uint64_t j = 0; j < rank; j++)
1123       indices[base + j] = elements[i].indices[j];
1124     base += rank;
1125   }
1126 
1127   delete coo;
1128   *pRank = rank;
1129   *pNse = nse;
1130   *pShape = shape;
1131   *pValues = values;
1132   *pIndices = indices;
1133 }
1134 } // extern "C"
1135 
1136 #endif // MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS
1137