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 /// Determine if the runtime library supports direct conversion to the
359 /// given target `dimTypes`.
360 static bool canUseDirectConversion(
361     ArrayRef<SparseTensorEncodingAttr::DimLevelType> dimTypes) {
362   bool alreadyCompressed = false;
363   for (uint64_t rank = dimTypes.size(), r = 0; r < rank; r++) {
364     switch (dimTypes[r]) {
365     case SparseTensorEncodingAttr::DimLevelType::Compressed:
366       if (alreadyCompressed)
367         return false; // Multiple compressed dimensions not yet supported.
368       alreadyCompressed = true;
369       break;
370     case SparseTensorEncodingAttr::DimLevelType::Dense:
371       if (alreadyCompressed)
372         return false; // Dense after Compressed not yet supported.
373       break;
374     case SparseTensorEncodingAttr::DimLevelType::Singleton:
375       // Although Singleton isn't generally supported yet, the direct
376       // conversion method doesn't have any particular problems with
377       // singleton after compressed.
378       break;
379     }
380   }
381   return true;
382 }
383 
384 //===----------------------------------------------------------------------===//
385 // Conversion rules.
386 //===----------------------------------------------------------------------===//
387 
388 /// Sparse conversion rule for returns.
389 class SparseReturnConverter : public OpConversionPattern<func::ReturnOp> {
390 public:
391   using OpConversionPattern::OpConversionPattern;
392   LogicalResult
393   matchAndRewrite(func::ReturnOp op, OpAdaptor adaptor,
394                   ConversionPatternRewriter &rewriter) const override {
395     rewriter.replaceOpWithNewOp<func::ReturnOp>(op, adaptor.getOperands());
396     return success();
397   }
398 };
399 
400 /// Sparse conversion rule for dimension accesses.
401 class SparseTensorToDimSizeConverter
402     : public OpConversionPattern<tensor::DimOp> {
403 public:
404   using OpConversionPattern::OpConversionPattern;
405   LogicalResult
406   matchAndRewrite(tensor::DimOp op, OpAdaptor adaptor,
407                   ConversionPatternRewriter &rewriter) const override {
408     // Only rewrite annotated DimOp with constant index.
409     auto enc = getSparseTensorEncoding(op.source().getType());
410     if (!enc)
411       return failure();
412     Optional<int64_t> index = op.getConstantIndex();
413     if (!index.hasValue())
414       return failure();
415     // Generate the call.
416     Value src = adaptor.getOperands()[0];
417     int64_t idx = index.getValue();
418     rewriter.replaceOp(op, genDimSizeCall(rewriter, op, enc, src, idx));
419     return success();
420   }
421 };
422 
423 /// Sparse conversion rule for trivial tensor casts.
424 class SparseCastConverter : public OpConversionPattern<tensor::CastOp> {
425   using OpConversionPattern::OpConversionPattern;
426   LogicalResult
427   matchAndRewrite(tensor::CastOp op, OpAdaptor adaptor,
428                   ConversionPatternRewriter &rewriter) const override {
429     // Only rewrite identically annotated source/dest.
430     auto encDst = getSparseTensorEncoding(op.getType());
431     auto encSrc = getSparseTensorEncoding(op.source().getType());
432     if (!encDst || encDst != encSrc)
433       return failure();
434     rewriter.replaceOp(op, adaptor.getOperands());
435     return success();
436   }
437 };
438 
439 /// Sparse conversion rule for the new operator.
440 class SparseTensorNewConverter : public OpConversionPattern<NewOp> {
441   using OpConversionPattern::OpConversionPattern;
442   LogicalResult
443   matchAndRewrite(NewOp op, OpAdaptor adaptor,
444                   ConversionPatternRewriter &rewriter) const override {
445     Type resType = op.getType();
446     auto enc = getSparseTensorEncoding(resType);
447     if (!enc)
448       return failure();
449     // Generate the call to construct tensor from ptr. The sizes are
450     // inferred from the result type of the new operator.
451     SmallVector<Value, 4> sizes;
452     SmallVector<Value, 8> params;
453     ShapedType stp = resType.cast<ShapedType>();
454     sizesFromType(rewriter, sizes, op.getLoc(), stp);
455     Value ptr = adaptor.getOperands()[0];
456     newParams(rewriter, params, op, stp, enc, Action::kFromFile, sizes, ptr);
457     rewriter.replaceOp(op, genNewCall(rewriter, op, params));
458     return success();
459   }
460 };
461 
462 /// Sparse conversion rule for the init operator.
463 class SparseTensorInitConverter : public OpConversionPattern<InitOp> {
464   using OpConversionPattern::OpConversionPattern;
465   LogicalResult
466   matchAndRewrite(InitOp op, OpAdaptor adaptor,
467                   ConversionPatternRewriter &rewriter) const override {
468     Type resType = op.getType();
469     auto enc = getSparseTensorEncoding(resType);
470     if (!enc)
471       return failure();
472     // Generate the call to construct empty tensor. The sizes are
473     // explicitly defined by the arguments to the init operator.
474     SmallVector<Value, 8> params;
475     ShapedType stp = resType.cast<ShapedType>();
476     newParams(rewriter, params, op, stp, enc, Action::kEmpty,
477               adaptor.getOperands());
478     rewriter.replaceOp(op, genNewCall(rewriter, op, params));
479     return success();
480   }
481 };
482 
483 /// Sparse conversion rule for the convert operator.
484 class SparseTensorConvertConverter : public OpConversionPattern<ConvertOp> {
485   /// Options to control sparse code generation.
486   SparseTensorConversionOptions options;
487 
488 public:
489   using OpConversionPattern::OpConversionPattern;
490   SparseTensorConvertConverter(MLIRContext *context,
491                                SparseTensorConversionOptions o)
492       : OpConversionPattern<ConvertOp>(context), options(o) {}
493   SparseTensorConvertConverter(TypeConverter &typeConv, MLIRContext *context,
494                                SparseTensorConversionOptions o)
495       : OpConversionPattern<ConvertOp>(typeConv, context), options(o) {}
496 
497   LogicalResult
498   matchAndRewrite(ConvertOp op, OpAdaptor adaptor,
499                   ConversionPatternRewriter &rewriter) const override {
500     Location loc = op->getLoc();
501     Type resType = op.getType();
502     Type srcType = op.source().getType();
503     auto encDst = getSparseTensorEncoding(resType);
504     auto encSrc = getSparseTensorEncoding(srcType);
505     Value src = adaptor.getOperands()[0];
506     if (encDst && encSrc) {
507       // This is a sparse => sparse conversion, which is handled as follows:
508       //   t = src->toCOO();         ; src to COO in dst order
509       //   dst = newSparseTensor(t)
510       // Using the coordinate scheme as an intermediate does not always
511       // yield the fastest conversion but avoids the need for a full
512       // O(N^2) conversion matrix.
513       if (encDst == encSrc) {
514         rewriter.replaceOp(op, adaptor.getOperands()); // hidden nop cast
515         return success();
516       }
517       SmallVector<Value, 4> sizes;
518       SmallVector<Value, 8> params;
519       ShapedType stp = srcType.cast<ShapedType>();
520       sizesFromPtr(rewriter, sizes, op, encSrc, stp, src);
521       bool useDirectConversion;
522       switch (options.sparseToSparseStrategy) {
523       case SparseToSparseConversionStrategy::kViaCOO:
524         useDirectConversion = false;
525         break;
526       case SparseToSparseConversionStrategy::kDirect:
527         useDirectConversion = true;
528         assert(canUseDirectConversion(encDst.getDimLevelType()) &&
529                "Unsupported target for direct sparse-to-sparse conversion");
530         break;
531       case SparseToSparseConversionStrategy::kAuto:
532         useDirectConversion = canUseDirectConversion(encDst.getDimLevelType());
533         break;
534       }
535       if (useDirectConversion) {
536         newParams(rewriter, params, op, stp, encDst, Action::kSparseToSparse,
537                   sizes, src);
538         rewriter.replaceOp(op, genNewCall(rewriter, op, params));
539       } else { // use via-COO conversion.
540         // Set up encoding with right mix of src and dst so that the two
541         // method calls can share most parameters, while still providing
542         // the correct sparsity information to either of them.
543         auto enc = SparseTensorEncodingAttr::get(
544             op->getContext(), encDst.getDimLevelType(), encDst.getDimOrdering(),
545             encSrc.getPointerBitWidth(), encSrc.getIndexBitWidth());
546         newParams(rewriter, params, op, stp, enc, Action::kToCOO, sizes, src);
547         Value coo = genNewCall(rewriter, op, params);
548         params[3] = constantPointerTypeEncoding(rewriter, loc, encDst);
549         params[4] = constantIndexTypeEncoding(rewriter, loc, encDst);
550         params[6] = constantAction(rewriter, loc, Action::kFromCOO);
551         params[7] = coo;
552         Value dst = genNewCall(rewriter, op, params);
553         genDelCOOCall(rewriter, op, stp.getElementType(), coo);
554         rewriter.replaceOp(op, dst);
555       }
556       return success();
557     }
558     if (!encDst && encSrc) {
559       // This is sparse => dense conversion, which is handled as follows:
560       //   dst = new Tensor(0);
561       //   iter = src->toCOO();
562       //   iter->startIterator();
563       //   while (elem = iter->getNext()) {
564       //     dst[elem.indices] = elem.value;
565       //   }
566       RankedTensorType dstTensorTp = resType.cast<RankedTensorType>();
567       RankedTensorType srcTensorTp = srcType.cast<RankedTensorType>();
568       unsigned rank = dstTensorTp.getRank();
569       Type elemTp = dstTensorTp.getElementType();
570       // Fabricate a no-permutation encoding for newParams().
571       // The pointer/index types must be those of `src`.
572       // The dimLevelTypes aren't actually used by Action::kToIterator.
573       encDst = SparseTensorEncodingAttr::get(
574           op->getContext(),
575           SmallVector<SparseTensorEncodingAttr::DimLevelType>(
576               rank, SparseTensorEncodingAttr::DimLevelType::Dense),
577           AffineMap(), encSrc.getPointerBitWidth(), encSrc.getIndexBitWidth());
578       SmallVector<Value, 4> sizes;
579       SmallVector<Value, 8> params;
580       sizesFromPtr(rewriter, sizes, op, encSrc, srcTensorTp, src);
581       newParams(rewriter, params, op, dstTensorTp, encDst, Action::kToIterator,
582                 sizes, src);
583       Value iter = genNewCall(rewriter, op, params);
584       Value ind = genAlloca(rewriter, loc, rank, rewriter.getIndexType());
585       Value elemPtr = genAllocaScalar(rewriter, loc, elemTp);
586       Value dst = allocDenseTensor(rewriter, loc, dstTensorTp, sizes);
587       SmallVector<Value> noArgs;
588       SmallVector<Type> noTypes;
589       auto whileOp = rewriter.create<scf::WhileOp>(loc, noTypes, noArgs);
590       Block *before = rewriter.createBlock(&whileOp.getBefore(), {}, noTypes);
591       rewriter.setInsertionPointToEnd(before);
592       Value cond = genGetNextCall(rewriter, op, iter, ind, elemPtr);
593       rewriter.create<scf::ConditionOp>(loc, cond, before->getArguments());
594       Block *after = rewriter.createBlock(&whileOp.getAfter(), {}, noTypes);
595       rewriter.setInsertionPointToStart(after);
596       insertScalarIntoDenseTensor(rewriter, loc, elemPtr, dst, rank, ind);
597       rewriter.create<scf::YieldOp>(loc);
598       rewriter.setInsertionPointAfter(whileOp);
599       genDelCOOCall(rewriter, op, elemTp, iter);
600       rewriter.replaceOpWithNewOp<bufferization::ToTensorOp>(op, resType, dst);
601       return success();
602     }
603     if (!encDst && !encSrc) {
604       // dense => dense
605       return failure();
606     }
607     // This is a dense => sparse conversion or a sparse constant in COO =>
608     // sparse conversion, which is handled as follows:
609     //   t = newSparseCOO()
610     //   ...code to fill the COO tensor t...
611     //   s = newSparseTensor(t)
612     //
613     // To fill the COO tensor from a dense tensor:
614     //   for i1 in dim1
615     //    ..
616     //     for ik in dimk
617     //       val = a[i1,..,ik]
618     //       if val != 0
619     //         t->add(val, [i1,..,ik], [p1,..,pk])
620     //
621     // To fill the COO tensor from a sparse constant in COO format:
622     //   for i in range(NNZ)
623     //     val = values[i]
624     //     [i1,..,ik] = indices[i]
625     //     t->add(val, [i1,..,ik], [p1,..,pk])
626     //
627     // Note that the dense tensor traversal code is actually implemented
628     // using MLIR IR to avoid having to expose too much low-level
629     // memref traversal details to the runtime support library.
630     // Also note that the code below only generates the "new" ops and
631     // the loop-nest per se; whereas the entire body of the innermost
632     // loop is generated by genAddElt().
633     ShapedType stp = resType.cast<ShapedType>();
634     unsigned rank = stp.getRank();
635     SmallVector<Value, 4> sizes;
636     SmallVector<Value, 8> params;
637     sizesFromSrc(rewriter, sizes, loc, src);
638     newParams(rewriter, params, op, stp, encDst, Action::kEmptyCOO, sizes);
639     Value coo = genNewCall(rewriter, op, params);
640     Value ind = genAlloca(rewriter, loc, rank, rewriter.getIndexType());
641     Value perm = params[2];
642     SmallVector<Value> lo;
643     SmallVector<Value> hi;
644     SmallVector<Value> st;
645     Value zero = constantIndex(rewriter, loc, 0);
646     Value one = constantIndex(rewriter, loc, 1);
647     auto indicesValues = genSplitSparseConstant(rewriter, loc, src);
648     bool isCOOConstant = indicesValues.hasValue();
649     Value indices;
650     Value values;
651     if (isCOOConstant) {
652       indices = indicesValues->first;
653       values = indicesValues->second;
654       lo.push_back(zero);
655       hi.push_back(linalg::createOrFoldDimOp(rewriter, loc, values, 0));
656       st.push_back(one);
657     } else {
658       for (unsigned i = 0; i < rank; i++) {
659         lo.push_back(zero);
660         hi.push_back(linalg::createOrFoldDimOp(rewriter, loc, src, i));
661         st.push_back(one);
662       }
663     }
664     Type eltType = stp.getElementType();
665     scf::buildLoopNest(
666         rewriter, op.getLoc(), lo, hi, st, {},
667         [&](OpBuilder &builder, Location loc, ValueRange ivs,
668             ValueRange args) -> scf::ValueVector {
669           Value val;
670           if (isCOOConstant)
671             val = genIndexAndValueForSparse(rewriter, loc, indices, values, ind,
672                                             ivs, rank);
673           else
674             val = genIndexAndValueForDense(rewriter, loc, src, ind, ivs);
675           genAddEltCall(rewriter, op, eltType, coo, val, ind, perm);
676           return {};
677         });
678     // Final call to construct sparse tensor storage.
679     params[6] = constantAction(rewriter, loc, Action::kFromCOO);
680     params[7] = coo;
681     Value dst = genNewCall(rewriter, op, params);
682     genDelCOOCall(rewriter, op, eltType, coo);
683     rewriter.replaceOp(op, dst);
684     return success();
685   }
686 };
687 
688 /// Sparse conversion rule for the release operator.
689 class SparseTensorReleaseConverter : public OpConversionPattern<ReleaseOp> {
690 public:
691   using OpConversionPattern::OpConversionPattern;
692   LogicalResult
693   matchAndRewrite(ReleaseOp op, OpAdaptor adaptor,
694                   ConversionPatternRewriter &rewriter) const override {
695     StringRef name = "delSparseTensor";
696     TypeRange noTp;
697     createFuncCall(rewriter, op, name, noTp, adaptor.getOperands(),
698                    EmitCInterface::Off);
699     rewriter.eraseOp(op);
700     return success();
701   }
702 };
703 
704 /// Sparse conversion rule for pointer accesses.
705 class SparseTensorToPointersConverter
706     : public OpConversionPattern<ToPointersOp> {
707 public:
708   using OpConversionPattern::OpConversionPattern;
709   LogicalResult
710   matchAndRewrite(ToPointersOp op, OpAdaptor adaptor,
711                   ConversionPatternRewriter &rewriter) const override {
712     Type resType = op.getType();
713     Type ptrType = resType.cast<ShapedType>().getElementType();
714     SmallString<16> name{"sparsePointers", overheadTypeFunctionSuffix(ptrType)};
715     replaceOpWithFuncCall(rewriter, op, name, resType, adaptor.getOperands(),
716                           EmitCInterface::On);
717     return success();
718   }
719 };
720 
721 /// Sparse conversion rule for index accesses.
722 class SparseTensorToIndicesConverter : public OpConversionPattern<ToIndicesOp> {
723 public:
724   using OpConversionPattern::OpConversionPattern;
725   LogicalResult
726   matchAndRewrite(ToIndicesOp op, OpAdaptor adaptor,
727                   ConversionPatternRewriter &rewriter) const override {
728     Type resType = op.getType();
729     Type indType = resType.cast<ShapedType>().getElementType();
730     SmallString<15> name{"sparseIndices", overheadTypeFunctionSuffix(indType)};
731     replaceOpWithFuncCall(rewriter, op, name, resType, adaptor.getOperands(),
732                           EmitCInterface::On);
733     return success();
734   }
735 };
736 
737 /// Sparse conversion rule for value accesses.
738 class SparseTensorToValuesConverter : public OpConversionPattern<ToValuesOp> {
739 public:
740   using OpConversionPattern::OpConversionPattern;
741   LogicalResult
742   matchAndRewrite(ToValuesOp op, OpAdaptor adaptor,
743                   ConversionPatternRewriter &rewriter) const override {
744     Type resType = op.getType();
745     Type eltType = resType.cast<ShapedType>().getElementType();
746     SmallString<15> name{"sparseValues", primaryTypeFunctionSuffix(eltType)};
747     replaceOpWithFuncCall(rewriter, op, name, resType, adaptor.getOperands(),
748                           EmitCInterface::On);
749     return success();
750   }
751 };
752 
753 /// Sparse conversion rule for tensor rematerialization.
754 class SparseTensorLoadConverter : public OpConversionPattern<LoadOp> {
755 public:
756   using OpConversionPattern::OpConversionPattern;
757   LogicalResult
758   matchAndRewrite(LoadOp op, OpAdaptor adaptor,
759                   ConversionPatternRewriter &rewriter) const override {
760     if (op.hasInserts()) {
761       // Finalize any pending insertions.
762       StringRef name = "endInsert";
763       TypeRange noTp;
764       createFuncCall(rewriter, op, name, noTp, adaptor.getOperands(),
765                      EmitCInterface::Off);
766     }
767     rewriter.replaceOp(op, adaptor.getOperands());
768     return success();
769   }
770 };
771 
772 /// Sparse conversion rule for inserting in lexicographic index order.
773 class SparseTensorLexInsertConverter : public OpConversionPattern<LexInsertOp> {
774 public:
775   using OpConversionPattern::OpConversionPattern;
776   LogicalResult
777   matchAndRewrite(LexInsertOp op, OpAdaptor adaptor,
778                   ConversionPatternRewriter &rewriter) const override {
779     Type elemTp = op.tensor().getType().cast<ShapedType>().getElementType();
780     SmallString<12> name{"lexInsert", primaryTypeFunctionSuffix(elemTp)};
781     TypeRange noTp;
782     replaceOpWithFuncCall(rewriter, op, name, noTp, adaptor.getOperands(),
783                           EmitCInterface::On);
784     return success();
785   }
786 };
787 
788 class SparseTensorExpandConverter : public OpConversionPattern<ExpandOp> {
789 public:
790   using OpConversionPattern::OpConversionPattern;
791   LogicalResult
792   matchAndRewrite(ExpandOp op, OpAdaptor adaptor,
793                   ConversionPatternRewriter &rewriter) const override {
794     Location loc = op->getLoc();
795     ShapedType srcType = op.tensor().getType().cast<ShapedType>();
796     Type eltType = srcType.getElementType();
797     Type boolType = rewriter.getIntegerType(1);
798     Type idxType = rewriter.getIndexType();
799     // All initialization should be done on entry of the loop nest.
800     rewriter.setInsertionPointAfter(op.tensor().getDefiningOp());
801     // Determine the size for access expansion.
802     auto enc = getSparseTensorEncoding(srcType);
803     Value src = adaptor.getOperands()[0];
804     Value sz = genDimSizeCall(rewriter, op, enc, src, srcType.getRank() - 1);
805     // Allocate temporary buffers for values, filled-switch, and indices.
806     // We do not use stack buffers for this, since the expanded size may
807     // be rather large (as it envelops a single expanded dense dimension).
808     Value values = genAlloc(rewriter, loc, sz, eltType);
809     Value filled = genAlloc(rewriter, loc, sz, boolType);
810     Value indices = genAlloc(rewriter, loc, sz, idxType);
811     Value zero = constantZero(rewriter, loc, idxType);
812     // Reset the values/filled-switch to all-zero/false. Note that this
813     // introduces an O(N) operation into the computation, but this reset
814     // operation is amortized over the innermost loops for the access
815     // pattern expansion. As noted in the operation doc, we would like
816     // to amortize this setup cost even between kernels.
817     rewriter.create<linalg::FillOp>(
818         loc, ValueRange{constantZero(rewriter, loc, eltType)},
819         ValueRange{values});
820     rewriter.create<linalg::FillOp>(
821         loc, ValueRange{constantZero(rewriter, loc, boolType)},
822         ValueRange{filled});
823     // Replace expansion op with these buffers and initial index.
824     assert(op.getNumResults() == 4);
825     rewriter.replaceOp(op, {values, filled, indices, zero});
826     return success();
827   }
828 };
829 
830 class SparseTensorCompressConverter : public OpConversionPattern<CompressOp> {
831 public:
832   using OpConversionPattern::OpConversionPattern;
833   LogicalResult
834   matchAndRewrite(CompressOp op, OpAdaptor adaptor,
835                   ConversionPatternRewriter &rewriter) const override {
836     Location loc = op->getLoc();
837     // Note that this method call resets the values/filled-switch back to
838     // all-zero/false by only iterating over the set elements, so the
839     // complexity remains proportional to the sparsity of the expanded
840     // access pattern.
841     Type elemTp = op.tensor().getType().cast<ShapedType>().getElementType();
842     SmallString<12> name{"expInsert", primaryTypeFunctionSuffix(elemTp)};
843     TypeRange noTp;
844     replaceOpWithFuncCall(rewriter, op, name, noTp, adaptor.getOperands(),
845                           EmitCInterface::On);
846     // Deallocate the buffers on exit of the loop nest.
847     Operation *parent = op;
848     for (; isa<scf::ForOp>(parent->getParentOp()) ||
849            isa<scf::WhileOp>(parent->getParentOp()) ||
850            isa<scf::ParallelOp>(parent->getParentOp()) ||
851            isa<scf::IfOp>(parent->getParentOp());
852          parent = parent->getParentOp())
853       ;
854     rewriter.setInsertionPointAfter(parent);
855     rewriter.create<memref::DeallocOp>(loc, adaptor.getOperands()[2]);
856     rewriter.create<memref::DeallocOp>(loc, adaptor.getOperands()[3]);
857     rewriter.create<memref::DeallocOp>(loc, adaptor.getOperands()[4]);
858     return success();
859   }
860 };
861 
862 class SparseTensorOutConverter : public OpConversionPattern<OutOp> {
863 public:
864   using OpConversionPattern::OpConversionPattern;
865   LogicalResult
866   matchAndRewrite(OutOp op, OpAdaptor adaptor,
867                   ConversionPatternRewriter &rewriter) const override {
868     Location loc = op->getLoc();
869     ShapedType srcType = op.tensor().getType().cast<ShapedType>();
870     // Convert to default permuted COO.
871     Value src = adaptor.getOperands()[0];
872     auto encSrc = getSparseTensorEncoding(srcType);
873     SmallVector<Value, 4> sizes;
874     SmallVector<Value, 8> params;
875     sizesFromPtr(rewriter, sizes, op, encSrc, srcType, src);
876     auto enc = SparseTensorEncodingAttr::get(
877         op->getContext(), encSrc.getDimLevelType(), AffineMap(),
878         encSrc.getPointerBitWidth(), encSrc.getIndexBitWidth());
879     newParams(rewriter, params, op, srcType, enc, Action::kToCOO, sizes, src);
880     Value coo = genNewCall(rewriter, op, params);
881     // Then output the tensor to external file with indices in the externally
882     // visible lexicographic index order. A sort is required if the source was
883     // not in that order yet (note that the sort can be dropped altogether if
884     // external format does not care about the order at all, but here we assume
885     // it does).
886     bool sort =
887         encSrc.getDimOrdering() && !encSrc.getDimOrdering().isIdentity();
888     params.clear();
889     params.push_back(coo);
890     params.push_back(adaptor.getOperands()[1]);
891     params.push_back(constantI1(rewriter, loc, sort));
892     Type eltType = srcType.getElementType();
893     SmallString<18> name{"outSparseTensor", primaryTypeFunctionSuffix(eltType)};
894     TypeRange noTp;
895     createFuncCall(rewriter, op, name, noTp, params, EmitCInterface::Off);
896     genDelCOOCall(rewriter, op, eltType, coo);
897     rewriter.eraseOp(op);
898     return success();
899   }
900 };
901 
902 } // namespace
903 
904 //===----------------------------------------------------------------------===//
905 // Public method for populating conversion rules.
906 //===----------------------------------------------------------------------===//
907 
908 /// Populates the given patterns list with conversion rules required for
909 /// the sparsification of linear algebra operations.
910 void mlir::populateSparseTensorConversionPatterns(
911     TypeConverter &typeConverter, RewritePatternSet &patterns,
912     const SparseTensorConversionOptions &options) {
913   patterns.add<SparseReturnConverter, SparseTensorToDimSizeConverter,
914                SparseCastConverter, SparseTensorNewConverter,
915                SparseTensorInitConverter, SparseTensorReleaseConverter,
916                SparseTensorToPointersConverter, SparseTensorToIndicesConverter,
917                SparseTensorToValuesConverter, SparseTensorLoadConverter,
918                SparseTensorLexInsertConverter, SparseTensorExpandConverter,
919                SparseTensorCompressConverter, SparseTensorOutConverter>(
920       typeConverter, patterns.getContext());
921   patterns.add<SparseTensorConvertConverter>(typeConverter,
922                                              patterns.getContext(), options);
923 }
924