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