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(uint64_t *, double) { fatal("insf64"); }
191   virtual void lexInsert(uint64_t *, float) { fatal("insf32"); }
192   virtual void lexInsert(uint64_t *, int64_t) { fatal("insi64"); }
193   virtual void lexInsert(uint64_t *, int32_t) { fatal("insi32"); }
194   virtual void lexInsert(uint64_t *, int16_t) { fatal("ins16"); }
195   virtual void lexInsert(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       uint64_t nnz = tensor->getElements().size();
273       values.reserve(nnz);
274       fromCOO(tensor, 0, nnz, 0);
275     } else if (allDense) {
276       values.resize(sz, 0);
277     }
278   }
279 
280   virtual ~SparseTensorStorage() = default;
281 
282   /// Get the rank of the tensor.
283   uint64_t getRank() const { return sizes.size(); }
284 
285   /// Get the size in the given dimension of the tensor.
286   uint64_t getDimSize(uint64_t d) override {
287     assert(d < getRank());
288     return sizes[d];
289   }
290 
291   /// Partially specialize these getter methods based on template types.
292   void getPointers(std::vector<P> **out, uint64_t d) override {
293     assert(d < getRank());
294     *out = &pointers[d];
295   }
296   void getIndices(std::vector<I> **out, uint64_t d) override {
297     assert(d < getRank());
298     *out = &indices[d];
299   }
300   void getValues(std::vector<V> **out) override { *out = &values; }
301 
302   /// Partially specialize lexicographical insertions based on template types.
303   void lexInsert(uint64_t *cursor, V val) override {
304     // First, wrap up pending insertion path.
305     uint64_t diff = 0;
306     uint64_t top = 0;
307     if (!values.empty()) {
308       diff = lexDiff(cursor);
309       endPath(diff + 1);
310       top = idx[diff] + 1;
311     }
312     // Then continue with insertion path.
313     insPath(cursor, diff, top, val);
314   }
315 
316   /// Partially specialize expanded insertions based on template types.
317   /// Note that this method resets the values/filled-switch array back
318   /// to all-zero/false while only iterating over the nonzero elements.
319   void expInsert(uint64_t *cursor, V *values, bool *filled, uint64_t *added,
320                  uint64_t count) override {
321     if (count == 0)
322       return;
323     // Sort.
324     std::sort(added, added + count);
325     // Restore insertion path for first insert.
326     uint64_t rank = getRank();
327     uint64_t index = added[0];
328     cursor[rank - 1] = index;
329     lexInsert(cursor, values[index]);
330     assert(filled[index]);
331     values[index] = 0;
332     filled[index] = false;
333     // Subsequent insertions are quick.
334     for (uint64_t i = 1; i < count; i++) {
335       assert(index < added[i] && "non-lexicographic insertion");
336       index = added[i];
337       cursor[rank - 1] = index;
338       insPath(cursor, rank - 1, added[i - 1] + 1, values[index]);
339       assert(filled[index]);
340       values[index] = 0.0;
341       filled[index] = false;
342     }
343   }
344 
345   /// Finalizes lexicographic insertions.
346   void endInsert() override {
347     if (values.empty())
348       endDim(0);
349     else
350       endPath(0);
351   }
352 
353   /// Returns this sparse tensor storage scheme as a new memory-resident
354   /// sparse tensor in coordinate scheme with the given dimension order.
355   SparseTensorCOO<V> *toCOO(const uint64_t *perm) {
356     // Restore original order of the dimension sizes and allocate coordinate
357     // scheme with desired new ordering specified in perm.
358     uint64_t rank = getRank();
359     std::vector<uint64_t> orgsz(rank);
360     for (uint64_t r = 0; r < rank; r++)
361       orgsz[rev[r]] = sizes[r];
362     SparseTensorCOO<V> *tensor = SparseTensorCOO<V>::newSparseTensorCOO(
363         rank, orgsz.data(), perm, values.size());
364     // Populate coordinate scheme restored from old ordering and changed with
365     // new ordering. Rather than applying both reorderings during the recursion,
366     // we compute the combine permutation in advance.
367     std::vector<uint64_t> reord(rank);
368     for (uint64_t r = 0; r < rank; r++)
369       reord[r] = perm[rev[r]];
370     toCOO(tensor, reord, 0, 0);
371     assert(tensor->getElements().size() == values.size());
372     return tensor;
373   }
374 
375   /// Factory method. Constructs a sparse tensor storage scheme with the given
376   /// dimensions, permutation, and per-dimension dense/sparse annotations,
377   /// using the coordinate scheme tensor for the initial contents if provided.
378   /// In the latter case, the coordinate scheme must respect the same
379   /// permutation as is desired for the new sparse tensor storage.
380   static SparseTensorStorage<P, I, V> *
381   newSparseTensor(uint64_t rank, const uint64_t *sizes, const uint64_t *perm,
382                   const DimLevelType *sparsity, SparseTensorCOO<V> *tensor) {
383     SparseTensorStorage<P, I, V> *n = nullptr;
384     if (tensor) {
385       assert(tensor->getRank() == rank);
386       for (uint64_t r = 0; r < rank; r++)
387         assert(sizes[r] == 0 || tensor->getSizes()[perm[r]] == sizes[r]);
388       tensor->sort(); // sort lexicographically
389       n = new SparseTensorStorage<P, I, V>(tensor->getSizes(), perm, sparsity,
390                                            tensor);
391       delete tensor;
392     } else {
393       std::vector<uint64_t> permsz(rank);
394       for (uint64_t r = 0; r < rank; r++)
395         permsz[perm[r]] = sizes[r];
396       n = new SparseTensorStorage<P, I, V>(permsz, perm, sparsity);
397     }
398     return n;
399   }
400 
401 private:
402   /// Initializes sparse tensor storage scheme from a memory-resident sparse
403   /// tensor in coordinate scheme. This method prepares the pointers and
404   /// indices arrays under the given per-dimension dense/sparse annotations.
405   void fromCOO(SparseTensorCOO<V> *tensor, uint64_t lo, uint64_t hi,
406                uint64_t d) {
407     const std::vector<Element<V>> &elements = tensor->getElements();
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(tensor, 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(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(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 /// This type is used in the public API at all places where MLIR expects
690 /// values with the built-in type "index". For now, we simply assume that
691 /// type is 64-bit, but targets with different "index" bit widths should link
692 /// with an alternatively built runtime support library.
693 // TODO: support such targets?
694 typedef uint64_t index_t;
695 
696 //===----------------------------------------------------------------------===//
697 //
698 // Public API with methods that operate on MLIR buffers (memrefs) to interact
699 // with sparse tensors, which are only visible as opaque pointers externally.
700 // These methods should be used exclusively by MLIR compiler-generated code.
701 //
702 // Some macro magic is used to generate implementations for all required type
703 // combinations that can be called from MLIR compiler-generated code.
704 //
705 //===----------------------------------------------------------------------===//
706 
707 #define CASE(p, i, v, P, I, V)                                                 \
708   if (ptrTp == (p) && indTp == (i) && valTp == (v)) {                          \
709     SparseTensorCOO<V> *tensor = nullptr;                                      \
710     if (action <= Action::kFromCOO) {                                          \
711       if (action == Action::kFromFile) {                                       \
712         char *filename = static_cast<char *>(ptr);                             \
713         tensor = openSparseTensorCOO<V>(filename, rank, sizes, perm);          \
714       } else if (action == Action::kFromCOO) {                                 \
715         tensor = static_cast<SparseTensorCOO<V> *>(ptr);                       \
716       } else {                                                                 \
717         assert(action == Action::kEmpty);                                      \
718       }                                                                        \
719       return SparseTensorStorage<P, I, V>::newSparseTensor(rank, sizes, perm,  \
720                                                            sparsity, tensor);  \
721     }                                                                          \
722     if (action == Action::kEmptyCOO)                                           \
723       return SparseTensorCOO<V>::newSparseTensorCOO(rank, sizes, perm);        \
724     tensor = static_cast<SparseTensorStorage<P, I, V> *>(ptr)->toCOO(perm);    \
725     if (action == Action::kToIterator) {                                       \
726       tensor->startIterator();                                                 \
727     } else {                                                                   \
728       assert(action == Action::kToCOO);                                        \
729     }                                                                          \
730     return tensor;                                                             \
731   }
732 
733 #define CASE_SECSAME(p, v, P, V) CASE(p, p, v, P, P, V)
734 
735 #define IMPL_SPARSEVALUES(NAME, TYPE, LIB)                                     \
736   void _mlir_ciface_##NAME(StridedMemRefType<TYPE, 1> *ref, void *tensor) {    \
737     assert(ref &&tensor);                                                      \
738     std::vector<TYPE> *v;                                                      \
739     static_cast<SparseTensorStorageBase *>(tensor)->LIB(&v);                   \
740     ref->basePtr = ref->data = v->data();                                      \
741     ref->offset = 0;                                                           \
742     ref->sizes[0] = v->size();                                                 \
743     ref->strides[0] = 1;                                                       \
744   }
745 
746 #define IMPL_GETOVERHEAD(NAME, TYPE, LIB)                                      \
747   void _mlir_ciface_##NAME(StridedMemRefType<TYPE, 1> *ref, void *tensor,      \
748                            index_t d) {                                        \
749     assert(ref &&tensor);                                                      \
750     std::vector<TYPE> *v;                                                      \
751     static_cast<SparseTensorStorageBase *>(tensor)->LIB(&v, d);                \
752     ref->basePtr = ref->data = v->data();                                      \
753     ref->offset = 0;                                                           \
754     ref->sizes[0] = v->size();                                                 \
755     ref->strides[0] = 1;                                                       \
756   }
757 
758 #define IMPL_ADDELT(NAME, TYPE)                                                \
759   void *_mlir_ciface_##NAME(void *tensor, TYPE value,                          \
760                             StridedMemRefType<index_t, 1> *iref,               \
761                             StridedMemRefType<index_t, 1> *pref) {             \
762     assert(tensor &&iref &&pref);                                              \
763     assert(iref->strides[0] == 1 && pref->strides[0] == 1);                    \
764     assert(iref->sizes[0] == pref->sizes[0]);                                  \
765     const index_t *indx = iref->data + iref->offset;                           \
766     const index_t *perm = pref->data + pref->offset;                           \
767     uint64_t isize = iref->sizes[0];                                           \
768     std::vector<index_t> indices(isize);                                       \
769     for (uint64_t r = 0; r < isize; r++)                                       \
770       indices[perm[r]] = indx[r];                                              \
771     static_cast<SparseTensorCOO<TYPE> *>(tensor)->add(indices, value);         \
772     return tensor;                                                             \
773   }
774 
775 #define IMPL_GETNEXT(NAME, V)                                                  \
776   bool _mlir_ciface_##NAME(void *tensor, StridedMemRefType<index_t, 1> *iref,  \
777                            StridedMemRefType<V, 0> *vref) {                    \
778     assert(tensor &&iref &&vref);                                              \
779     assert(iref->strides[0] == 1);                                             \
780     index_t *indx = iref->data + iref->offset;                                 \
781     V *value = vref->data + vref->offset;                                      \
782     const uint64_t isize = iref->sizes[0];                                     \
783     auto iter = static_cast<SparseTensorCOO<V> *>(tensor);                     \
784     const Element<V> *elem = iter->getNext();                                  \
785     if (elem == nullptr) {                                                     \
786       delete iter;                                                             \
787       return false;                                                            \
788     }                                                                          \
789     for (uint64_t r = 0; r < isize; r++)                                       \
790       indx[r] = elem->indices[r];                                              \
791     *value = elem->value;                                                      \
792     return true;                                                               \
793   }
794 
795 #define IMPL_LEXINSERT(NAME, V)                                                \
796   void _mlir_ciface_##NAME(void *tensor, StridedMemRefType<index_t, 1> *cref,  \
797                            V val) {                                            \
798     assert(tensor &&cref);                                                     \
799     assert(cref->strides[0] == 1);                                             \
800     index_t *cursor = cref->data + cref->offset;                               \
801     assert(cursor);                                                            \
802     static_cast<SparseTensorStorageBase *>(tensor)->lexInsert(cursor, val);    \
803   }
804 
805 #define IMPL_EXPINSERT(NAME, V)                                                \
806   void _mlir_ciface_##NAME(                                                    \
807       void *tensor, StridedMemRefType<index_t, 1> *cref,                       \
808       StridedMemRefType<V, 1> *vref, StridedMemRefType<bool, 1> *fref,         \
809       StridedMemRefType<index_t, 1> *aref, index_t count) {                    \
810     assert(tensor &&cref &&vref &&fref &&aref);                                \
811     assert(cref->strides[0] == 1);                                             \
812     assert(vref->strides[0] == 1);                                             \
813     assert(fref->strides[0] == 1);                                             \
814     assert(aref->strides[0] == 1);                                             \
815     assert(vref->sizes[0] == fref->sizes[0]);                                  \
816     index_t *cursor = cref->data + cref->offset;                               \
817     V *values = vref->data + vref->offset;                                     \
818     bool *filled = fref->data + fref->offset;                                  \
819     index_t *added = aref->data + aref->offset;                                \
820     static_cast<SparseTensorStorageBase *>(tensor)->expInsert(                 \
821         cursor, values, filled, added, count);                                 \
822   }
823 
824 /// Constructs a new sparse tensor. This is the "swiss army knife"
825 /// method for materializing sparse tensors into the computation.
826 ///
827 /// Action:
828 /// kEmpty = returns empty storage to fill later
829 /// kFromFile = returns storage, where ptr contains filename to read
830 /// kFromCOO = returns storage, where ptr contains coordinate scheme to assign
831 /// kEmptyCOO = returns empty coordinate scheme to fill and use with kFromCOO
832 /// kToCOO = returns coordinate scheme from storage in ptr to use with kFromCOO
833 /// kToIterator = returns iterator from storage in ptr (call getNext() to use)
834 void *
835 _mlir_ciface_newSparseTensor(StridedMemRefType<DimLevelType, 1> *aref, // NOLINT
836                              StridedMemRefType<index_t, 1> *sref,
837                              StridedMemRefType<index_t, 1> *pref,
838                              OverheadType ptrTp, OverheadType indTp,
839                              PrimaryType valTp, Action action, void *ptr) {
840   assert(aref && sref && pref);
841   assert(aref->strides[0] == 1 && sref->strides[0] == 1 &&
842          pref->strides[0] == 1);
843   assert(aref->sizes[0] == sref->sizes[0] && sref->sizes[0] == pref->sizes[0]);
844   const DimLevelType *sparsity = aref->data + aref->offset;
845   const index_t *sizes = sref->data + sref->offset;
846   const index_t *perm = pref->data + pref->offset;
847   uint64_t rank = aref->sizes[0];
848 
849   // Double matrices with all combinations of overhead storage.
850   CASE(OverheadType::kU64, OverheadType::kU64, PrimaryType::kF64, uint64_t,
851        uint64_t, double);
852   CASE(OverheadType::kU64, OverheadType::kU32, PrimaryType::kF64, uint64_t,
853        uint32_t, double);
854   CASE(OverheadType::kU64, OverheadType::kU16, PrimaryType::kF64, uint64_t,
855        uint16_t, double);
856   CASE(OverheadType::kU64, OverheadType::kU8, PrimaryType::kF64, uint64_t,
857        uint8_t, double);
858   CASE(OverheadType::kU32, OverheadType::kU64, PrimaryType::kF64, uint32_t,
859        uint64_t, double);
860   CASE(OverheadType::kU32, OverheadType::kU32, PrimaryType::kF64, uint32_t,
861        uint32_t, double);
862   CASE(OverheadType::kU32, OverheadType::kU16, PrimaryType::kF64, uint32_t,
863        uint16_t, double);
864   CASE(OverheadType::kU32, OverheadType::kU8, PrimaryType::kF64, uint32_t,
865        uint8_t, double);
866   CASE(OverheadType::kU16, OverheadType::kU64, PrimaryType::kF64, uint16_t,
867        uint64_t, double);
868   CASE(OverheadType::kU16, OverheadType::kU32, PrimaryType::kF64, uint16_t,
869        uint32_t, double);
870   CASE(OverheadType::kU16, OverheadType::kU16, PrimaryType::kF64, uint16_t,
871        uint16_t, double);
872   CASE(OverheadType::kU16, OverheadType::kU8, PrimaryType::kF64, uint16_t,
873        uint8_t, double);
874   CASE(OverheadType::kU8, OverheadType::kU64, PrimaryType::kF64, uint8_t,
875        uint64_t, double);
876   CASE(OverheadType::kU8, OverheadType::kU32, PrimaryType::kF64, uint8_t,
877        uint32_t, double);
878   CASE(OverheadType::kU8, OverheadType::kU16, PrimaryType::kF64, uint8_t,
879        uint16_t, double);
880   CASE(OverheadType::kU8, OverheadType::kU8, PrimaryType::kF64, uint8_t,
881        uint8_t, double);
882 
883   // Float matrices with all combinations of overhead storage.
884   CASE(OverheadType::kU64, OverheadType::kU64, PrimaryType::kF32, uint64_t,
885        uint64_t, float);
886   CASE(OverheadType::kU64, OverheadType::kU32, PrimaryType::kF32, uint64_t,
887        uint32_t, float);
888   CASE(OverheadType::kU64, OverheadType::kU16, PrimaryType::kF32, uint64_t,
889        uint16_t, float);
890   CASE(OverheadType::kU64, OverheadType::kU8, PrimaryType::kF32, uint64_t,
891        uint8_t, float);
892   CASE(OverheadType::kU32, OverheadType::kU64, PrimaryType::kF32, uint32_t,
893        uint64_t, float);
894   CASE(OverheadType::kU32, OverheadType::kU32, PrimaryType::kF32, uint32_t,
895        uint32_t, float);
896   CASE(OverheadType::kU32, OverheadType::kU16, PrimaryType::kF32, uint32_t,
897        uint16_t, float);
898   CASE(OverheadType::kU32, OverheadType::kU8, PrimaryType::kF32, uint32_t,
899        uint8_t, float);
900   CASE(OverheadType::kU16, OverheadType::kU64, PrimaryType::kF32, uint16_t,
901        uint64_t, float);
902   CASE(OverheadType::kU16, OverheadType::kU32, PrimaryType::kF32, uint16_t,
903        uint32_t, float);
904   CASE(OverheadType::kU16, OverheadType::kU16, PrimaryType::kF32, uint16_t,
905        uint16_t, float);
906   CASE(OverheadType::kU16, OverheadType::kU8, PrimaryType::kF32, uint16_t,
907        uint8_t, float);
908   CASE(OverheadType::kU8, OverheadType::kU64, PrimaryType::kF32, uint8_t,
909        uint64_t, float);
910   CASE(OverheadType::kU8, OverheadType::kU32, PrimaryType::kF32, uint8_t,
911        uint32_t, float);
912   CASE(OverheadType::kU8, OverheadType::kU16, PrimaryType::kF32, uint8_t,
913        uint16_t, float);
914   CASE(OverheadType::kU8, OverheadType::kU8, PrimaryType::kF32, uint8_t,
915        uint8_t, float);
916 
917   // Integral matrices with both overheads of the same type.
918   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI64, uint64_t, int64_t);
919   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI32, uint64_t, int32_t);
920   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI16, uint64_t, int16_t);
921   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI8, uint64_t, int8_t);
922   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI32, uint32_t, int32_t);
923   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI16, uint32_t, int16_t);
924   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI8, uint32_t, int8_t);
925   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI32, uint16_t, int32_t);
926   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI16, uint16_t, int16_t);
927   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI8, uint16_t, int8_t);
928   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI32, uint8_t, int32_t);
929   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI16, uint8_t, int16_t);
930   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI8, uint8_t, int8_t);
931 
932   // Unsupported case (add above if needed).
933   fputs("unsupported combination of types\n", stderr);
934   exit(1);
935 }
936 
937 /// Methods that provide direct access to pointers.
938 IMPL_GETOVERHEAD(sparsePointers, index_t, getPointers)
939 IMPL_GETOVERHEAD(sparsePointers64, uint64_t, getPointers)
940 IMPL_GETOVERHEAD(sparsePointers32, uint32_t, getPointers)
941 IMPL_GETOVERHEAD(sparsePointers16, uint16_t, getPointers)
942 IMPL_GETOVERHEAD(sparsePointers8, uint8_t, getPointers)
943 
944 /// Methods that provide direct access to indices.
945 IMPL_GETOVERHEAD(sparseIndices, index_t, getIndices)
946 IMPL_GETOVERHEAD(sparseIndices64, uint64_t, getIndices)
947 IMPL_GETOVERHEAD(sparseIndices32, uint32_t, getIndices)
948 IMPL_GETOVERHEAD(sparseIndices16, uint16_t, getIndices)
949 IMPL_GETOVERHEAD(sparseIndices8, uint8_t, getIndices)
950 
951 /// Methods that provide direct access to values.
952 IMPL_SPARSEVALUES(sparseValuesF64, double, getValues)
953 IMPL_SPARSEVALUES(sparseValuesF32, float, getValues)
954 IMPL_SPARSEVALUES(sparseValuesI64, int64_t, getValues)
955 IMPL_SPARSEVALUES(sparseValuesI32, int32_t, getValues)
956 IMPL_SPARSEVALUES(sparseValuesI16, int16_t, getValues)
957 IMPL_SPARSEVALUES(sparseValuesI8, int8_t, getValues)
958 
959 /// Helper to add value to coordinate scheme, one per value type.
960 IMPL_ADDELT(addEltF64, double)
961 IMPL_ADDELT(addEltF32, float)
962 IMPL_ADDELT(addEltI64, int64_t)
963 IMPL_ADDELT(addEltI32, int32_t)
964 IMPL_ADDELT(addEltI16, int16_t)
965 IMPL_ADDELT(addEltI8, int8_t)
966 
967 /// Helper to enumerate elements of coordinate scheme, one per value type.
968 IMPL_GETNEXT(getNextF64, double)
969 IMPL_GETNEXT(getNextF32, float)
970 IMPL_GETNEXT(getNextI64, int64_t)
971 IMPL_GETNEXT(getNextI32, int32_t)
972 IMPL_GETNEXT(getNextI16, int16_t)
973 IMPL_GETNEXT(getNextI8, int8_t)
974 
975 /// Helper to insert elements in lexicographical index order, one per value
976 /// type.
977 IMPL_LEXINSERT(lexInsertF64, double)
978 IMPL_LEXINSERT(lexInsertF32, float)
979 IMPL_LEXINSERT(lexInsertI64, int64_t)
980 IMPL_LEXINSERT(lexInsertI32, int32_t)
981 IMPL_LEXINSERT(lexInsertI16, int16_t)
982 IMPL_LEXINSERT(lexInsertI8, int8_t)
983 
984 /// Helper to insert using expansion, one per value type.
985 IMPL_EXPINSERT(expInsertF64, double)
986 IMPL_EXPINSERT(expInsertF32, float)
987 IMPL_EXPINSERT(expInsertI64, int64_t)
988 IMPL_EXPINSERT(expInsertI32, int32_t)
989 IMPL_EXPINSERT(expInsertI16, int16_t)
990 IMPL_EXPINSERT(expInsertI8, int8_t)
991 
992 #undef CASE
993 #undef IMPL_SPARSEVALUES
994 #undef IMPL_GETOVERHEAD
995 #undef IMPL_ADDELT
996 #undef IMPL_GETNEXT
997 #undef IMPL_LEXINSERT
998 #undef IMPL_EXPINSERT
999 
1000 //===----------------------------------------------------------------------===//
1001 //
1002 // Public API with methods that accept C-style data structures to interact
1003 // with sparse tensors, which are only visible as opaque pointers externally.
1004 // These methods can be used both by MLIR compiler-generated code as well as by
1005 // an external runtime that wants to interact with MLIR compiler-generated code.
1006 //
1007 //===----------------------------------------------------------------------===//
1008 
1009 /// Helper method to read a sparse tensor filename from the environment,
1010 /// defined with the naming convention ${TENSOR0}, ${TENSOR1}, etc.
1011 char *getTensorFilename(index_t id) {
1012   char var[80];
1013   sprintf(var, "TENSOR%" PRIu64, id);
1014   char *env = getenv(var);
1015   return env;
1016 }
1017 
1018 /// Returns size of sparse tensor in given dimension.
1019 index_t sparseDimSize(void *tensor, index_t d) {
1020   return static_cast<SparseTensorStorageBase *>(tensor)->getDimSize(d);
1021 }
1022 
1023 /// Finalizes lexicographic insertions.
1024 void endInsert(void *tensor) {
1025   return static_cast<SparseTensorStorageBase *>(tensor)->endInsert();
1026 }
1027 
1028 /// Releases sparse tensor storage.
1029 void delSparseTensor(void *tensor) {
1030   delete static_cast<SparseTensorStorageBase *>(tensor);
1031 }
1032 
1033 /// Initializes sparse tensor from a COO-flavored format expressed using C-style
1034 /// data structures. The expected parameters are:
1035 ///
1036 ///   rank:    rank of tensor
1037 ///   nse:     number of specified elements (usually the nonzeros)
1038 ///   shape:   array with dimension size for each rank
1039 ///   values:  a "nse" array with values for all specified elements
1040 ///   indices: a flat "nse x rank" array with indices for all specified elements
1041 ///
1042 /// For example, the sparse matrix
1043 ///     | 1.0 0.0 0.0 |
1044 ///     | 0.0 5.0 3.0 |
1045 /// can be passed as
1046 ///      rank    = 2
1047 ///      nse     = 3
1048 ///      shape   = [2, 3]
1049 ///      values  = [1.0, 5.0, 3.0]
1050 ///      indices = [ 0, 0,  1, 1,  1, 2]
1051 //
1052 // TODO: for now f64 tensors only, no dim ordering, all dimensions compressed
1053 //
1054 void *convertToMLIRSparseTensor(uint64_t rank, uint64_t nse, uint64_t *shape,
1055                                 double *values, uint64_t *indices) {
1056   // Setup all-dims compressed and default ordering.
1057   std::vector<DimLevelType> sparse(rank, DimLevelType::kCompressed);
1058   std::vector<uint64_t> perm(rank);
1059   std::iota(perm.begin(), perm.end(), 0);
1060   // Convert external format to internal COO.
1061   SparseTensorCOO<double> *tensor = SparseTensorCOO<double>::newSparseTensorCOO(
1062       rank, shape, perm.data(), nse);
1063   std::vector<uint64_t> idx(rank);
1064   for (uint64_t i = 0, base = 0; i < nse; i++) {
1065     for (uint64_t r = 0; r < rank; r++)
1066       idx[r] = indices[base + r];
1067     tensor->add(idx, values[i]);
1068     base += rank;
1069   }
1070   // Return sparse tensor storage format as opaque pointer.
1071   return SparseTensorStorage<uint64_t, uint64_t, double>::newSparseTensor(
1072       rank, shape, perm.data(), sparse.data(), tensor);
1073 }
1074 
1075 /// Converts a sparse tensor to COO-flavored format expressed using C-style
1076 /// data structures. The expected output parameters are pointers for these
1077 /// values:
1078 ///
1079 ///   rank:    rank of tensor
1080 ///   nse:     number of specified elements (usually the nonzeros)
1081 ///   shape:   array with dimension size for each rank
1082 ///   values:  a "nse" array with values for all specified elements
1083 ///   indices: a flat "nse x rank" array with indices for all specified elements
1084 ///
1085 /// The input is a pointer to SparseTensorStorage<P, I, V>, typically returned
1086 /// from convertToMLIRSparseTensor.
1087 ///
1088 //  TODO: Currently, values are copied from SparseTensorStorage to
1089 //  SparseTensorCOO, then to the output. We may want to reduce the number of
1090 //  copies.
1091 //
1092 //  TODO: for now f64 tensors only, no dim ordering, all dimensions compressed
1093 //
1094 void convertFromMLIRSparseTensor(void *tensor, uint64_t *pRank, uint64_t *pNse,
1095                                  uint64_t **pShape, double **pValues,
1096                                  uint64_t **pIndices) {
1097   SparseTensorStorage<uint64_t, uint64_t, double> *sparseTensor =
1098       static_cast<SparseTensorStorage<uint64_t, uint64_t, double> *>(tensor);
1099   uint64_t rank = sparseTensor->getRank();
1100   std::vector<uint64_t> perm(rank);
1101   std::iota(perm.begin(), perm.end(), 0);
1102   SparseTensorCOO<double> *coo = sparseTensor->toCOO(perm.data());
1103 
1104   const std::vector<Element<double>> &elements = coo->getElements();
1105   uint64_t nse = elements.size();
1106 
1107   uint64_t *shape = new uint64_t[rank];
1108   for (uint64_t i = 0; i < rank; i++)
1109     shape[i] = coo->getSizes()[i];
1110 
1111   double *values = new double[nse];
1112   uint64_t *indices = new uint64_t[rank * nse];
1113 
1114   for (uint64_t i = 0, base = 0; i < nse; i++) {
1115     values[i] = elements[i].value;
1116     for (uint64_t j = 0; j < rank; j++)
1117       indices[base + j] = elements[i].indices[j];
1118     base += rank;
1119   }
1120 
1121   delete coo;
1122   *pRank = rank;
1123   *pNse = nse;
1124   *pShape = shape;
1125   *pValues = values;
1126   *pIndices = indices;
1127 }
1128 } // extern "C"
1129 
1130 #endif // MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS
1131