1 //===- SparseTensorConversion.cpp - Sparse tensor primitives conversion ---===//
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 // Convert sparse tensor primitives to calls into a runtime support library.
10 // Note that this is a current implementation choice to keep the conversion
11 // simple. In principle, these primitives could also be converted to actual
12 // elaborate IR code that implements the primitives on the selected sparse
13 // tensor storage schemes.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "CodegenUtils.h"
18 
19 #include "mlir/Dialect/Bufferization/IR/Bufferization.h"
20 #include "mlir/Dialect/Func/IR/FuncOps.h"
21 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
22 #include "mlir/Dialect/Linalg/Utils/Utils.h"
23 #include "mlir/Dialect/MemRef/IR/MemRef.h"
24 #include "mlir/Dialect/SCF/SCF.h"
25 #include "mlir/Dialect/SparseTensor/IR/SparseTensor.h"
26 #include "mlir/Dialect/SparseTensor/Transforms/Passes.h"
27 #include "mlir/Dialect/Tensor/IR/Tensor.h"
28 #include "mlir/ExecutionEngine/SparseTensorUtils.h"
29 #include "mlir/Transforms/DialectConversion.h"
30 
31 using namespace mlir;
32 using namespace mlir::sparse_tensor;
33 
34 namespace {
35 
36 /// Shorthand aliases for the `emitCInterface` argument to `getFunc()`,
37 /// `createFuncCall()`, and `replaceOpWithFuncCall()`.
38 enum class EmitCInterface : bool { Off = false, On = true };
39 
40 //===----------------------------------------------------------------------===//
41 // Helper methods.
42 //===----------------------------------------------------------------------===//
43 
44 /// Returns the equivalent of `void*` for opaque arguments to the
45 /// execution engine.
46 static Type getOpaquePointerType(OpBuilder &builder) {
47   return LLVM::LLVMPointerType::get(builder.getI8Type());
48 }
49 
50 /// Returns a function reference (first hit also inserts into module). Sets
51 /// the "_emit_c_interface" on the function declaration when requested,
52 /// so that LLVM lowering generates a wrapper function that takes care
53 /// of ABI complications with passing in and returning MemRefs to C functions.
54 static FlatSymbolRefAttr getFunc(Operation *op, StringRef name,
55                                  TypeRange resultType, ValueRange operands,
56                                  EmitCInterface emitCInterface) {
57   MLIRContext *context = op->getContext();
58   auto module = op->getParentOfType<ModuleOp>();
59   auto result = SymbolRefAttr::get(context, name);
60   auto func = module.lookupSymbol<func::FuncOp>(result.getAttr());
61   if (!func) {
62     OpBuilder moduleBuilder(module.getBodyRegion());
63     func = moduleBuilder.create<func::FuncOp>(
64         op->getLoc(), name,
65         FunctionType::get(context, operands.getTypes(), resultType));
66     func.setPrivate();
67     if (static_cast<bool>(emitCInterface))
68       func->setAttr("llvm.emit_c_interface", UnitAttr::get(context));
69   }
70   return result;
71 }
72 
73 /// Creates a `CallOp` to the function reference returned by `getFunc()`.
74 static func::CallOp createFuncCall(OpBuilder &builder, Operation *op,
75                                    StringRef name, TypeRange resultType,
76                                    ValueRange operands,
77                                    EmitCInterface emitCInterface) {
78   auto fn = getFunc(op, name, resultType, operands, emitCInterface);
79   return builder.create<func::CallOp>(op->getLoc(), resultType, fn, operands);
80 }
81 
82 /// Replaces the `op` with  a `CallOp` to the function reference returned
83 /// by `getFunc()`.
84 static func::CallOp replaceOpWithFuncCall(RewriterBase &rewriter, Operation *op,
85                                           StringRef name, TypeRange resultType,
86                                           ValueRange operands,
87                                           EmitCInterface emitCInterface) {
88   auto fn = getFunc(op, name, resultType, operands, emitCInterface);
89   return rewriter.replaceOpWithNewOp<func::CallOp>(op, resultType, fn,
90                                                    operands);
91 }
92 
93 /// Generates dimension size call.
94 static Value genDimSizeCall(OpBuilder &builder, Operation *op,
95                             SparseTensorEncodingAttr &enc, Value src,
96                             int64_t idx) {
97   // Permute the index according to an optional dimension ordering.
98   if (AffineMap p = enc.getDimOrdering())
99     idx = p.getPermutedPosition(idx);
100   // Generate the call.
101   StringRef name = "sparseDimSize";
102   SmallVector<Value, 2> params{src, constantIndex(builder, op->getLoc(), idx)};
103   Type iTp = builder.getIndexType();
104   return createFuncCall(builder, op, name, iTp, params, EmitCInterface::Off)
105       .getResult(0);
106 }
107 
108 /// Generates a call into the "swiss army knife" method of the sparse runtime
109 /// support library for materializing sparse tensors into the computation.
110 static Value genNewCall(OpBuilder &builder, Operation *op,
111                         ArrayRef<Value> params) {
112   StringRef name = "newSparseTensor";
113   Type pTp = getOpaquePointerType(builder);
114   return createFuncCall(builder, op, name, pTp, params, EmitCInterface::On)
115       .getResult(0);
116 }
117 
118 /// Populates given sizes array from type.
119 static void sizesFromType(OpBuilder &builder, SmallVector<Value, 4> &sizes,
120                           Location loc, ShapedType stp) {
121   auto shape = stp.getShape();
122   for (unsigned i = 0, rank = stp.getRank(); i < rank; i++) {
123     uint64_t s = shape[i] == ShapedType::kDynamicSize ? 0 : shape[i];
124     sizes.push_back(constantIndex(builder, loc, s));
125   }
126 }
127 
128 /// Populates given sizes array from source.
129 static void sizesFromSrc(OpBuilder &builder, SmallVector<Value, 4> &sizes,
130                          Location loc, Value src) {
131   unsigned rank = src.getType().cast<ShapedType>().getRank();
132   for (unsigned i = 0; i < rank; i++)
133     sizes.push_back(linalg::createOrFoldDimOp(builder, loc, src, i));
134 }
135 
136 /// Populates given sizes array from type (for static sizes) and from
137 /// an already converted into opague pointer source (for dynamic sizes).
138 static void sizesFromPtr(OpBuilder &builder, SmallVector<Value, 4> &sizes,
139                          Operation *op, SparseTensorEncodingAttr &enc,
140                          ShapedType stp, Value src) {
141   Location loc = op->getLoc();
142   auto shape = stp.getShape();
143   for (unsigned i = 0, rank = stp.getRank(); i < rank; i++)
144     if (shape[i] == ShapedType::kDynamicSize)
145       sizes.push_back(genDimSizeCall(builder, op, enc, src, i));
146     else
147       sizes.push_back(constantIndex(builder, loc, shape[i]));
148 }
149 
150 /// Generates an uninitialized temporary buffer of the given size and
151 /// type, but returns it as type `memref<? x $tp>` (rather than as type
152 /// `memref<$sz x $tp>`).
153 static Value genAlloca(OpBuilder &builder, Location loc, Value sz, Type tp) {
154   auto memTp = MemRefType::get({ShapedType::kDynamicSize}, tp);
155   return builder.create<memref::AllocaOp>(loc, memTp, ValueRange{sz});
156 }
157 
158 /// Generates an uninitialized buffer of the given size and type,
159 /// but returns it as type `memref<? x $tp>` (rather than as type
160 /// `memref<$sz x $tp>`). Unlike temporary buffers on the stack,
161 /// this buffer must be explicitly deallocated by client.
162 static Value genAlloc(RewriterBase &rewriter, Location loc, Value sz, Type tp) {
163   auto memTp = MemRefType::get({ShapedType::kDynamicSize}, tp);
164   return rewriter.create<memref::AllocOp>(loc, memTp, ValueRange{sz});
165 }
166 
167 /// Generates an uninitialized temporary buffer of the given size and
168 /// type, but returns it as type `memref<? x $tp>` (rather than as type
169 /// `memref<$sz x $tp>`).
170 static Value genAlloca(OpBuilder &builder, Location loc, unsigned sz, Type tp) {
171   return genAlloca(builder, loc, constantIndex(builder, loc, sz), tp);
172 }
173 
174 /// Generates an uninitialized temporary buffer with room for one value
175 /// of the given type, and returns the `memref<$tp>`.
176 static Value genAllocaScalar(OpBuilder &builder, Location loc, Type tp) {
177   return builder.create<memref::AllocaOp>(loc, MemRefType::get({}, tp));
178 }
179 
180 /// Generates a temporary buffer of the given type and given contents.
181 static Value genBuffer(OpBuilder &builder, Location loc, ValueRange values) {
182   unsigned sz = values.size();
183   assert(sz >= 1);
184   Value buffer = genAlloca(builder, loc, sz, values[0].getType());
185   for (unsigned i = 0; i < sz; i++) {
186     Value idx = constantIndex(builder, loc, i);
187     builder.create<memref::StoreOp>(loc, values[i], buffer, idx);
188   }
189   return buffer;
190 }
191 
192 /// Populates parameters required to call the "swiss army knife" method of the
193 /// sparse runtime support library for materializing sparse tensors into the
194 /// computation.
195 static void newParams(OpBuilder &builder, SmallVector<Value, 8> &params,
196                       Operation *op, ShapedType stp,
197                       SparseTensorEncodingAttr &enc, Action action,
198                       ValueRange szs, Value ptr = Value()) {
199   Location loc = op->getLoc();
200   ArrayRef<SparseTensorEncodingAttr::DimLevelType> dlt = enc.getDimLevelType();
201   unsigned sz = dlt.size();
202   // Sparsity annotations.
203   SmallVector<Value, 4> attrs;
204   for (unsigned i = 0; i < sz; i++)
205     attrs.push_back(constantDimLevelTypeEncoding(builder, loc, dlt[i]));
206   params.push_back(genBuffer(builder, loc, attrs));
207   // Dimension sizes array of the enveloping tensor. Useful for either
208   // verification of external data, or for construction of internal data.
209   params.push_back(genBuffer(builder, loc, szs));
210   // Dimension order permutation array. This is the "identity" permutation by
211   // default, or otherwise the "reverse" permutation of a given ordering, so
212   // that indices can be mapped quickly to the right position.
213   SmallVector<Value, 4> rev(sz);
214   if (AffineMap p = enc.getDimOrdering()) {
215     for (unsigned i = 0; i < sz; i++)
216       rev[p.getDimPosition(i)] = constantIndex(builder, loc, i);
217   } else {
218     for (unsigned i = 0; i < sz; i++)
219       rev[i] = constantIndex(builder, loc, i);
220   }
221   params.push_back(genBuffer(builder, loc, rev));
222   // Secondary and primary types encoding.
223   Type elemTp = stp.getElementType();
224   params.push_back(constantPointerTypeEncoding(builder, loc, enc));
225   params.push_back(constantIndexTypeEncoding(builder, loc, enc));
226   params.push_back(constantPrimaryTypeEncoding(builder, loc, elemTp));
227   // User action.
228   params.push_back(constantAction(builder, loc, action));
229   // Payload pointer.
230   if (!ptr)
231     ptr = builder.create<LLVM::NullOp>(loc, getOpaquePointerType(builder));
232   params.push_back(ptr);
233 }
234 
235 /// Generates the code to read the value from tensor[ivs], and conditionally
236 /// stores the indices ivs to the memory in ind. The generated code looks like
237 /// the following and the insertion point after this routine is inside the
238 /// if-then branch behind the assignment to ind. This is to ensure that the
239 /// addEltX call generated after is inside the if-then branch.
240 ///    if (tensor[ivs]!=0) {
241 ///      ind = ivs
242 static Value genIndexAndValueForDense(OpBuilder &builder, Location loc,
243                                       Value tensor, Value ind, ValueRange ivs) {
244   Value val = builder.create<tensor::ExtractOp>(loc, tensor, ivs);
245   Value cond = genIsNonzero(builder, loc, val);
246   scf::IfOp ifOp = builder.create<scf::IfOp>(loc, cond, /*else*/ false);
247   builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
248   unsigned i = 0;
249   for (auto iv : ivs) {
250     Value idx = constantIndex(builder, loc, i++);
251     builder.create<memref::StoreOp>(loc, iv, ind, idx);
252   }
253   return val;
254 }
255 
256 /// Generates a call to release/delete a `SparseTensorCOO`.
257 static void genDelCOOCall(OpBuilder &builder, Operation *op, Type elemTp,
258                           Value coo) {
259   SmallString<21> name{"delSparseTensorCOO", primaryTypeFunctionSuffix(elemTp)};
260   TypeRange noTp;
261   createFuncCall(builder, op, name, noTp, coo, EmitCInterface::Off);
262 }
263 
264 /// Generates a call that adds one element to a coordinate scheme.
265 /// In particular, this generates code like the following:
266 ///   val = a[i1,..,ik];
267 ///   if val != 0
268 ///     t->add(val, [i1,..,ik], [p1,..,pk]);
269 static void genAddEltCall(OpBuilder &builder, Operation *op, Type eltType,
270                           Value ptr, Value val, Value ind, Value perm) {
271   SmallString<9> name{"addElt", primaryTypeFunctionSuffix(eltType)};
272   SmallVector<Value, 4> params{ptr, val, ind, perm};
273   Type pTp = getOpaquePointerType(builder);
274   createFuncCall(builder, op, name, pTp, params, EmitCInterface::On);
275 }
276 
277 /// Generates a call to `iter->getNext()`.  If there is a next element,
278 /// then it is copied into the out-parameters `ind` and `elemPtr`,
279 /// and the return value is true.  If there isn't a next element, then
280 /// the memory for `iter` is freed and the return value is false.
281 static Value genGetNextCall(OpBuilder &builder, Operation *op, Value iter,
282                             Value ind, Value elemPtr) {
283   Type elemTp = elemPtr.getType().cast<ShapedType>().getElementType();
284   SmallString<10> name{"getNext", primaryTypeFunctionSuffix(elemTp)};
285   SmallVector<Value, 3> params{iter, ind, elemPtr};
286   Type i1 = builder.getI1Type();
287   return createFuncCall(builder, op, name, i1, params, EmitCInterface::On)
288       .getResult(0);
289 }
290 
291 /// If the tensor is a sparse constant, generates and returns the pair of
292 /// the constants for the indices and the values.
293 static Optional<std::pair<Value, Value>>
294 genSplitSparseConstant(OpBuilder &builder, Location loc, Value tensor) {
295   if (auto constOp = tensor.getDefiningOp<arith::ConstantOp>()) {
296     if (auto attr = constOp.getValue().dyn_cast<SparseElementsAttr>()) {
297       DenseElementsAttr indicesAttr = attr.getIndices();
298       Value indices = builder.create<arith::ConstantOp>(loc, indicesAttr);
299       DenseElementsAttr valuesAttr = attr.getValues();
300       Value values = builder.create<arith::ConstantOp>(loc, valuesAttr);
301       return std::make_pair(indices, values);
302     }
303   }
304   return {};
305 }
306 
307 /// Generates the code to copy the index at indices[ivs] to ind, and return
308 /// the value at value[ivs].
309 static Value genIndexAndValueForSparse(OpBuilder &builder, Location loc,
310                                        Value indices, Value values, Value ind,
311                                        ValueRange ivs, unsigned rank) {
312   for (unsigned i = 0; i < rank; i++) {
313     Value idx = constantIndex(builder, loc, i);
314     Value val = builder.create<tensor::ExtractOp>(loc, indices,
315                                                   ValueRange{ivs[0], idx});
316     val = builder.create<arith::IndexCastOp>(loc, builder.getIndexType(), val);
317     builder.create<memref::StoreOp>(loc, val, ind, idx);
318   }
319   return builder.create<tensor::ExtractOp>(loc, values, ivs[0]);
320 }
321 
322 /// Generates code to allocate a tensor of the given type, and zero
323 /// initialize it.  If the tensor type has any dynamic sizes, then the
324 /// `sizes` parameter should be as filled by sizesFromPtr(); that way
325 /// we can reuse the genDimSizeCall() results generated by sizesFromPtr().
326 static Value allocDenseTensor(OpBuilder &builder, Location loc,
327                               RankedTensorType tensorTp, ValueRange sizes) {
328   Type elemTp = tensorTp.getElementType();
329   auto shape = tensorTp.getShape();
330   auto memTp = MemRefType::get(shape, elemTp);
331   SmallVector<Value> dynamicSizes;
332   for (unsigned i = 0, rank = tensorTp.getRank(); i < rank; i++) {
333     if (shape[i] == ShapedType::kDynamicSize)
334       dynamicSizes.push_back(sizes[i]);
335   }
336   Value mem = builder.create<memref::AllocOp>(loc, memTp, dynamicSizes);
337   Value zero = constantZero(builder, loc, elemTp);
338   builder.create<linalg::FillOp>(loc, ValueRange{zero}, ValueRange{mem});
339   return mem;
340 }
341 
342 /// Inserts the element returned by genGetNextCall(_, ind, elemPtr) into
343 /// the tensor created by allocDenseTensor().  The `rank` is the rank
344 /// of the `tensor` and the length of `ind`.
345 static void insertScalarIntoDenseTensor(OpBuilder &builder, Location loc,
346                                         Value elemPtr, Value tensor,
347                                         unsigned rank, Value ind) {
348   SmallVector<Value, 4> ivs;
349   ivs.reserve(rank);
350   for (unsigned i = 0; i < rank; i++) {
351     Value idx = constantIndex(builder, loc, i);
352     ivs.push_back(builder.create<memref::LoadOp>(loc, ind, idx));
353   }
354   Value elemV = builder.create<memref::LoadOp>(loc, elemPtr);
355   builder.create<memref::StoreOp>(loc, elemV, tensor, ivs);
356 }
357 
358 //===----------------------------------------------------------------------===//
359 // Conversion rules.
360 //===----------------------------------------------------------------------===//
361 
362 /// Sparse conversion rule for returns.
363 class SparseReturnConverter : public OpConversionPattern<func::ReturnOp> {
364 public:
365   using OpConversionPattern::OpConversionPattern;
366   LogicalResult
367   matchAndRewrite(func::ReturnOp op, OpAdaptor adaptor,
368                   ConversionPatternRewriter &rewriter) const override {
369     rewriter.replaceOpWithNewOp<func::ReturnOp>(op, adaptor.getOperands());
370     return success();
371   }
372 };
373 
374 /// Sparse conversion rule for dimension accesses.
375 class SparseTensorToDimSizeConverter
376     : public OpConversionPattern<tensor::DimOp> {
377 public:
378   using OpConversionPattern::OpConversionPattern;
379   LogicalResult
380   matchAndRewrite(tensor::DimOp op, OpAdaptor adaptor,
381                   ConversionPatternRewriter &rewriter) const override {
382     // Only rewrite annotated DimOp with constant index.
383     auto enc = getSparseTensorEncoding(op.source().getType());
384     if (!enc)
385       return failure();
386     Optional<int64_t> index = op.getConstantIndex();
387     if (!index.hasValue())
388       return failure();
389     // Generate the call.
390     Value src = adaptor.getOperands()[0];
391     int64_t idx = index.getValue();
392     rewriter.replaceOp(op, genDimSizeCall(rewriter, op, enc, src, idx));
393     return success();
394   }
395 };
396 
397 /// Sparse conversion rule for trivial tensor casts.
398 class SparseCastConverter : public OpConversionPattern<tensor::CastOp> {
399   using OpConversionPattern::OpConversionPattern;
400   LogicalResult
401   matchAndRewrite(tensor::CastOp op, OpAdaptor adaptor,
402                   ConversionPatternRewriter &rewriter) const override {
403     // Only rewrite identically annotated source/dest.
404     auto encDst = getSparseTensorEncoding(op.getType());
405     auto encSrc = getSparseTensorEncoding(op.source().getType());
406     if (!encDst || encDst != encSrc)
407       return failure();
408     rewriter.replaceOp(op, adaptor.getOperands());
409     return success();
410   }
411 };
412 
413 /// Sparse conversion rule for the new operator.
414 class SparseTensorNewConverter : public OpConversionPattern<NewOp> {
415   using OpConversionPattern::OpConversionPattern;
416   LogicalResult
417   matchAndRewrite(NewOp op, OpAdaptor adaptor,
418                   ConversionPatternRewriter &rewriter) const override {
419     Type resType = op.getType();
420     auto enc = getSparseTensorEncoding(resType);
421     if (!enc)
422       return failure();
423     // Generate the call to construct tensor from ptr. The sizes are
424     // inferred from the result type of the new operator.
425     SmallVector<Value, 4> sizes;
426     SmallVector<Value, 8> params;
427     ShapedType stp = resType.cast<ShapedType>();
428     sizesFromType(rewriter, sizes, op.getLoc(), stp);
429     Value ptr = adaptor.getOperands()[0];
430     newParams(rewriter, params, op, stp, enc, Action::kFromFile, sizes, ptr);
431     rewriter.replaceOp(op, genNewCall(rewriter, op, params));
432     return success();
433   }
434 };
435 
436 /// Sparse conversion rule for the init operator.
437 class SparseTensorInitConverter : public OpConversionPattern<InitOp> {
438   using OpConversionPattern::OpConversionPattern;
439   LogicalResult
440   matchAndRewrite(InitOp op, OpAdaptor adaptor,
441                   ConversionPatternRewriter &rewriter) const override {
442     Type resType = op.getType();
443     auto enc = getSparseTensorEncoding(resType);
444     if (!enc)
445       return failure();
446     // Generate the call to construct empty tensor. The sizes are
447     // explicitly defined by the arguments to the init operator.
448     SmallVector<Value, 8> params;
449     ShapedType stp = resType.cast<ShapedType>();
450     newParams(rewriter, params, op, stp, enc, Action::kEmpty,
451               adaptor.getOperands());
452     rewriter.replaceOp(op, genNewCall(rewriter, op, params));
453     return success();
454   }
455 };
456 
457 /// Sparse conversion rule for the convert operator.
458 class SparseTensorConvertConverter : public OpConversionPattern<ConvertOp> {
459   /// Options to control sparse code generation.
460   SparseTensorConversionOptions options;
461 
462 public:
463   using OpConversionPattern::OpConversionPattern;
464   SparseTensorConvertConverter(MLIRContext *context,
465                                SparseTensorConversionOptions o)
466       : OpConversionPattern<ConvertOp>(context), options(o) {}
467   SparseTensorConvertConverter(TypeConverter &typeConv, MLIRContext *context,
468                                SparseTensorConversionOptions o)
469       : OpConversionPattern<ConvertOp>(typeConv, context), options(o) {}
470 
471   LogicalResult
472   matchAndRewrite(ConvertOp op, OpAdaptor adaptor,
473                   ConversionPatternRewriter &rewriter) const override {
474     Location loc = op->getLoc();
475     Type resType = op.getType();
476     Type srcType = op.source().getType();
477     auto encDst = getSparseTensorEncoding(resType);
478     auto encSrc = getSparseTensorEncoding(srcType);
479     Value src = adaptor.getOperands()[0];
480     if (encDst && encSrc) {
481       // This is a sparse => sparse conversion, which is handled as follows:
482       //   t = src->toCOO();         ; src to COO in dst order
483       //   dst = newSparseTensor(t)
484       // Using the coordinate scheme as an intermediate does not always
485       // yield the fastest conversion but avoids the need for a full
486       // O(N^2) conversion matrix.
487       if (encDst == encSrc) {
488         rewriter.replaceOp(op, adaptor.getOperands()); // hidden nop cast
489         return success();
490       }
491       SmallVector<Value, 4> sizes;
492       SmallVector<Value, 8> params;
493       ShapedType stp = srcType.cast<ShapedType>();
494       sizesFromPtr(rewriter, sizes, op, encSrc, stp, src);
495       // Set up encoding with right mix of src and dst so that the two
496       // method calls can share most parameters, while still providing
497       // the correct sparsity information to either of them.
498       auto enc = SparseTensorEncodingAttr::get(
499           op->getContext(), encDst.getDimLevelType(), encDst.getDimOrdering(),
500           encSrc.getPointerBitWidth(), encSrc.getIndexBitWidth());
501       newParams(rewriter, params, op, stp, enc, Action::kToCOO, sizes, src);
502       Value coo = genNewCall(rewriter, op, params);
503       params[3] = constantPointerTypeEncoding(rewriter, loc, encDst);
504       params[4] = constantIndexTypeEncoding(rewriter, loc, encDst);
505       params[6] = constantAction(rewriter, loc, Action::kFromCOO);
506       params[7] = coo;
507       Value dst = genNewCall(rewriter, op, params);
508       genDelCOOCall(rewriter, op, stp.getElementType(), coo);
509       rewriter.replaceOp(op, dst);
510       return success();
511     }
512     if (!encDst && encSrc) {
513       // This is sparse => dense conversion, which is handled as follows:
514       //   dst = new Tensor(0);
515       //   iter = src->toCOO();
516       //   iter->startIterator();
517       //   while (elem = iter->getNext()) {
518       //     dst[elem.indices] = elem.value;
519       //   }
520       RankedTensorType dstTensorTp = resType.cast<RankedTensorType>();
521       RankedTensorType srcTensorTp = srcType.cast<RankedTensorType>();
522       unsigned rank = dstTensorTp.getRank();
523       Type elemTp = dstTensorTp.getElementType();
524       // Fabricate a no-permutation encoding for newParams().
525       // The pointer/index types must be those of `src`.
526       // The dimLevelTypes aren't actually used by Action::kToIterator.
527       encDst = SparseTensorEncodingAttr::get(
528           op->getContext(),
529           SmallVector<SparseTensorEncodingAttr::DimLevelType>(
530               rank, SparseTensorEncodingAttr::DimLevelType::Dense),
531           AffineMap(), encSrc.getPointerBitWidth(), encSrc.getIndexBitWidth());
532       SmallVector<Value, 4> sizes;
533       SmallVector<Value, 8> params;
534       sizesFromPtr(rewriter, sizes, op, encSrc, srcTensorTp, src);
535       newParams(rewriter, params, op, dstTensorTp, encDst, Action::kToIterator,
536                 sizes, src);
537       Value iter = genNewCall(rewriter, op, params);
538       Value ind = genAlloca(rewriter, loc, rank, rewriter.getIndexType());
539       Value elemPtr = genAllocaScalar(rewriter, loc, elemTp);
540       Value dst = allocDenseTensor(rewriter, loc, dstTensorTp, sizes);
541       SmallVector<Value> noArgs;
542       SmallVector<Type> noTypes;
543       auto whileOp = rewriter.create<scf::WhileOp>(loc, noTypes, noArgs);
544       Block *before = rewriter.createBlock(&whileOp.getBefore(), {}, noTypes);
545       rewriter.setInsertionPointToEnd(before);
546       Value cond = genGetNextCall(rewriter, op, iter, ind, elemPtr);
547       rewriter.create<scf::ConditionOp>(loc, cond, before->getArguments());
548       Block *after = rewriter.createBlock(&whileOp.getAfter(), {}, noTypes);
549       rewriter.setInsertionPointToStart(after);
550       insertScalarIntoDenseTensor(rewriter, loc, elemPtr, dst, rank, ind);
551       rewriter.create<scf::YieldOp>(loc);
552       rewriter.setInsertionPointAfter(whileOp);
553       genDelCOOCall(rewriter, op, elemTp, iter);
554       rewriter.replaceOpWithNewOp<bufferization::ToTensorOp>(op, resType, dst);
555       return success();
556     }
557     if (!encDst && !encSrc) {
558       // dense => dense
559       return failure();
560     }
561     // This is a dense => sparse conversion or a sparse constant in COO =>
562     // sparse conversion, which is handled as follows:
563     //   t = newSparseCOO()
564     //   ...code to fill the COO tensor t...
565     //   s = newSparseTensor(t)
566     //
567     // To fill the COO tensor from a dense tensor:
568     //   for i1 in dim1
569     //    ..
570     //     for ik in dimk
571     //       val = a[i1,..,ik]
572     //       if val != 0
573     //         t->add(val, [i1,..,ik], [p1,..,pk])
574     //
575     // To fill the COO tensor from a sparse constant in COO format:
576     //   for i in range(NNZ)
577     //     val = values[i]
578     //     [i1,..,ik] = indices[i]
579     //     t->add(val, [i1,..,ik], [p1,..,pk])
580     //
581     // Note that the dense tensor traversal code is actually implemented
582     // using MLIR IR to avoid having to expose too much low-level
583     // memref traversal details to the runtime support library.
584     // Also note that the code below only generates the "new" ops and
585     // the loop-nest per se; whereas the entire body of the innermost
586     // loop is generated by genAddElt().
587     ShapedType stp = resType.cast<ShapedType>();
588     unsigned rank = stp.getRank();
589     SmallVector<Value, 4> sizes;
590     SmallVector<Value, 8> params;
591     sizesFromSrc(rewriter, sizes, loc, src);
592     newParams(rewriter, params, op, stp, encDst, Action::kEmptyCOO, sizes);
593     Value coo = genNewCall(rewriter, op, params);
594     Value ind = genAlloca(rewriter, loc, rank, rewriter.getIndexType());
595     Value perm = params[2];
596     SmallVector<Value> lo;
597     SmallVector<Value> hi;
598     SmallVector<Value> st;
599     Value zero = constantIndex(rewriter, loc, 0);
600     Value one = constantIndex(rewriter, loc, 1);
601     auto indicesValues = genSplitSparseConstant(rewriter, loc, src);
602     bool isCOOConstant = indicesValues.hasValue();
603     Value indices;
604     Value values;
605     if (isCOOConstant) {
606       indices = indicesValues->first;
607       values = indicesValues->second;
608       lo.push_back(zero);
609       hi.push_back(linalg::createOrFoldDimOp(rewriter, loc, values, 0));
610       st.push_back(one);
611     } else {
612       for (unsigned i = 0; i < rank; i++) {
613         lo.push_back(zero);
614         hi.push_back(linalg::createOrFoldDimOp(rewriter, loc, src, i));
615         st.push_back(one);
616       }
617     }
618     Type eltType = stp.getElementType();
619     scf::buildLoopNest(
620         rewriter, op.getLoc(), lo, hi, st, {},
621         [&](OpBuilder &builder, Location loc, ValueRange ivs,
622             ValueRange args) -> scf::ValueVector {
623           Value val;
624           if (isCOOConstant)
625             val = genIndexAndValueForSparse(rewriter, loc, indices, values, ind,
626                                             ivs, rank);
627           else
628             val = genIndexAndValueForDense(rewriter, loc, src, ind, ivs);
629           genAddEltCall(rewriter, op, eltType, coo, val, ind, perm);
630           return {};
631         });
632     // Final call to construct sparse tensor storage.
633     params[6] = constantAction(rewriter, loc, Action::kFromCOO);
634     params[7] = coo;
635     Value dst = genNewCall(rewriter, op, params);
636     genDelCOOCall(rewriter, op, eltType, coo);
637     rewriter.replaceOp(op, dst);
638     return success();
639   }
640 };
641 
642 /// Sparse conversion rule for the release operator.
643 class SparseTensorReleaseConverter : public OpConversionPattern<ReleaseOp> {
644 public:
645   using OpConversionPattern::OpConversionPattern;
646   LogicalResult
647   matchAndRewrite(ReleaseOp op, OpAdaptor adaptor,
648                   ConversionPatternRewriter &rewriter) const override {
649     StringRef name = "delSparseTensor";
650     TypeRange noTp;
651     createFuncCall(rewriter, op, name, noTp, adaptor.getOperands(),
652                    EmitCInterface::Off);
653     rewriter.eraseOp(op);
654     return success();
655   }
656 };
657 
658 /// Sparse conversion rule for pointer accesses.
659 class SparseTensorToPointersConverter
660     : public OpConversionPattern<ToPointersOp> {
661 public:
662   using OpConversionPattern::OpConversionPattern;
663   LogicalResult
664   matchAndRewrite(ToPointersOp op, OpAdaptor adaptor,
665                   ConversionPatternRewriter &rewriter) const override {
666     Type resType = op.getType();
667     Type ptrType = resType.cast<ShapedType>().getElementType();
668     SmallString<16> name{"sparsePointers", overheadTypeFunctionSuffix(ptrType)};
669     replaceOpWithFuncCall(rewriter, op, name, resType, adaptor.getOperands(),
670                           EmitCInterface::On);
671     return success();
672   }
673 };
674 
675 /// Sparse conversion rule for index accesses.
676 class SparseTensorToIndicesConverter : public OpConversionPattern<ToIndicesOp> {
677 public:
678   using OpConversionPattern::OpConversionPattern;
679   LogicalResult
680   matchAndRewrite(ToIndicesOp op, OpAdaptor adaptor,
681                   ConversionPatternRewriter &rewriter) const override {
682     Type resType = op.getType();
683     Type indType = resType.cast<ShapedType>().getElementType();
684     SmallString<15> name{"sparseIndices", overheadTypeFunctionSuffix(indType)};
685     replaceOpWithFuncCall(rewriter, op, name, resType, adaptor.getOperands(),
686                           EmitCInterface::On);
687     return success();
688   }
689 };
690 
691 /// Sparse conversion rule for value accesses.
692 class SparseTensorToValuesConverter : public OpConversionPattern<ToValuesOp> {
693 public:
694   using OpConversionPattern::OpConversionPattern;
695   LogicalResult
696   matchAndRewrite(ToValuesOp op, OpAdaptor adaptor,
697                   ConversionPatternRewriter &rewriter) const override {
698     Type resType = op.getType();
699     Type eltType = resType.cast<ShapedType>().getElementType();
700     SmallString<15> name{"sparseValues", primaryTypeFunctionSuffix(eltType)};
701     replaceOpWithFuncCall(rewriter, op, name, resType, adaptor.getOperands(),
702                           EmitCInterface::On);
703     return success();
704   }
705 };
706 
707 /// Sparse conversion rule for tensor rematerialization.
708 class SparseTensorLoadConverter : public OpConversionPattern<LoadOp> {
709 public:
710   using OpConversionPattern::OpConversionPattern;
711   LogicalResult
712   matchAndRewrite(LoadOp op, OpAdaptor adaptor,
713                   ConversionPatternRewriter &rewriter) const override {
714     if (op.hasInserts()) {
715       // Finalize any pending insertions.
716       StringRef name = "endInsert";
717       TypeRange noTp;
718       createFuncCall(rewriter, op, name, noTp, adaptor.getOperands(),
719                      EmitCInterface::Off);
720     }
721     rewriter.replaceOp(op, adaptor.getOperands());
722     return success();
723   }
724 };
725 
726 /// Sparse conversion rule for inserting in lexicographic index order.
727 class SparseTensorLexInsertConverter : public OpConversionPattern<LexInsertOp> {
728 public:
729   using OpConversionPattern::OpConversionPattern;
730   LogicalResult
731   matchAndRewrite(LexInsertOp op, OpAdaptor adaptor,
732                   ConversionPatternRewriter &rewriter) const override {
733     Type elemTp = op.tensor().getType().cast<ShapedType>().getElementType();
734     SmallString<12> name{"lexInsert", primaryTypeFunctionSuffix(elemTp)};
735     TypeRange noTp;
736     replaceOpWithFuncCall(rewriter, op, name, noTp, adaptor.getOperands(),
737                           EmitCInterface::On);
738     return success();
739   }
740 };
741 
742 class SparseTensorExpandConverter : public OpConversionPattern<ExpandOp> {
743 public:
744   using OpConversionPattern::OpConversionPattern;
745   LogicalResult
746   matchAndRewrite(ExpandOp op, OpAdaptor adaptor,
747                   ConversionPatternRewriter &rewriter) const override {
748     Location loc = op->getLoc();
749     ShapedType srcType = op.tensor().getType().cast<ShapedType>();
750     Type eltType = srcType.getElementType();
751     Type boolType = rewriter.getIntegerType(1);
752     Type idxType = rewriter.getIndexType();
753     // All initialization should be done on entry of the loop nest.
754     rewriter.setInsertionPointAfter(op.tensor().getDefiningOp());
755     // Determine the size for access expansion.
756     auto enc = getSparseTensorEncoding(srcType);
757     Value src = adaptor.getOperands()[0];
758     Value sz = genDimSizeCall(rewriter, op, enc, src, srcType.getRank() - 1);
759     // Allocate temporary buffers for values, filled-switch, and indices.
760     // We do not use stack buffers for this, since the expanded size may
761     // be rather large (as it envelops a single expanded dense dimension).
762     Value values = genAlloc(rewriter, loc, sz, eltType);
763     Value filled = genAlloc(rewriter, loc, sz, boolType);
764     Value indices = genAlloc(rewriter, loc, sz, idxType);
765     Value zero = constantZero(rewriter, loc, idxType);
766     // Reset the values/filled-switch to all-zero/false. Note that this
767     // introduces an O(N) operation into the computation, but this reset
768     // operation is amortized over the innermost loops for the access
769     // pattern expansion. As noted in the operation doc, we would like
770     // to amortize this setup cost even between kernels.
771     rewriter.create<linalg::FillOp>(
772         loc, ValueRange{constantZero(rewriter, loc, eltType)},
773         ValueRange{values});
774     rewriter.create<linalg::FillOp>(
775         loc, ValueRange{constantZero(rewriter, loc, boolType)},
776         ValueRange{filled});
777     // Replace expansion op with these buffers and initial index.
778     assert(op.getNumResults() == 4);
779     rewriter.replaceOp(op, {values, filled, indices, zero});
780     return success();
781   }
782 };
783 
784 class SparseTensorCompressConverter : public OpConversionPattern<CompressOp> {
785 public:
786   using OpConversionPattern::OpConversionPattern;
787   LogicalResult
788   matchAndRewrite(CompressOp op, OpAdaptor adaptor,
789                   ConversionPatternRewriter &rewriter) const override {
790     Location loc = op->getLoc();
791     // Note that this method call resets the values/filled-switch back to
792     // all-zero/false by only iterating over the set elements, so the
793     // complexity remains proportional to the sparsity of the expanded
794     // access pattern.
795     Type elemTp = op.tensor().getType().cast<ShapedType>().getElementType();
796     SmallString<12> name{"expInsert", primaryTypeFunctionSuffix(elemTp)};
797     TypeRange noTp;
798     replaceOpWithFuncCall(rewriter, op, name, noTp, adaptor.getOperands(),
799                           EmitCInterface::On);
800     // Deallocate the buffers on exit of the loop nest.
801     Operation *parent = op;
802     for (; isa<scf::ForOp>(parent->getParentOp()) ||
803            isa<scf::WhileOp>(parent->getParentOp()) ||
804            isa<scf::ParallelOp>(parent->getParentOp()) ||
805            isa<scf::IfOp>(parent->getParentOp());
806          parent = parent->getParentOp())
807       ;
808     rewriter.setInsertionPointAfter(parent);
809     rewriter.create<memref::DeallocOp>(loc, adaptor.getOperands()[2]);
810     rewriter.create<memref::DeallocOp>(loc, adaptor.getOperands()[3]);
811     rewriter.create<memref::DeallocOp>(loc, adaptor.getOperands()[4]);
812     return success();
813   }
814 };
815 
816 class SparseTensorOutConverter : public OpConversionPattern<OutOp> {
817 public:
818   using OpConversionPattern::OpConversionPattern;
819   LogicalResult
820   matchAndRewrite(OutOp op, OpAdaptor adaptor,
821                   ConversionPatternRewriter &rewriter) const override {
822     Location loc = op->getLoc();
823     ShapedType srcType = op.tensor().getType().cast<ShapedType>();
824     // Convert to default permuted COO.
825     Value src = adaptor.getOperands()[0];
826     auto encSrc = getSparseTensorEncoding(srcType);
827     SmallVector<Value, 4> sizes;
828     SmallVector<Value, 8> params;
829     sizesFromPtr(rewriter, sizes, op, encSrc, srcType, src);
830     auto enc = SparseTensorEncodingAttr::get(
831         op->getContext(), encSrc.getDimLevelType(), AffineMap(),
832         encSrc.getPointerBitWidth(), encSrc.getIndexBitWidth());
833     newParams(rewriter, params, op, srcType, enc, Action::kToCOO, sizes, src);
834     Value coo = genNewCall(rewriter, op, params);
835     // Then output the tensor to external file with indices in the externally
836     // visible lexicographic index order. A sort is required if the source was
837     // not in that order yet (note that the sort can be dropped altogether if
838     // external format does not care about the order at all, but here we assume
839     // it does).
840     bool sort =
841         encSrc.getDimOrdering() && !encSrc.getDimOrdering().isIdentity();
842     params.clear();
843     params.push_back(coo);
844     params.push_back(adaptor.getOperands()[1]);
845     params.push_back(constantI1(rewriter, loc, sort));
846     Type eltType = srcType.getElementType();
847     SmallString<18> name{"outSparseTensor", primaryTypeFunctionSuffix(eltType)};
848     TypeRange noTp;
849     createFuncCall(rewriter, op, name, noTp, params, EmitCInterface::Off);
850     genDelCOOCall(rewriter, op, eltType, coo);
851     rewriter.eraseOp(op);
852     return success();
853   }
854 };
855 
856 } // namespace
857 
858 //===----------------------------------------------------------------------===//
859 // Public method for populating conversion rules.
860 //===----------------------------------------------------------------------===//
861 
862 /// Populates the given patterns list with conversion rules required for
863 /// the sparsification of linear algebra operations.
864 void mlir::populateSparseTensorConversionPatterns(
865     TypeConverter &typeConverter, RewritePatternSet &patterns,
866     const SparseTensorConversionOptions &options) {
867   patterns.add<SparseReturnConverter, SparseTensorToDimSizeConverter,
868                SparseCastConverter, SparseTensorNewConverter,
869                SparseTensorInitConverter, SparseTensorReleaseConverter,
870                SparseTensorToPointersConverter, SparseTensorToIndicesConverter,
871                SparseTensorToValuesConverter, SparseTensorLoadConverter,
872                SparseTensorLexInsertConverter, SparseTensorExpandConverter,
873                SparseTensorCompressConverter, SparseTensorOutConverter>(
874       typeConverter, patterns.getContext());
875   patterns.add<SparseTensorConvertConverter>(typeConverter,
876                                              patterns.getContext(), options);
877 }
878