1 //===- Sparsification.cpp - Implementation of sparsification --------------===//
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 converting sparse tensor types to actual sparse code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodegenUtils.h"
14 
15 #include "mlir/Dialect/Affine/IR/AffineOps.h"
16 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
17 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
18 #include "mlir/Dialect/Bufferization/IR/Bufferization.h"
19 #include "mlir/Dialect/Func/IR/FuncOps.h"
20 #include "mlir/Dialect/Linalg/IR/Linalg.h"
21 #include "mlir/Dialect/Linalg/Utils/Utils.h"
22 #include "mlir/Dialect/MemRef/IR/MemRef.h"
23 #include "mlir/Dialect/SCF/SCF.h"
24 #include "mlir/Dialect/SCF/Transforms.h"
25 #include "mlir/Dialect/SparseTensor/IR/SparseTensor.h"
26 #include "mlir/Dialect/SparseTensor/Transforms/Passes.h"
27 #include "mlir/Dialect/SparseTensor/Utils/Merger.h"
28 #include "mlir/Dialect/Vector/IR/VectorOps.h"
29 #include "mlir/IR/Matchers.h"
30 #include "mlir/IR/TensorEncoding.h"
31 #include "llvm/ADT/SmallBitVector.h"
32 
33 using namespace mlir;
34 using namespace mlir::sparse_tensor;
35 
36 //===----------------------------------------------------------------------===//
37 // Declarations of data structures.
38 //===----------------------------------------------------------------------===//
39 
40 namespace {
41 
42 // Iteration graph sorting.
43 enum SortMask { kSparseOnly = 0x0, kIncludeDense = 0x1, kIncludeUndef = 0x2 };
44 
45 // Reduction kinds.
46 enum Reduction { kNoReduc, kSum, kProduct, kAnd, kOr, kXor };
47 
48 // Code generation.
49 struct CodeGen {
50   CodeGen(SparsificationOptions o, unsigned numTensors, unsigned numLoops,
51           OpOperand *op, unsigned nest)
52       : options(o), loops(numLoops), sizes(numLoops), buffers(numTensors),
53         pointers(numTensors, std::vector<Value>(numLoops)),
54         indices(numTensors, std::vector<Value>(numLoops)),
55         highs(numTensors, std::vector<Value>(numLoops)),
56         pidxs(numTensors, std::vector<Value>(numLoops)),
57         idxs(numTensors, std::vector<Value>(numLoops)), redVal(), sparseOut(op),
58         outerParNest(nest), lexIdx(), expValues(), expFilled(), expAdded(),
59         expCount(), curVecMask() {}
60   /// Sparsification options.
61   SparsificationOptions options;
62   /// Universal dense indices and upper bounds (by index). The loops array
63   /// is updated with the value of the universal dense index in the current
64   /// loop. The sizes array is set once with the inferred dimension sizes.
65   std::vector<Value> loops;
66   std::vector<Value> sizes;
67   /// Buffers for storing dense and sparse numerical values (by tensor).
68   /// This array is set once during bufferization of all tensors.
69   std::vector<Value> buffers;
70   /// Sparse storage schemes (1-D): pointers and indices (by tensor and index).
71   /// This array is set once during bufferization of all sparse tensors.
72   std::vector<std::vector<Value>> pointers;
73   std::vector<std::vector<Value>> indices;
74   /// Sparse iteration information (by tensor and index). These arrays
75   /// are updated to remain current within the current loop.
76   std::vector<std::vector<Value>> highs;
77   std::vector<std::vector<Value>> pidxs;
78   std::vector<std::vector<Value>> idxs;
79   /// Current reduction, updated during code generation. When indices of a
80   /// reduction are exhausted, all inner loops can use a scalarized reduction.
81   unsigned redExp = -1u;
82   Value redVal;
83   Reduction redKind = kNoReduc;
84   // Sparse tensor as output. Implemented either through direct injective
85   // insertion in lexicographic index order (where indices are updated
86   // in the temporary array `lexIdx`) or through access pattern expansion
87   // in the innermost loop nest (`expValues` through `expCount`).
88   OpOperand *sparseOut;
89   unsigned outerParNest;
90   Value lexIdx;
91   Value expValues;
92   Value expFilled;
93   Value expAdded;
94   Value expCount;
95   // Current vector length and mask.
96   unsigned curVecLength = 1;
97   Value curVecMask;
98 };
99 
100 } // namespace
101 
102 //===----------------------------------------------------------------------===//
103 // Sparse compiler analysis methods.
104 //===----------------------------------------------------------------------===//
105 
106 /// Helper method to apply dimension ordering permutation.
107 static unsigned perm(const SparseTensorEncodingAttr &enc, unsigned d) {
108   if (enc) {
109     auto order = enc.getDimOrdering();
110     if (order) {
111       assert(order.isPermutation());
112       return order.getDimPosition(d);
113     }
114   }
115   return d;
116 }
117 
118 /// Helper method to translate dim level type to internal representation.
119 static Dim toDim(const SparseTensorEncodingAttr &enc, unsigned d) {
120   if (enc) {
121     SparseTensorEncodingAttr::DimLevelType tp = enc.getDimLevelType()[d];
122     if (tp == SparseTensorEncodingAttr::DimLevelType::Compressed)
123       return Dim::kSparse;
124     if (tp == SparseTensorEncodingAttr::DimLevelType::Singleton)
125       return Dim::kSingle;
126   }
127   return Dim::kDense;
128 }
129 
130 /// Helper method to inspect affine expressions. Rejects cases where the
131 /// same index is used more than once. Also rejects affine expressions
132 /// that are not a direct index for annotated tensors.
133 // TODO: accept more affine cases for sparse tensors
134 static bool findAffine(Merger &merger, unsigned tensor, AffineExpr a, Dim dim,
135                        bool isDense) {
136   switch (a.getKind()) {
137   case AffineExprKind::DimId: {
138     unsigned idx = a.cast<AffineDimExpr>().getPosition();
139     if (!merger.isDim(tensor, idx, Dim::kUndef))
140       return false; // used more than once
141     merger.setDim(tensor, idx, dim);
142     return true;
143   }
144   case AffineExprKind::Add:
145   case AffineExprKind::Mul: {
146     if (!isDense)
147       return false;
148     auto binOp = a.cast<AffineBinaryOpExpr>();
149     return findAffine(merger, tensor, binOp.getLHS(), dim, isDense) &&
150            findAffine(merger, tensor, binOp.getRHS(), dim, isDense);
151   }
152   case AffineExprKind::Constant:
153     return isDense;
154   default:
155     return false;
156   }
157 }
158 
159 /// Helper method to inspect sparse encodings in the tensor types.
160 /// Fills the per-dimension sparsity information for all tensors.
161 /// Returns true if the sparse annotations and affine subscript
162 /// expressions of all tensors are admissable. Returns false if
163 /// no annotations are found or inadmissable constructs occur.
164 static bool findSparseAnnotations(Merger &merger, linalg::GenericOp op) {
165   bool annotated = false;
166   for (OpOperand *t : op.getInputAndOutputOperands()) {
167     auto map = op.getTiedIndexingMap(t);
168     auto enc = getSparseTensorEncoding(t->get().getType());
169     if (enc)
170       annotated = true;
171     assert(map.getNumResults() == op.getRank(t));
172     for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) {
173       unsigned tensor = t->getOperandNumber();
174       AffineExpr a = map.getResult(perm(enc, d));
175       if (!findAffine(merger, tensor, a, toDim(enc, d), !enc))
176         return false; // inadmissable affine expression
177     }
178   }
179   return annotated;
180 }
181 
182 /// A DFS helper to compute a topological sort. Note that recursion is
183 /// bounded by the number of implicit loops, which is always small.
184 /// Returns false when a cycle is detected.
185 static bool topSortDFS(unsigned i, std::vector<unsigned> &visit,
186                        std::vector<unsigned> &topSort,
187                        std::vector<std::vector<bool>> &adjM) {
188   if (visit[i] != 0)
189     return visit[i] != 1; // 1 denotes cycle!
190   visit[i] = 1;
191   for (unsigned j = 0, e = visit.size(); j < e; j++)
192     if (adjM[i][j])
193       if (!topSortDFS(j, visit, topSort, adjM))
194         return false;
195   visit[i] = 2;
196   topSort.push_back(i);
197   return true;
198 }
199 
200 /// Helper method to add all constraints from the indices in one affine
201 /// expression before all indices in the other affine expression. For
202 /// example i0+i1 < i2+i3+1 yields i0<i2, i0<i3, i1<i2, and i1<i3.
203 static void addAffineOrderings(std::vector<std::vector<bool>> &adjM,
204                                AffineExpr a, AffineExpr b, unsigned fidx) {
205   switch (a.getKind()) {
206   case AffineExprKind::DimId: {
207     unsigned idx = a.cast<AffineDimExpr>().getPosition();
208     if (b)
209       addAffineOrderings(adjM, b, AffineExpr(), idx);
210     else
211       adjM[fidx][idx] = true;
212     break;
213   }
214   case AffineExprKind::Add:
215   case AffineExprKind::Mul: {
216     auto binOp = a.cast<AffineBinaryOpExpr>();
217     addAffineOrderings(adjM, binOp.getLHS(), b, fidx);
218     addAffineOrderings(adjM, binOp.getRHS(), b, fidx);
219     break;
220   }
221   default:
222     break;
223   }
224 }
225 
226 /// Computes a topologically sorted iteration graph for the linalg operation.
227 /// Ensures all tensors are visited in natural index order. This is essential
228 /// for sparse storage formats since these only support access along fixed
229 /// dimensions. Even for dense storage formats, however, the natural index
230 /// order yields innermost unit-stride access with better spatial locality.
231 static bool computeIterationGraph(Merger &merger, linalg::GenericOp op,
232                                   std::vector<unsigned> &topSort,
233                                   unsigned mask) {
234   // Set up an n x n from/to adjacency matrix of the iteration graph
235   // for the implicit loop indices i_0 .. i_n-1.
236   unsigned n = op.getNumLoops();
237   std::vector<std::vector<bool>> adjM(n, std::vector<bool>(n, false));
238 
239   // Iterate over the indexing maps of every tensor in the tensor expression.
240   for (OpOperand *t : op.getInputAndOutputOperands()) {
241     auto map = op.getTiedIndexingMap(t);
242     auto enc = getSparseTensorEncoding(t->get().getType());
243     assert(map.getNumDims() == n);
244     // Skip dense tensor constraints when not requested.
245     if (!(mask & SortMask::kIncludeDense) && !enc)
246       continue;
247     // Each tensor expression and optional dimension ordering (row-major
248     // by default) puts an ordering constraint on the loop indices. For
249     // example, the tensor expresion A_ijk forces the ordering i < j < k
250     // on the loop indices if no explicit dimension ordering is given.
251     for (unsigned d = 1, rank = map.getNumResults(); d < rank; d++) {
252       AffineExpr f = map.getResult(perm(enc, d - 1));
253       AffineExpr t = map.getResult(perm(enc, d));
254       addAffineOrderings(adjM, f, t, 0);
255     }
256     // Push unrelated loops into sparse iteration space, so these
257     // will be skipped more often.
258     if (mask & SortMask::kIncludeUndef) {
259       unsigned tensor = t->getOperandNumber();
260       for (unsigned i = 0; i < n; i++)
261         if (merger.isDim(tensor, i, Dim::kSparse))
262           for (unsigned j = 0; j < n; j++)
263             if (merger.isDim(tensor, j, Dim::kUndef))
264               adjM[i][j] = true;
265     }
266   }
267 
268   // Topologically sort the iteration graph to determine loop order.
269   // Report failure for a cyclic iteration graph.
270   topSort.clear();
271   topSort.reserve(n);
272   std::vector<unsigned> visit(n, 0);
273   for (unsigned i = 0; i < n; i++)
274     if (visit[i] == 0)
275       if (!topSortDFS(i, visit, topSort, adjM))
276         return false; // cycle!
277   std::reverse(std::begin(topSort), std::end(topSort));
278   return true;
279 }
280 
281 /// Returns true if tensor has an in-place annotation.
282 static bool isInPlace(Value val) {
283   if (auto arg = val.dyn_cast<BlockArgument>())
284     if (auto funcOp = dyn_cast<FuncOp>(arg.getOwner()->getParentOp()))
285       if (auto attr = funcOp.getArgAttrOfType<BoolAttr>(
286               arg.getArgNumber(),
287               bufferization::BufferizableOpInterface::kInplaceableAttrName))
288         return attr.getValue();
289   return false;
290 }
291 
292 /// Returns true if tensor materializes uninitialized into the computation.
293 static bool isMaterializing(Value val) {
294   return val.getDefiningOp<linalg::InitTensorOp>() ||
295          val.getDefiningOp<InitOp>();
296 }
297 
298 /// Returns true when the tensor expression is admissable for codegen.
299 /// Since all sparse input tensors are admissable, we just need to check
300 /// whether the out tensor in the tensor expression codegen is admissable.
301 /// Sets `sparseOut` to the tensor and `outerParNest` to the outer injective
302 /// nesting depth when a "truly dynamic" sparse tensor output occurs.
303 static bool isAdmissableTensorExp(Merger &merger, linalg::GenericOp op,
304                                   std::vector<unsigned> &topSort, unsigned exp,
305                                   OpOperand **sparseOut,
306                                   unsigned &outerParNest) {
307   OpOperand *lhs = op.getOutputOperand(0);
308   unsigned tensor = lhs->getOperandNumber();
309   auto enc = getSparseTensorEncoding(lhs->get().getType());
310   // An non-annotated output tensor is assumed dense, and becomes a random
311   // access n-dim memref. Admissable since insertions cannot occur.
312   if (!enc)
313     return true;
314   // An all-dense annotated "sparse" output tensor becomes a linearized random
315   // access 1-dim memref. Also admissable since insertions cannot occur.
316   bool allDense = true;
317   auto iteratorTypes = op.iterator_types().getValue();
318   unsigned numLoops = iteratorTypes.size();
319   for (unsigned i = 0; i < numLoops; i++)
320     if (merger.isDim(tensor, i, Dim::kSparse)) {
321       allDense = false;
322       break;
323     }
324   if (allDense)
325     return true;
326   // A tensor expression with a sparse output tensor that changes its values
327   // but not its nonzero structure, an operation called "simply dynamic" in
328   // [Bik96,Ch9], is also admissable without special codegen, provided
329   // the tensor's underlying sparse storage scheme can be modified in place.
330   if (merger.isSingleCondition(tensor, exp) && isInPlace(lhs->get()))
331     return true;
332   // Accept "truly dynamic" if the output tensor materializes uninitialized
333   // into the computation and insertions occur in lexicographic index order.
334   if (isMaterializing(lhs->get())) {
335     unsigned nest = 0;
336     for (unsigned i = 0; i < numLoops; i++) {
337       if (isReductionIterator(iteratorTypes[topSort[i]]))
338         break; // terminate at first reduction
339       nest++;
340     }
341     // Determine admissable dynamic insertion situations:
342     // (1) fully injective, since there are no reductions,
343     // (2) admissable 1-d expansion in innermost dimension.
344     if (nest >= op.getRank(lhs) - 1) {
345       *sparseOut = lhs;
346       outerParNest = nest;
347       return true;
348     }
349   }
350   return false;
351 }
352 
353 //===----------------------------------------------------------------------===//
354 // Sparse compiler synthesis methods (reductions).
355 //===----------------------------------------------------------------------===//
356 
357 /// Maps reduction kind to vector::CombiningKind.
358 static vector::CombiningKind getCombiningKind(Reduction kind) {
359   switch (kind) {
360   case kNoReduc:
361     break;
362   case kSum:
363     return vector::CombiningKind::ADD;
364   case kProduct:
365     return vector::CombiningKind::MUL;
366   case kAnd:
367     return vector::CombiningKind::AND;
368   case kOr:
369     return vector::CombiningKind::OR;
370   case kXor:
371     return vector::CombiningKind::XOR;
372   }
373   llvm_unreachable("unknown reduction kind");
374 }
375 
376 /// Maps operation to reduction.
377 static Reduction getReduction(Kind kind) {
378   switch (kind) {
379   case Kind::kAddF:
380   case Kind::kAddI:
381   case Kind::kSubF:
382   case Kind::kSubI:
383     return kSum;
384   case Kind::kMulF:
385   case Kind::kMulI:
386     return kProduct;
387   case Kind::kAndI:
388     return kAnd;
389   case Kind::kOrI:
390     return kOr;
391   case Kind::kXorI:
392     return kXor;
393   default:
394     llvm_unreachable("unexpected reduction operator");
395   }
396 }
397 
398 /// Generates an initial value for a vector reduction, following the scheme
399 /// given in Chapter 5 of "The Software Vectorization Handbook", where the
400 /// initial scalar value is correctly embedded in the vector reduction value,
401 /// and a straightforward horizontal reduction will complete the operation.
402 static Value genVectorReducInit(CodeGen &codegen, PatternRewriter &rewriter,
403                                 Location loc, VectorType vtp) {
404   Value r = codegen.redVal;
405   switch (codegen.redKind) {
406   case kNoReduc:
407     break;
408   case kSum:
409   case kXor:
410     // Initialize reduction vector to: | 0 | .. | 0 | r |
411     return rewriter.create<vector::InsertElementOp>(
412         loc, r, constantZero(rewriter, loc, vtp),
413         constantIndex(rewriter, loc, 0));
414   case kProduct:
415     // Initialize reduction vector to: | 1 | .. | 1 | r |
416     return rewriter.create<vector::InsertElementOp>(
417         loc, r, constantOne(rewriter, loc, vtp),
418         constantIndex(rewriter, loc, 0));
419   case kAnd:
420   case kOr:
421     // Initialize reduction vector to: | r | .. | r | r |
422     return rewriter.create<vector::BroadcastOp>(loc, vtp, r);
423   }
424   llvm_unreachable("unknown reduction kind");
425 }
426 
427 /// Generates final value for a vector reduction.
428 static Value genVectorReducEnd(CodeGen &codegen, PatternRewriter &rewriter,
429                                Location loc, VectorType vtp) {
430   vector::CombiningKind kind = getCombiningKind(codegen.redKind);
431   return rewriter.create<vector::ReductionOp>(loc, kind, codegen.redVal);
432 }
433 
434 /// Updates scalarized reduction value.
435 static void updateReduc(Merger &merger, CodeGen &codegen, Value reduc) {
436   assert(codegen.redKind != kNoReduc);
437   codegen.redVal = merger.exp(codegen.redExp).val = reduc;
438 }
439 
440 //===----------------------------------------------------------------------===//
441 // Sparse compiler synthesis methods (statements and expressions).
442 //===----------------------------------------------------------------------===//
443 
444 /// Generates buffer for the output tensor. Note that all sparse kernels
445 /// assume that when all elements are written to (viz. x(i) = y(i) * z(i)),
446 /// the output buffer is already initialized to all zeroes and only nonzeroes
447 /// values are computed and written out. For updates (viz. x(i) += y(i) * z(i)),
448 /// only nonzeroes values are used for the updates and no assumption on the
449 /// original contents of the output buffer is necessary..
450 static Value genOutputBuffer(CodeGen &codegen, PatternRewriter &rewriter,
451                              linalg::GenericOp op, MemRefType denseTp,
452                              ArrayRef<Value> args) {
453   Location loc = op.getLoc();
454   Value tensor = op.getOutputOperand(0)->get();
455   // The output tensor simply could materialize from the buffer that will
456   // be generated for the tensor present in the outs() clause. This has
457   // the major advantage that the sparse kernel only updates the nonzero
458   // positions for the output tensor.
459   if (isInPlace(tensor))
460     return rewriter.create<bufferization::ToMemrefOp>(loc, denseTp, tensor);
461   // By default, a new buffer is allocated which is initialized to the
462   // tensor defined in the outs() clause. This is always correct but
463   // introduces a dense initialization component that may negatively
464   // impact the running complexity of the sparse kernel. If the tensor
465   // materializes into the computation, we need to preserve the zero
466   // initialization assumption of all sparse output buffers.
467   Value alloc = rewriter.create<memref::AllocOp>(loc, denseTp, args);
468   if (isMaterializing(tensor)) {
469     Value zero = constantZero(rewriter, loc, denseTp.getElementType());
470     rewriter.create<linalg::FillOp>(loc, ValueRange{zero}, ValueRange{alloc});
471   } else {
472     Value init =
473         rewriter.create<bufferization::ToMemrefOp>(loc, denseTp, tensor);
474     rewriter.create<memref::CopyOp>(loc, init, alloc);
475   }
476   return alloc;
477 }
478 
479 /// Local bufferization of all dense and sparse data structures.
480 /// This code enables testing the first prototype sparse compiler.
481 // TODO: replace this with a proliferated bufferization strategy
482 static void genBuffers(Merger &merger, CodeGen &codegen,
483                        PatternRewriter &rewriter, linalg::GenericOp op) {
484   Location loc = op.getLoc();
485   assert(op.getNumInputsAndOutputs() == op.getNumInputs() + 1);
486   // For every tensor, find lower and upper bound on dimensions, set the
487   // same bounds on loop indices, and obtain dense or sparse buffer(s).
488   SmallVector<Value, 4> args;
489   for (OpOperand *t : op.getInputAndOutputOperands()) {
490     unsigned tensor = t->getOperandNumber();
491     auto shape = op.getShape(t);
492     auto map = op.getTiedIndexingMap(t);
493     auto enc = getSparseTensorEncoding(t->get().getType());
494     // Scan all dimensions of current tensor.
495     args.clear();
496     for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) {
497       AffineExpr a = map.getResult(perm(enc, d));
498       if (a.getKind() != AffineExprKind::DimId)
499         continue; // compound
500       unsigned idx = a.cast<AffineDimExpr>().getPosition();
501       // Handle sparse storage schemes.
502       if (merger.isDim(tensor, idx, Dim::kSparse)) {
503         auto dynShape = {ShapedType::kDynamicSize};
504         auto ptrTp =
505             MemRefType::get(dynShape, getPointerOverheadType(rewriter, enc));
506         auto indTp =
507             MemRefType::get(dynShape, getIndexOverheadType(rewriter, enc));
508         Value dim = constantIndex(rewriter, loc, d);
509         // Generate sparse primitives to obtains pointer and indices.
510         codegen.pointers[tensor][idx] =
511             rewriter.create<ToPointersOp>(loc, ptrTp, t->get(), dim);
512         codegen.indices[tensor][idx] =
513             rewriter.create<ToIndicesOp>(loc, indTp, t->get(), dim);
514       }
515       // Find upper bound in current dimension.
516       unsigned p = perm(enc, d);
517       Value up = linalg::createOrFoldDimOp(rewriter, loc, t->get(), p);
518       if (ShapedType::isDynamic(shape[p]))
519         args.push_back(up);
520       assert(codegen.highs[tensor][idx] == nullptr);
521       codegen.sizes[idx] = codegen.highs[tensor][idx] = up;
522     }
523     // Perform the required bufferization. Dense inputs materialize
524     // from the input tensors. Dense outputs need special handling.
525     // Sparse inputs use sparse primitives to obtain the values.
526     // We also accept in-place all-dense annotated "sparse" outputs.
527     Type elementType = getElementTypeOrSelf(t->get().getType());
528     if (!enc) {
529       // Non-annotated dense tensors.
530       auto denseTp = MemRefType::get(shape, elementType);
531       if (tensor < op.getNumInputs())
532         codegen.buffers[tensor] =
533             rewriter.create<bufferization::ToMemrefOp>(loc, denseTp, t->get());
534       else
535         codegen.buffers[tensor] =
536             genOutputBuffer(codegen, rewriter, op, denseTp, args);
537     } else if (t == codegen.sparseOut) {
538       // True sparse output needs a lexIdx array.
539       Value rank = constantIndex(rewriter, loc, op.getRank(t));
540       auto dynShape = {ShapedType::kDynamicSize};
541       auto memTp = MemRefType::get(dynShape, rewriter.getIndexType());
542       codegen.lexIdx = rewriter.create<memref::AllocaOp>(loc, memTp, rank);
543     } else {
544       // Annotated sparse tensors.
545       auto dynShape = {ShapedType::kDynamicSize};
546       auto sparseTp = MemRefType::get(dynShape, elementType);
547       codegen.buffers[tensor] =
548           rewriter.create<ToValuesOp>(loc, sparseTp, t->get());
549     }
550   }
551 }
552 
553 /// Constructs vector type.
554 static VectorType vectorType(CodeGen &codegen, Type etp) {
555   unsigned numScalableDims = codegen.options.enableVLAVectorization;
556   return VectorType::get(codegen.curVecLength, etp, numScalableDims);
557 }
558 
559 /// Constructs vector type from pointer.
560 static VectorType vectorType(CodeGen &codegen, Value ptr) {
561   return vectorType(codegen, ptr.getType().cast<MemRefType>().getElementType());
562 }
563 
564 /// Constructs vector iteration mask.
565 static Value genVectorMask(CodeGen &codegen, PatternRewriter &rewriter,
566                            Value iv, Value lo, Value hi, Value step) {
567   Location loc = iv.getLoc();
568   VectorType mtp = vectorType(codegen, rewriter.getI1Type());
569   // Special case if the vector length evenly divides the trip count (for
570   // example, "for i = 0, 128, 16"). A constant all-true mask is generated
571   // so that all subsequent masked memory operations are immediately folded
572   // into unconditional memory operations.
573   IntegerAttr loInt, hiInt, stepInt;
574   if (matchPattern(lo, m_Constant(&loInt)) &&
575       matchPattern(hi, m_Constant(&hiInt)) &&
576       matchPattern(step, m_Constant(&stepInt))) {
577     if (((hiInt.getInt() - loInt.getInt()) % stepInt.getInt()) == 0)
578       return rewriter.create<vector::BroadcastOp>(
579           loc, mtp, constantI1(rewriter, loc, true));
580   }
581   // Otherwise, generate a vector mask that avoids overrunning the upperbound
582   // during vector execution. Here we rely on subsequent loop optimizations to
583   // avoid executing the mask in all iterations, for example, by splitting the
584   // loop into an unconditional vector loop and a scalar cleanup loop.
585   auto minMap = AffineMap::get(
586       /*dimCount=*/2, /*symbolCount=*/1,
587       {rewriter.getAffineSymbolExpr(0),
588        rewriter.getAffineDimExpr(0) - rewriter.getAffineDimExpr(1)},
589       rewriter.getContext());
590   Value end =
591       rewriter.createOrFold<AffineMinOp>(loc, minMap, ValueRange{hi, iv, step});
592   return rewriter.create<vector::CreateMaskOp>(loc, mtp, end);
593 }
594 
595 /// Generates a vectorized load lhs = a[ind[lo:hi]] or lhs = a[lo:hi].
596 static Value genVectorLoad(CodeGen &codegen, PatternRewriter &rewriter,
597                            Value ptr, ArrayRef<Value> args) {
598   Location loc = ptr.getLoc();
599   VectorType vtp = vectorType(codegen, ptr);
600   Value pass = constantZero(rewriter, loc, vtp);
601   if (args.back().getType().isa<VectorType>()) {
602     SmallVector<Value, 4> scalarArgs(args.begin(), args.end());
603     Value indexVec = args.back();
604     scalarArgs.back() = constantIndex(rewriter, loc, 0);
605     return rewriter.create<vector::GatherOp>(
606         loc, vtp, ptr, scalarArgs, indexVec, codegen.curVecMask, pass);
607   }
608   return rewriter.create<vector::MaskedLoadOp>(loc, vtp, ptr, args,
609                                                codegen.curVecMask, pass);
610 }
611 
612 /// Generates a vectorized store a[ind[lo:hi]] = rhs or a[lo:hi] = rhs.
613 static void genVectorStore(CodeGen &codegen, PatternRewriter &rewriter,
614                            Value rhs, Value ptr, ArrayRef<Value> args) {
615   Location loc = ptr.getLoc();
616   if (args.back().getType().isa<VectorType>()) {
617     SmallVector<Value, 4> scalarArgs(args.begin(), args.end());
618     Value indexVec = args.back();
619     scalarArgs.back() = constantIndex(rewriter, loc, 0);
620     rewriter.create<vector::ScatterOp>(loc, ptr, scalarArgs, indexVec,
621                                        codegen.curVecMask, rhs);
622     return;
623   }
624   rewriter.create<vector::MaskedStoreOp>(loc, ptr, args, codegen.curVecMask,
625                                          rhs);
626 }
627 
628 /// Generates a vectorized invariant. Here we rely on subsequent loop
629 /// optimizations to hoist the invariant broadcast out of the vector loop.
630 static Value genVectorInvariantValue(CodeGen &codegen,
631                                      PatternRewriter &rewriter, Value val) {
632   VectorType vtp = vectorType(codegen, val.getType());
633   return rewriter.create<vector::BroadcastOp>(val.getLoc(), vtp, val);
634 }
635 
636 /// Generates an affine expression.
637 //
638 // TODO: generalize for sparse tensor subscripts
639 //
640 static Value genAffine(CodeGen &codegen, PatternRewriter &rewriter,
641                        AffineExpr a, Location loc) {
642   switch (a.getKind()) {
643   case AffineExprKind::DimId: {
644     unsigned idx = a.cast<AffineDimExpr>().getPosition();
645     return codegen.loops[idx]; // universal dense index
646   }
647   case AffineExprKind::Add: {
648     auto binOp = a.cast<AffineBinaryOpExpr>();
649     return rewriter.create<arith::AddIOp>(
650         loc, genAffine(codegen, rewriter, binOp.getLHS(), loc),
651         genAffine(codegen, rewriter, binOp.getRHS(), loc));
652   }
653   case AffineExprKind::Mul: {
654     auto binOp = a.cast<AffineBinaryOpExpr>();
655     return rewriter.create<arith::MulIOp>(
656         loc, genAffine(codegen, rewriter, binOp.getLHS(), loc),
657         genAffine(codegen, rewriter, binOp.getRHS(), loc));
658   }
659   case AffineExprKind::Constant: {
660     int64_t c = a.cast<AffineConstantExpr>().getValue();
661     return constantIndex(rewriter, loc, c);
662   }
663   default:
664     llvm_unreachable("unexpected affine subscript");
665   }
666 }
667 
668 /// Generates index for load/store on sparse tensor.
669 static Value genIndex(CodeGen &codegen, linalg::GenericOp op, OpOperand *t) {
670   auto map = op.getTiedIndexingMap(t);
671   auto enc = getSparseTensorEncoding(t->get().getType());
672   AffineExpr a = map.getResult(perm(enc, map.getNumResults() - 1));
673   assert(a.getKind() == AffineExprKind::DimId);
674   unsigned idx = a.cast<AffineDimExpr>().getPosition();
675   return codegen.loops[idx];
676 }
677 
678 /// Generates subscript for load/store on a dense or sparse tensor.
679 static Value genSubscript(CodeGen &codegen, PatternRewriter &rewriter,
680                           linalg::GenericOp op, OpOperand *t,
681                           SmallVector<Value, 4> &args) {
682   unsigned tensor = t->getOperandNumber();
683   auto map = op.getTiedIndexingMap(t);
684   auto enc = getSparseTensorEncoding(t->get().getType());
685   unsigned rank = map.getNumResults();
686   if (enc) {
687     // Note that currently, all sparse subscripts are simple.
688     // TODO: accept affine too?
689     AffineExpr a = map.getResult(perm(enc, rank - 1));
690     assert(a.getKind() == AffineExprKind::DimId);
691     unsigned idx = a.cast<AffineDimExpr>().getPosition();
692     assert(codegen.pidxs[tensor][idx] != nullptr);
693     args.push_back(codegen.pidxs[tensor][idx]); // position index
694   } else {
695     for (unsigned d = 0; d < rank; d++) {
696       AffineExpr a = map.getResult(perm(enc, d));
697       args.push_back(genAffine(codegen, rewriter, a, op.getLoc()));
698     }
699   }
700   return codegen.buffers[tensor];
701 }
702 
703 /// Generates insertion code to implement dynamic tensor load.
704 static Value genInsertionLoad(CodeGen &codegen, PatternRewriter &rewriter,
705                               linalg::GenericOp op, OpOperand *t) {
706   Location loc = op.getLoc();
707   // Direct lexicographic index order, tensor loads as zero.
708   if (!codegen.expValues) {
709     Type tp = getElementTypeOrSelf(t->get().getType());
710     return constantZero(rewriter, loc, tp);
711   }
712   // Load from expanded access pattern.
713   Value index = genIndex(codegen, op, t);
714   return rewriter.create<memref::LoadOp>(loc, codegen.expValues, index);
715 }
716 
717 /// Generates insertion code to implement dynamic tensor store.
718 static void genInsertionStore(CodeGen &codegen, PatternRewriter &rewriter,
719                               linalg::GenericOp op, OpOperand *t, Value rhs) {
720   Location loc = op.getLoc();
721   // Direct insertion in lexicographic index order.
722   if (!codegen.expValues) {
723     rewriter.create<LexInsertOp>(loc, t->get(), codegen.lexIdx, rhs);
724     return;
725   }
726   // Generates insertion code along expanded access pattern.
727   //   if (!expFilled[i]) then
728   //     expFilled[i] = true
729   //     expAdded[inserts++] = i
730   //   endif
731   //   values[i] = rhs
732   Value index = genIndex(codegen, op, t);
733   Value fval = constantI1(rewriter, loc, false);
734   Value tval = constantI1(rewriter, loc, true);
735   // If statement.
736   Value filled = rewriter.create<memref::LoadOp>(loc, codegen.expFilled, index);
737   Value cond = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq,
738                                               filled, fval);
739   scf::IfOp ifOp = rewriter.create<scf::IfOp>(loc, rewriter.getIndexType(),
740                                               cond, /*else=*/true);
741   // True branch.
742   rewriter.setInsertionPointToStart(&ifOp.getThenRegion().front());
743   rewriter.create<memref::StoreOp>(loc, tval, codegen.expFilled, index);
744   rewriter.create<memref::StoreOp>(loc, index, codegen.expAdded,
745                                    codegen.expCount);
746   Value one = constantIndex(rewriter, loc, 1);
747   Value add = rewriter.create<arith::AddIOp>(loc, codegen.expCount, one);
748   rewriter.create<scf::YieldOp>(loc, add);
749   // False branch.
750   rewriter.setInsertionPointToStart(&ifOp.getElseRegion().front());
751   rewriter.create<scf::YieldOp>(loc, codegen.expCount);
752   rewriter.setInsertionPointAfter(ifOp);
753   // Value assignment.
754   codegen.expCount = ifOp.getResult(0);
755   rewriter.create<memref::StoreOp>(loc, rhs, codegen.expValues, index);
756 }
757 
758 /// Generates a load on a dense or sparse tensor.
759 static Value genTensorLoad(Merger &merger, CodeGen &codegen,
760                            PatternRewriter &rewriter, linalg::GenericOp op,
761                            unsigned exp) {
762   // Test if the load was hoisted to a higher loop nest.
763   Value val = merger.exp(exp).val;
764   if (val) {
765     if (codegen.curVecLength > 1 && !val.getType().isa<VectorType>())
766       return genVectorInvariantValue(codegen, rewriter, val);
767     return val;
768   }
769   // Load during insertion.
770   OpOperand *t = op.getInputAndOutputOperands()[merger.exp(exp).tensor];
771   if (t == codegen.sparseOut)
772     return genInsertionLoad(codegen, rewriter, op, t);
773   // Actual load.
774   SmallVector<Value, 4> args;
775   Value ptr = genSubscript(codegen, rewriter, op, t, args);
776   if (codegen.curVecLength > 1)
777     return genVectorLoad(codegen, rewriter, ptr, args);
778   return rewriter.create<memref::LoadOp>(op.getLoc(), ptr, args);
779 }
780 
781 /// Generates a store on a dense or sparse tensor.
782 static void genTensorStore(Merger &merger, CodeGen &codegen,
783                            PatternRewriter &rewriter, linalg::GenericOp op,
784                            Value rhs) {
785   Location loc = op.getLoc();
786   // Test if this is a scalarized reduction.
787   if (codegen.redVal) {
788     if (codegen.curVecLength > 1)
789       rhs = rewriter.create<arith::SelectOp>(loc, codegen.curVecMask, rhs,
790                                              codegen.redVal);
791     updateReduc(merger, codegen, rhs);
792     return;
793   }
794   // Store during insertion.
795   OpOperand *t = op.getOutputOperand(0);
796   if (t == codegen.sparseOut) {
797     genInsertionStore(codegen, rewriter, op, t, rhs);
798     return;
799   }
800   // Actual store.
801   SmallVector<Value, 4> args;
802   Value ptr = genSubscript(codegen, rewriter, op, t, args);
803   if (codegen.curVecLength > 1)
804     genVectorStore(codegen, rewriter, rhs, ptr, args);
805   else
806     rewriter.create<memref::StoreOp>(loc, rhs, ptr, args);
807 }
808 
809 /// Generates a pointer/index load from the sparse storage scheme. Narrower
810 /// data types need to be zero extended before casting the value into the
811 /// index type used for looping and indexing.
812 static Value genLoad(CodeGen &codegen, PatternRewriter &rewriter, Location loc,
813                      Value ptr, Value s) {
814   // See https://llvm.org/docs/GetElementPtr.html for some background on
815   // the complications described below.
816   if (codegen.curVecLength > 1) {
817     // Since the index vector is used in a subsequent gather/scatter operations,
818     // which effectively defines an unsigned pointer + signed index, we must
819     // zero extend the vector to an index width. For 8-bit and 16-bit values,
820     // an 32-bit index width suffices. For 32-bit values, zero extending the
821     // elements into 64-bit loses some performance since the 32-bit indexed
822     // gather/scatter is more efficient than the 64-bit index variant (if the
823     // negative 32-bit index space is unused, the enableSIMDIndex32 flag can
824     // preserve this performance). For 64-bit values, there is no good way
825     // to state that the indices are unsigned, with creates the potential of
826     // incorrect address calculations in the unlikely case we need such
827     // extremely large offsets.
828     Type etp = ptr.getType().cast<MemRefType>().getElementType();
829     Value vload = genVectorLoad(codegen, rewriter, ptr, {s});
830     if (!etp.isa<IndexType>()) {
831       if (etp.getIntOrFloatBitWidth() < 32)
832         vload = rewriter.create<arith::ExtUIOp>(
833             loc, vectorType(codegen, rewriter.getI32Type()), vload);
834       else if (etp.getIntOrFloatBitWidth() < 64 &&
835                !codegen.options.enableSIMDIndex32)
836         vload = rewriter.create<arith::ExtUIOp>(
837             loc, vectorType(codegen, rewriter.getI64Type()), vload);
838     }
839     return vload;
840   }
841   // For the scalar case, we simply zero extend narrower indices into 64-bit
842   // values before casting to index without a performance penalty. Here too,
843   // however, indices that already are 64-bit, in theory, cannot express the
844   // full range as explained above.
845   Value load = rewriter.create<memref::LoadOp>(loc, ptr, s);
846   if (!load.getType().isa<IndexType>()) {
847     if (load.getType().getIntOrFloatBitWidth() < 64)
848       load = rewriter.create<arith::ExtUIOp>(loc, rewriter.getI64Type(), load);
849     load =
850         rewriter.create<arith::IndexCastOp>(loc, rewriter.getIndexType(), load);
851   }
852   return load;
853 }
854 
855 /// Generates an invariant value.
856 static Value genInvariantValue(Merger &merger, CodeGen &codegen,
857                                PatternRewriter &rewriter, unsigned exp) {
858   Value val = merger.exp(exp).val;
859   if (codegen.curVecLength > 1)
860     return genVectorInvariantValue(codegen, rewriter, val);
861   return val;
862 }
863 
864 /// Generates an address computation "sz * p + i".
865 static Value genAddress(CodeGen &codegen, PatternRewriter &rewriter,
866                         Location loc, Value size, Value p, Value i) {
867   Value mul = rewriter.create<arith::MulIOp>(loc, size, p);
868   if (auto vtp = i.getType().dyn_cast<VectorType>()) {
869     Value inv =
870         rewriter.create<arith::IndexCastOp>(loc, vtp.getElementType(), mul);
871     mul = genVectorInvariantValue(codegen, rewriter, inv);
872   }
873   return rewriter.create<arith::AddIOp>(loc, mul, i);
874 }
875 
876 /// Generates an index value.
877 static Value genIndexValue(Merger &merger, CodeGen &codegen,
878                            PatternRewriter &rewriter, unsigned exp,
879                            unsigned ldx) {
880   unsigned idx = merger.exp(exp).index;
881   Value ival = codegen.loops[idx];
882   Type itype = ival.getType();
883   // During vectorization, we either encounter:
884   // (1) indices already in vector form, as in ... = ind[lo:hi], good to go, or
885   // (2) single index, as in ... = i, must convert to [i, i+1, ...] for inner i.
886   unsigned vl = codegen.curVecLength;
887   if (vl > 1 && !itype.isa<VectorType>()) {
888     Location loc = ival.getLoc();
889     VectorType vtp = vectorType(codegen, itype);
890     ival = rewriter.create<vector::BroadcastOp>(loc, vtp, ival);
891     if (idx == ldx) {
892       SmallVector<APInt, 4> integers;
893       for (unsigned i = 0; i < vl; i++)
894         integers.push_back(APInt(/*width=*/64, i));
895       auto values = DenseElementsAttr::get(vtp, integers);
896       Value incr = rewriter.create<arith::ConstantOp>(loc, vtp, values);
897       ival = rewriter.create<arith::AddIOp>(loc, ival, incr);
898     }
899   }
900   return ival;
901 }
902 
903 /// Recursively generates tensor expression.
904 static Value genExp(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
905                     linalg::GenericOp op, unsigned exp, unsigned ldx) {
906   Location loc = op.getLoc();
907   if (exp == -1u)
908     return Value();
909   if (merger.exp(exp).kind == Kind::kTensor)
910     return genTensorLoad(merger, codegen, rewriter, op, exp);
911   if (merger.exp(exp).kind == Kind::kInvariant)
912     return genInvariantValue(merger, codegen, rewriter, exp);
913   if (merger.exp(exp).kind == Kind::kIndex)
914     return genIndexValue(merger, codegen, rewriter, exp, ldx);
915   Value v0 =
916       genExp(merger, codegen, rewriter, op, merger.exp(exp).children.e0, ldx);
917   Value v1 =
918       genExp(merger, codegen, rewriter, op, merger.exp(exp).children.e1, ldx);
919   return merger.buildExp(rewriter, loc, exp, v0, v1);
920 }
921 
922 /// Determines if affine expression is invariant.
923 static bool isInvariantAffine(const CodeGen &codegen, AffineExpr a,
924                               unsigned ldx, bool &atLevel) {
925   switch (a.getKind()) {
926   case AffineExprKind::DimId: {
927     unsigned idx = a.cast<AffineDimExpr>().getPosition();
928     if (idx == ldx)
929       atLevel = true;
930     return codegen.loops[idx] != nullptr; // no longer in play?
931   }
932   case AffineExprKind::Add:
933   case AffineExprKind::Mul: {
934     auto binOp = a.cast<AffineBinaryOpExpr>();
935     return isInvariantAffine(codegen, binOp.getLHS(), ldx, atLevel) &&
936            isInvariantAffine(codegen, binOp.getRHS(), ldx, atLevel);
937   }
938   default:
939     return true;
940   }
941 }
942 
943 /// Hoists loop invariant tensor loads for which indices have been exhausted.
944 static void genInvariants(Merger &merger, CodeGen &codegen,
945                           PatternRewriter &rewriter, linalg::GenericOp op,
946                           unsigned exp, unsigned ldx, bool atStart,
947                           Kind last = Kind::kTensor) {
948   if (exp == -1u)
949     return;
950   if (merger.exp(exp).kind == Kind::kTensor) {
951     // Inspect tensor indices.
952     bool atLevel = ldx == -1u;
953     OpOperand *t = op.getInputAndOutputOperands()[merger.exp(exp).tensor];
954     auto map = op.getTiedIndexingMap(t);
955     auto enc = getSparseTensorEncoding(t->get().getType());
956     for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) {
957       AffineExpr a = map.getResult(perm(enc, d));
958       if (!isInvariantAffine(codegen, a, ldx, atLevel))
959         return; // still in play
960     }
961     // All exhausted at this level (atLevel denotes exactly at this level).
962     if (!atLevel)
963       return;
964     OpOperand *lhs = op.getOutputOperand(0);
965     if (lhs == t) {
966       // Start or end a scalarized reduction
967       if (atStart) {
968         Value load = genTensorLoad(merger, codegen, rewriter, op, exp);
969         codegen.redKind = getReduction(last);
970         codegen.redExp = exp;
971         updateReduc(merger, codegen, load);
972       } else {
973         Value redVal = codegen.redVal;
974         updateReduc(merger, codegen, Value());
975         codegen.redExp = -1u;
976         codegen.redKind = kNoReduc;
977         genTensorStore(merger, codegen, rewriter, op, redVal);
978       }
979     } else {
980       // Start or end loop invariant hoisting of a tensor load.
981       merger.exp(exp).val =
982           atStart ? genTensorLoad(merger, codegen, rewriter, op, exp) : Value();
983     }
984   } else if (merger.exp(exp).kind != Kind::kInvariant &&
985              merger.exp(exp).kind != Kind::kIndex) {
986     // Traverse into the binary operations. Note that we only hoist
987     // tensor loads, since subsequent MLIR/LLVM passes know how to
988     // deal with all other kinds of derived loop invariants.
989     Kind last = merger.exp(exp).kind;
990     unsigned e0 = merger.exp(exp).children.e0;
991     unsigned e1 = merger.exp(exp).children.e1;
992     genInvariants(merger, codegen, rewriter, op, e0, ldx, atStart, last);
993     genInvariants(merger, codegen, rewriter, op, e1, ldx, atStart, last);
994   }
995 }
996 
997 /// Generates an expanded access pattern in innermost dimension.
998 static void genExpansion(Merger &merger, CodeGen &codegen,
999                          PatternRewriter &rewriter, linalg::GenericOp op,
1000                          unsigned at, bool atStart) {
1001   OpOperand *lhs = codegen.sparseOut;
1002   if (!lhs || codegen.outerParNest != op.getRank(lhs) - 1 ||
1003       at != codegen.outerParNest)
1004     return; // not needed at this level
1005   // Generate start or end of an expanded access pattern.
1006   Value tensor = lhs->get();
1007   Location loc = op.getLoc();
1008   if (atStart) {
1009     auto dynShape = {ShapedType::kDynamicSize};
1010     Type etp = tensor.getType().cast<ShapedType>().getElementType();
1011     Type t1 = MemRefType::get(dynShape, etp);
1012     Type t2 = MemRefType::get(dynShape, rewriter.getI1Type());
1013     Type t3 = MemRefType::get(dynShape, rewriter.getIndexType());
1014     Type t4 = rewriter.getIndexType();
1015     auto res =
1016         rewriter.create<ExpandOp>(loc, TypeRange({t1, t2, t3, t4}), tensor);
1017     assert(res.getNumResults() == 4);
1018     assert(!codegen.expValues);
1019     codegen.expValues = res.getResult(0);
1020     codegen.expFilled = res.getResult(1);
1021     codegen.expAdded = res.getResult(2);
1022     codegen.expCount = res.getResult(3);
1023   } else {
1024     assert(codegen.expValues);
1025     rewriter.create<CompressOp>(loc, tensor, codegen.lexIdx, codegen.expValues,
1026                                 codegen.expFilled, codegen.expAdded,
1027                                 codegen.expCount);
1028     codegen.expValues = codegen.expFilled = codegen.expAdded =
1029         codegen.expCount = Value();
1030   }
1031 }
1032 
1033 /// Generates initialization code for the subsequent loop sequence at
1034 /// current index level. Returns true if the loop sequence needs to
1035 /// maintain the universal index.
1036 static bool genInit(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
1037                     linalg::GenericOp op, std::vector<unsigned> &topSort,
1038                     unsigned at, BitVector &inits) {
1039   bool needsUniv = false;
1040   Location loc = op.getLoc();
1041   unsigned idx = topSort[at];
1042 
1043   // Initialize sparse positions.
1044   for (unsigned b = 0, be = inits.size(); b < be; b++) {
1045     if (inits[b]) {
1046       unsigned tensor = merger.tensor(b);
1047       assert(idx == merger.index(b));
1048       if (merger.isDim(b, Dim::kSparse)) {
1049         // Initialize sparse index.
1050         unsigned pat = at;
1051         for (; pat != 0; pat--) {
1052           if (codegen.pidxs[tensor][topSort[pat - 1]])
1053             break;
1054         }
1055         Value ptr = codegen.pointers[tensor][idx];
1056         Value one = constantIndex(rewriter, loc, 1);
1057         Value p0 = (pat == 0) ? constantIndex(rewriter, loc, 0)
1058                               : codegen.pidxs[tensor][topSort[pat - 1]];
1059         codegen.pidxs[tensor][idx] = genLoad(codegen, rewriter, loc, ptr, p0);
1060         Value p1 = rewriter.create<arith::AddIOp>(loc, p0, one);
1061         codegen.highs[tensor][idx] = genLoad(codegen, rewriter, loc, ptr, p1);
1062       } else {
1063         // Dense index still in play.
1064         needsUniv = true;
1065       }
1066     }
1067   }
1068 
1069   // Initialize the universal dense index.
1070   codegen.loops[idx] = constantIndex(rewriter, loc, 0);
1071   return needsUniv;
1072 }
1073 
1074 /// Returns vectorization strategy. Any implicit inner loop in the Linalg
1075 /// operation is a candidate. Whether it is actually converted to SIMD code
1076 /// depends on the requested strategy.
1077 static bool isVectorFor(CodeGen &codegen, bool isInner, bool isReduction,
1078                         bool isSparse) {
1079   // Reject vectorization of sparse output, unless innermost is reduction.
1080   if (codegen.sparseOut && !isReduction)
1081     return false;
1082   // Inspect strategy.
1083   switch (codegen.options.vectorizationStrategy) {
1084   case SparseVectorizationStrategy::kNone:
1085     return false;
1086   case SparseVectorizationStrategy::kDenseInnerLoop:
1087     return isInner && !isSparse;
1088   case SparseVectorizationStrategy::kAnyStorageInnerLoop:
1089     return isInner;
1090   }
1091   llvm_unreachable("unexpected vectorization strategy");
1092 }
1093 
1094 /// Returns parallelization strategy. Any implicit loop in the Linalg operation
1095 /// that is marked "parallel" is a candidate. Whether it is actually converted
1096 /// to a parallel operation depends on the requested strategy.
1097 static bool isParallelFor(CodeGen &codegen, bool isOuter, bool isReduction,
1098                           bool isSparse, bool isVector) {
1099   // Reject parallelization of sparse output.
1100   if (codegen.sparseOut)
1101     return false;
1102   // Inspect strategy.
1103   switch (codegen.options.parallelizationStrategy) {
1104   case SparseParallelizationStrategy::kNone:
1105     return false;
1106   case SparseParallelizationStrategy::kDenseOuterLoop:
1107     return isOuter && !isSparse && !isReduction && !isVector;
1108   case SparseParallelizationStrategy::kAnyStorageOuterLoop:
1109     return isOuter && !isReduction && !isVector;
1110   case SparseParallelizationStrategy::kDenseAnyLoop:
1111     return !isSparse && !isReduction && !isVector;
1112   case SparseParallelizationStrategy::kAnyStorageAnyLoop:
1113     return !isReduction && !isVector;
1114   }
1115   llvm_unreachable("unexpected parallelization strategy");
1116 }
1117 
1118 /// Checks unit stride for dense tensors. The iteration graph may have ignored
1119 /// dense access patterns in order to avoid cycles (sparse access patterns are
1120 /// always placed innermost), but that means dense access has become strided.
1121 /// This prevents effective vectorization.
1122 static bool denseUnitStrides(Merger &merger, linalg::GenericOp op,
1123                              unsigned idx) {
1124   for (OpOperand *t : op.getInputAndOutputOperands()) {
1125     if (!getSparseTensorEncoding(t->get().getType())) {
1126       auto map = op.getTiedIndexingMap(t);
1127       for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) {
1128         AffineExpr a = map.getResult(d);
1129         // Report non-unit stride if innermost index appears at an outer
1130         // dimension (true non-unit stride) or if the innermost index appears
1131         // in a compound subscript in the innermost dimension. Even if the
1132         // latter is unit stride, it does not play well with scatter/gather.
1133         // TODO: accept unit stride affine innermost like a[i,j+k+1]?
1134         if (a.isFunctionOfDim(idx) &&
1135             ((d != rank - 1) || (a.getKind() != AffineExprKind::DimId)))
1136           return false;
1137       }
1138     }
1139   }
1140   return true;
1141 }
1142 
1143 /// Generates a for-loop on a single index.
1144 static Operation *genFor(Merger &merger, CodeGen &codegen,
1145                          PatternRewriter &rewriter, linalg::GenericOp op,
1146                          bool isOuter, bool isInner, unsigned idx,
1147                          BitVector &indices) {
1148   unsigned fb = indices.find_first();
1149   unsigned tensor = merger.tensor(fb);
1150   assert(idx == merger.index(fb));
1151   auto iteratorTypes = op.iterator_types().getValue();
1152   bool isReduction = isReductionIterator(iteratorTypes[idx]);
1153   bool isSparse = merger.isDim(fb, Dim::kSparse);
1154   bool isVector = isVectorFor(codegen, isInner, isReduction, isSparse) &&
1155                   denseUnitStrides(merger, op, idx);
1156   bool isParallel =
1157       isParallelFor(codegen, isOuter, isReduction, isSparse, isVector);
1158 
1159   // Prepare vector length.
1160   if (isVector)
1161     codegen.curVecLength = codegen.options.vectorLength;
1162 
1163   // Loop bounds and increment.
1164   Location loc = op.getLoc();
1165   Value lo = isSparse ? codegen.pidxs[tensor][idx] : codegen.loops[idx];
1166   Value hi = isSparse ? codegen.highs[tensor][idx] : codegen.sizes[idx];
1167   Value step = constantIndex(rewriter, loc, codegen.curVecLength);
1168   if (isVector && codegen.options.enableVLAVectorization) {
1169     Value vscale = rewriter.create<vector::VectorScaleOp>(
1170         loc, IndexType::get(rewriter.getContext()));
1171     step = rewriter.create<arith::MulIOp>(loc, vscale, step);
1172   }
1173 
1174   // Emit a parallel loop.
1175   if (isParallel) {
1176     assert(!isVector);
1177     scf::ParallelOp parOp = rewriter.create<scf::ParallelOp>(loc, lo, hi, step);
1178     if (isSparse)
1179       codegen.pidxs[tensor][idx] = parOp.getInductionVars()[0];
1180     else
1181       codegen.loops[idx] = parOp.getInductionVars()[0];
1182     rewriter.setInsertionPointToStart(parOp.getBody());
1183     return parOp;
1184   }
1185 
1186   // Emit a sequential or vector loop.
1187   SmallVector<Value, 4> operands;
1188   if (codegen.redVal) {
1189     // In a vector loop, bring reduction into SIMD form, if not already.
1190     if (isVector && !codegen.redVal.getType().isa<VectorType>()) {
1191       VectorType vtp = vectorType(codegen, codegen.redVal.getType());
1192       Value vred = genVectorReducInit(codegen, rewriter, loc, vtp);
1193       updateReduc(merger, codegen, vred);
1194     }
1195     operands.push_back(codegen.redVal);
1196   }
1197   if (codegen.expValues)
1198     operands.push_back(codegen.expCount);
1199   scf::ForOp forOp = rewriter.create<scf::ForOp>(loc, lo, hi, step, operands);
1200   if (codegen.redVal)
1201     updateReduc(merger, codegen, forOp.getRegionIterArgs().front());
1202   if (codegen.expValues)
1203     codegen.expCount = forOp.getRegionIterArgs().back();
1204   // Assign induction variable to sparse or dense index.
1205   Value iv = forOp.getInductionVar();
1206   if (isSparse)
1207     codegen.pidxs[tensor][idx] = iv;
1208   else
1209     codegen.loops[idx] = iv;
1210   rewriter.setInsertionPointToStart(forOp.getBody());
1211   // Share vector iteration mask between all subsequent loads/stores.
1212   if (isVector)
1213     codegen.curVecMask = genVectorMask(codegen, rewriter, iv, lo, hi, step);
1214   return forOp;
1215 }
1216 
1217 /// Emit a while-loop for co-iteration over multiple indices.
1218 static Operation *genWhile(Merger &merger, CodeGen &codegen,
1219                            PatternRewriter &rewriter, linalg::GenericOp op,
1220                            unsigned idx, bool needsUniv,
1221                            BitVector &indices) {
1222   SmallVector<Type, 4> types;
1223   SmallVector<Value, 4> operands;
1224   // Construct the while-loop with a parameter for each index.
1225   Type indexType = rewriter.getIndexType();
1226   for (unsigned b = 0, be = indices.size(); b < be; b++) {
1227     if (indices[b] && merger.isDim(b, Dim::kSparse)) {
1228       unsigned tensor = merger.tensor(b);
1229       assert(idx == merger.index(b));
1230       types.push_back(indexType);
1231       operands.push_back(codegen.pidxs[tensor][idx]);
1232     }
1233   }
1234   if (codegen.redVal) {
1235     types.push_back(codegen.redVal.getType());
1236     operands.push_back(codegen.redVal);
1237   }
1238   if (codegen.expValues) {
1239     types.push_back(indexType);
1240     operands.push_back(codegen.expCount);
1241   }
1242   if (needsUniv) {
1243     types.push_back(indexType);
1244     operands.push_back(codegen.loops[idx]);
1245   }
1246   assert(types.size() == operands.size());
1247   Location loc = op.getLoc();
1248   scf::WhileOp whileOp = rewriter.create<scf::WhileOp>(loc, types, operands);
1249 
1250   SmallVector<Location> locs(types.size(), loc);
1251   Block *before = rewriter.createBlock(&whileOp.getBefore(), {}, types, locs);
1252   Block *after = rewriter.createBlock(&whileOp.getAfter(), {}, types, locs);
1253 
1254   // Build the "before" region, which effectively consists
1255   // of a conjunction of "i < upper" tests on all induction.
1256   rewriter.setInsertionPointToStart(&whileOp.getBefore().front());
1257   Value cond;
1258   unsigned o = 0;
1259   for (unsigned b = 0, be = indices.size(); b < be; b++) {
1260     if (indices[b] && merger.isDim(b, Dim::kSparse)) {
1261       unsigned tensor = merger.tensor(b);
1262       assert(idx == merger.index(b));
1263       Value op1 = before->getArgument(o);
1264       Value op2 = codegen.highs[tensor][idx];
1265       Value opc = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult,
1266                                                  op1, op2);
1267       cond = cond ? rewriter.create<arith::AndIOp>(loc, cond, opc) : opc;
1268       codegen.pidxs[tensor][idx] = after->getArgument(o++);
1269     }
1270   }
1271   if (codegen.redVal)
1272     updateReduc(merger, codegen, after->getArgument(o++));
1273   if (codegen.expValues)
1274     codegen.expCount = after->getArgument(o++);
1275   if (needsUniv)
1276     codegen.loops[idx] = after->getArgument(o++);
1277   assert(o == operands.size());
1278   rewriter.create<scf::ConditionOp>(loc, cond, before->getArguments());
1279   rewriter.setInsertionPointToStart(&whileOp.getAfter().front());
1280   return whileOp;
1281 }
1282 
1283 /// Generates a for-loop or a while-loop, depending on whether it implements
1284 /// singleton iteration or co-iteration over the given conjunction.
1285 static Operation *genLoop(Merger &merger, CodeGen &codegen,
1286                           PatternRewriter &rewriter, linalg::GenericOp op,
1287                           std::vector<unsigned> &topSort, unsigned at,
1288                           bool needsUniv, BitVector &indices) {
1289   unsigned idx = topSort[at];
1290   if (indices.count() == 1) {
1291     bool isOuter = at == 0;
1292     bool isInner = at == topSort.size() - 1;
1293     return genFor(merger, codegen, rewriter, op, isOuter, isInner, idx,
1294                   indices);
1295   }
1296   return genWhile(merger, codegen, rewriter, op, idx, needsUniv, indices);
1297 }
1298 
1299 /// Generates the local variables for this loop, consisting of the sparse
1300 /// indices, restored universal dense index, and dense positions.
1301 static void genLocals(Merger &merger, CodeGen &codegen,
1302                       PatternRewriter &rewriter, linalg::GenericOp op,
1303                       std::vector<unsigned> &topSort, unsigned at,
1304                       bool needsUniv, BitVector &locals) {
1305   Location loc = op.getLoc();
1306   unsigned idx = topSort[at];
1307 
1308   // Initialize sparse indices.
1309   Value min;
1310   for (unsigned b = 0, be = locals.size(); b < be; b++) {
1311     if (locals[b] && merger.isDim(b, Dim::kSparse)) {
1312       unsigned tensor = merger.tensor(b);
1313       assert(idx == merger.index(b));
1314       Value ptr = codegen.indices[tensor][idx];
1315       Value s = codegen.pidxs[tensor][idx];
1316       Value load = genLoad(codegen, rewriter, loc, ptr, s);
1317       codegen.idxs[tensor][idx] = load;
1318       if (!needsUniv) {
1319         if (min) {
1320           Value cmp = rewriter.create<arith::CmpIOp>(
1321               loc, arith::CmpIPredicate::ult, load, min);
1322           min = rewriter.create<arith::SelectOp>(loc, cmp, load, min);
1323         } else {
1324           min = load;
1325         }
1326       }
1327     }
1328   }
1329 
1330   // Merge dense universal index over minimum.
1331   if (min) {
1332     assert(!needsUniv);
1333     codegen.loops[idx] = min;
1334   }
1335 
1336   // Initialize dense positions. Note that we generate dense indices of the
1337   // output tensor unconditionally, since they may not appear in the lattice,
1338   // but may be needed for linearized codegen.
1339   for (unsigned b = 0, be = locals.size(); b < be; b++) {
1340     if ((locals[b] || merger.isOutTensor(b, idx)) &&
1341         merger.isDim(b, Dim::kDense)) {
1342       unsigned tensor = merger.tensor(b);
1343       assert(idx == merger.index(b));
1344       unsigned pat = at;
1345       for (; pat != 0; pat--)
1346         if (codegen.pidxs[tensor][topSort[pat - 1]])
1347           break;
1348       Value p = (pat == 0) ? constantIndex(rewriter, loc, 0)
1349                            : codegen.pidxs[tensor][topSort[pat - 1]];
1350       codegen.pidxs[tensor][idx] = genAddress(
1351           codegen, rewriter, loc, codegen.sizes[idx], p, codegen.loops[idx]);
1352     }
1353   }
1354 
1355   // Move the insertion indices in lexicographic index order. During access
1356   // pattern expansion, we can skip setting the innermost dimension.
1357   if (codegen.sparseOut && !codegen.expValues) {
1358     Value pos = constantIndex(rewriter, loc, at);
1359     rewriter.create<memref::StoreOp>(loc, codegen.loops[idx], codegen.lexIdx,
1360                                      pos);
1361   }
1362 }
1363 
1364 /// Generates the induction structure for a while-loop.
1365 static void genWhileInduction(Merger &merger, CodeGen &codegen,
1366                               PatternRewriter &rewriter, linalg::GenericOp op,
1367                               unsigned idx, bool needsUniv,
1368                               BitVector &induction,
1369                               scf::WhileOp whileOp) {
1370   Location loc = op.getLoc();
1371   // Finalize each else branch of all if statements.
1372   if (codegen.redVal || codegen.expValues) {
1373     while (auto ifOp = dyn_cast_or_null<scf::IfOp>(
1374                rewriter.getInsertionBlock()->getParentOp())) {
1375       unsigned y = 0;
1376       SmallVector<Value, 4> yields;
1377       if (codegen.redVal) {
1378         yields.push_back(codegen.redVal);
1379         updateReduc(merger, codegen, ifOp.getResult(y++));
1380       }
1381       if (codegen.expValues) {
1382         yields.push_back(codegen.expCount);
1383         codegen.expCount = ifOp->getResult(y++);
1384       }
1385       assert(y == yields.size());
1386       rewriter.create<scf::YieldOp>(loc, yields);
1387       rewriter.setInsertionPointAfter(ifOp);
1388     }
1389   }
1390   rewriter.setInsertionPointToEnd(&whileOp.getAfter().front());
1391   // Finalize the induction. Note that the induction could be performed
1392   // in the individual if-branches to avoid re-evaluating the conditions.
1393   // However, that would result in a rather elaborate forest of yield
1394   // instructions during code generation. Moreover, performing the induction
1395   // after the if-statements more closely resembles code generated by TACO.
1396   unsigned o = 0;
1397   SmallVector<Value, 4> operands;
1398   Value one = constantIndex(rewriter, loc, 1);
1399   for (unsigned b = 0, be = induction.size(); b < be; b++) {
1400     if (induction[b] && merger.isDim(b, Dim::kSparse)) {
1401       unsigned tensor = merger.tensor(b);
1402       assert(idx == merger.index(b));
1403       Value op1 = codegen.idxs[tensor][idx];
1404       Value op2 = codegen.loops[idx];
1405       Value op3 = codegen.pidxs[tensor][idx];
1406       Value cmp = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq,
1407                                                  op1, op2);
1408       Value add = rewriter.create<arith::AddIOp>(loc, op3, one);
1409       operands.push_back(rewriter.create<arith::SelectOp>(loc, cmp, add, op3));
1410       codegen.pidxs[tensor][idx] = whileOp->getResult(o++);
1411     }
1412   }
1413   if (codegen.redVal) {
1414     operands.push_back(codegen.redVal);
1415     updateReduc(merger, codegen, whileOp->getResult(o++));
1416   }
1417   if (codegen.expValues) {
1418     operands.push_back(codegen.expCount);
1419     codegen.expCount = whileOp->getResult(o++);
1420   }
1421   if (needsUniv) {
1422     operands.push_back(
1423         rewriter.create<arith::AddIOp>(loc, codegen.loops[idx], one));
1424     codegen.loops[idx] = whileOp->getResult(o++);
1425   }
1426   assert(o == operands.size());
1427   rewriter.create<scf::YieldOp>(loc, operands);
1428   rewriter.setInsertionPointAfter(whileOp);
1429 }
1430 
1431 /// Generates the induction structure for a for-loop.
1432 static void genForInduction(Merger &merger, CodeGen &codegen,
1433                             PatternRewriter &rewriter, linalg::GenericOp op,
1434                             Operation *loop) {
1435   Location loc = op.getLoc();
1436   unsigned o = 0;
1437   SmallVector<Value, 4> operands;
1438   if (codegen.redVal) {
1439     operands.push_back(codegen.redVal);
1440     updateReduc(merger, codegen, loop->getResult(o++));
1441   }
1442   if (codegen.expValues) {
1443     operands.push_back(codegen.expCount);
1444     codegen.expCount = loop->getResult(o++);
1445   }
1446   assert(o == operands.size());
1447   if (o > 0)
1448     rewriter.create<scf::YieldOp>(loc, operands);
1449   rewriter.setInsertionPointAfter(loop);
1450 }
1451 
1452 /// Generates a single if-statement within a while-loop.
1453 static scf::IfOp genIf(Merger &merger, CodeGen &codegen,
1454                        PatternRewriter &rewriter, linalg::GenericOp op,
1455                        unsigned idx, BitVector &conditions) {
1456   Location loc = op.getLoc();
1457   SmallVector<Type, 4> types;
1458   Value cond;
1459   for (unsigned b = 0, be = conditions.size(); b < be; b++) {
1460     if (conditions[b]) {
1461       unsigned tensor = merger.tensor(b);
1462       assert(idx == merger.index(b));
1463       Value clause;
1464       if (merger.isDim(b, Dim::kSparse)) {
1465         Value op1 = codegen.idxs[tensor][idx];
1466         Value op2 = codegen.loops[idx];
1467         clause = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq,
1468                                                 op1, op2);
1469       } else {
1470         clause = constantI1(rewriter, loc, true);
1471       }
1472       cond = cond ? rewriter.create<arith::AndIOp>(loc, cond, clause) : clause;
1473     }
1474   }
1475   if (codegen.redVal)
1476     types.push_back(codegen.redVal.getType());
1477   if (codegen.expValues)
1478     types.push_back(rewriter.getIndexType());
1479   scf::IfOp ifOp = rewriter.create<scf::IfOp>(loc, types, cond, /*else=*/true);
1480   rewriter.setInsertionPointToStart(&ifOp.getThenRegion().front());
1481   return ifOp;
1482 }
1483 
1484 /// Generates end of true branch of if-statement within a while-loop.
1485 static void endIf(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
1486                   linalg::GenericOp op, scf::IfOp ifOp, Operation *loop,
1487                   Value redInput, Value cntInput) {
1488   SmallVector<Value, 4> operands;
1489   if (codegen.redVal) {
1490     operands.push_back(codegen.redVal);
1491     updateReduc(merger, codegen, redInput);
1492   }
1493   if (codegen.expValues) {
1494     operands.push_back(codegen.expCount);
1495     codegen.expCount = cntInput;
1496   }
1497   if (!operands.empty())
1498     rewriter.create<scf::YieldOp>(op.getLoc(), operands);
1499   rewriter.setInsertionPointToStart(&ifOp.getElseRegion().front());
1500 }
1501 
1502 //===----------------------------------------------------------------------===//
1503 // Sparse compiler synthesis methods (loop sequence).
1504 //===----------------------------------------------------------------------===//
1505 
1506 /// Starts a loop sequence at given level. Returns true if
1507 /// the universal loop index must be maintained at this level.
1508 static bool startLoopSeq(Merger &merger, CodeGen &codegen,
1509                          PatternRewriter &rewriter, linalg::GenericOp op,
1510                          std::vector<unsigned> &topSort, unsigned exp,
1511                          unsigned at, unsigned idx, unsigned ldx,
1512                          unsigned lts) {
1513   assert(codegen.curVecLength == 1);
1514   assert(!codegen.loops[idx]);
1515   // Emit invariants at this loop sequence level.
1516   genInvariants(merger, codegen, rewriter, op, exp, ldx, /*atStart=*/true);
1517   // Emit access pattern expansion for sparse tensor output.
1518   genExpansion(merger, codegen, rewriter, op, at, /*atStart=*/true);
1519   // Emit further intitialization at this loop sequence level.
1520   unsigned l0 = merger.set(lts)[0];
1521   bool needsUniv =
1522       genInit(merger, codegen, rewriter, op, topSort, at, merger.lat(l0).bits);
1523   // Maintain the universal index only if it is actually
1524   // consumed by a subsequent lattice point.
1525   if (needsUniv) {
1526     unsigned lsize = merger.set(lts).size();
1527     for (unsigned i = 1; i < lsize; i++) {
1528       unsigned li = merger.set(lts)[i];
1529       if (!merger.hasAnyDimOf(merger.lat(li).simple, Dim::kSparse))
1530         return true;
1531     }
1532   }
1533   return false;
1534 }
1535 
1536 /// Starts a single loop in current sequence.
1537 static Operation *startLoop(Merger &merger, CodeGen &codegen,
1538                             PatternRewriter &rewriter, linalg::GenericOp op,
1539                             std::vector<unsigned> &topSort, unsigned at,
1540                             unsigned li, bool needsUniv) {
1541   assert(codegen.curVecLength == 1);
1542   // Emit the for/while-loop control.
1543   Operation *loop = genLoop(merger, codegen, rewriter, op, topSort, at,
1544                             needsUniv, merger.lat(li).simple);
1545   // Emit the locals for this loop.
1546   genLocals(merger, codegen, rewriter, op, topSort, at, needsUniv,
1547             merger.lat(li).bits);
1548   return loop;
1549 }
1550 
1551 /// Ends a single loop in current sequence. Returns new values for needsUniv.
1552 static bool endLoop(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
1553                     linalg::GenericOp op, Operation *loop, unsigned idx,
1554                     unsigned li, bool needsUniv) {
1555   codegen.curVecLength = 1;
1556   // End a while-loop.
1557   if (auto whileOp = dyn_cast<scf::WhileOp>(loop)) {
1558     genWhileInduction(merger, codegen, rewriter, op, idx, needsUniv,
1559                       merger.lat(li).bits, whileOp);
1560     return needsUniv;
1561   }
1562   // End a for-loop.
1563   genForInduction(merger, codegen, rewriter, op, loop);
1564   return false;
1565 }
1566 
1567 /// Ends a loop sequence at given level.
1568 static void endLoopSeq(Merger &merger, CodeGen &codegen,
1569                        PatternRewriter &rewriter, linalg::GenericOp op,
1570                        unsigned exp, unsigned at, unsigned idx, unsigned ldx) {
1571   assert(codegen.curVecLength == 1);
1572   codegen.loops[idx] = Value();
1573   // Bring a pending reduction back from SIMD form when sequence ends.
1574   if (codegen.redVal)
1575     if (auto vtp = codegen.redVal.getType().dyn_cast<VectorType>())
1576       updateReduc(merger, codegen,
1577                   genVectorReducEnd(codegen, rewriter, op.getLoc(), vtp));
1578   // Unmark bookkeeping of invariants and loop index.
1579   genInvariants(merger, codegen, rewriter, op, exp, ldx, /*atStart=*/false);
1580   // Finalize access pattern expansion for sparse tensor output.
1581   genExpansion(merger, codegen, rewriter, op, at, /*atStart=*/false);
1582 }
1583 
1584 /// Recursively generates code while computing iteration lattices in order
1585 /// to manage the complexity of implementing co-iteration over unions
1586 /// and intersections of sparse iterations spaces.
1587 static void genStmt(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
1588                     linalg::GenericOp op, std::vector<unsigned> &topSort,
1589                     unsigned exp, unsigned at) {
1590   // At each leaf, assign remaining tensor (sub)expression to output tensor.
1591   if (at == topSort.size()) {
1592     unsigned ldx = topSort[at - 1];
1593     Value rhs = genExp(merger, codegen, rewriter, op, exp, ldx);
1594     genTensorStore(merger, codegen, rewriter, op, rhs);
1595     return;
1596   }
1597 
1598   // Construct iteration lattices for current loop index, with L0 at top.
1599   unsigned idx = topSort[at];
1600   unsigned ldx = at == 0 ? -1u : topSort[at - 1];
1601   unsigned lts = merger.optimizeSet(merger.buildLattices(exp, idx));
1602 
1603   // Start a loop sequence.
1604   bool needsUniv = startLoopSeq(merger, codegen, rewriter, op, topSort, exp, at,
1605                                 idx, ldx, lts);
1606 
1607   // Emit a loop for every lattice point L0 >= Li in this loop sequence.
1608   unsigned lsize = merger.set(lts).size();
1609   for (unsigned i = 0; i < lsize; i++) {
1610     // Start a loop.
1611     unsigned li = merger.set(lts)[i];
1612     Operation *loop =
1613         startLoop(merger, codegen, rewriter, op, topSort, at, li, needsUniv);
1614 
1615     // Visit all lattices points with Li >= Lj to generate the
1616     // loop-body, possibly with if statements for coiteration.
1617     Value redInput = codegen.redVal;
1618     Value cntInput = codegen.expCount;
1619     bool isWhile = dyn_cast<scf::WhileOp>(loop) != nullptr;
1620     for (unsigned j = 0; j < lsize; j++) {
1621       unsigned lj = merger.set(lts)[j];
1622       unsigned ej = merger.lat(lj).exp;
1623       if (li == lj || merger.latGT(li, lj)) {
1624         // Recurse into body of each branch.
1625         if (isWhile) {
1626           scf::IfOp ifOp =
1627               genIf(merger, codegen, rewriter, op, idx, merger.lat(lj).simple);
1628           genStmt(merger, codegen, rewriter, op, topSort, ej, at + 1);
1629           endIf(merger, codegen, rewriter, op, ifOp, loop, redInput, cntInput);
1630         } else {
1631           genStmt(merger, codegen, rewriter, op, topSort, ej, at + 1);
1632         }
1633       }
1634     }
1635 
1636     // End a loop.
1637     needsUniv =
1638         endLoop(merger, codegen, rewriter, op, loop, idx, li, needsUniv);
1639   }
1640 
1641   // End a loop sequence.
1642   endLoopSeq(merger, codegen, rewriter, op, exp, at, idx, ldx);
1643 }
1644 
1645 /// Converts the result computed by the sparse kernel into the required form.
1646 static void genResult(Merger &merger, CodeGen &codegen,
1647                       PatternRewriter &rewriter, linalg::GenericOp op) {
1648   OpOperand *lhs = op.getOutputOperand(0);
1649   Type resType = lhs->get().getType();
1650   if (getSparseTensorEncoding(resType)) {
1651     // The sparse tensor rematerializes from the original sparse tensor's
1652     // underlying sparse storage format.
1653     rewriter.replaceOpWithNewOp<LoadOp>(op, resType, lhs->get(),
1654                                         codegen.sparseOut == lhs);
1655   } else {
1656     // To rematerialize an non-annotated tensor, simply load it
1657     // from the bufferized value.
1658     Value val = codegen.buffers.back(); // value array
1659     rewriter.replaceOpWithNewOp<bufferization::ToTensorOp>(op, resType, val);
1660   }
1661 }
1662 
1663 //===----------------------------------------------------------------------===//
1664 // Sparse compiler rewriting methods.
1665 //===----------------------------------------------------------------------===//
1666 
1667 namespace {
1668 
1669 /// Sparse rewriting rule for generic Lingalg operation.
1670 struct GenericOpSparsifier : public OpRewritePattern<linalg::GenericOp> {
1671 public:
1672   GenericOpSparsifier(MLIRContext *context, SparsificationOptions o)
1673       : OpRewritePattern<linalg::GenericOp>(context), options(o) {}
1674 
1675   LogicalResult matchAndRewrite(linalg::GenericOp op,
1676                                 PatternRewriter &rewriter) const override {
1677     // Detects sparse annotations and translate the per-dimension sparsity
1678     // information for all tensors to loop indices in the kernel.
1679     assert(op.getNumOutputs() == 1);
1680     unsigned numTensors = op.getNumInputsAndOutputs();
1681     unsigned numLoops = op.iterator_types().getValue().size();
1682     Merger merger(numTensors, numLoops);
1683     if (!findSparseAnnotations(merger, op))
1684       return failure();
1685 
1686     // Computes a topologically sorted iteration graph to ensure
1687     // tensors are visited in natural index order. Fails on cycles.
1688     // This assumes that higher-level passes have already put the
1689     // tensors in each tensor expression in a feasible order.
1690     std::vector<unsigned> topSort;
1691     if (!computeIterationGraph(merger, op, topSort,
1692                                SortMask::kIncludeUndef |
1693                                    SortMask::kIncludeDense) &&
1694         !computeIterationGraph(merger, op, topSort, SortMask::kIncludeUndef) &&
1695         !computeIterationGraph(merger, op, topSort, SortMask::kIncludeDense) &&
1696         !computeIterationGraph(merger, op, topSort, SortMask::kSparseOnly))
1697       return failure();
1698 
1699     // Builds the tensor expression for the Linalg operation in SSA form.
1700     Optional<unsigned> optExp = merger.buildTensorExpFromLinalg(op);
1701     if (!optExp.hasValue())
1702       return failure();
1703     unsigned exp = optExp.getValue();
1704 
1705     // Rejects an inadmissable tensor expression.
1706     OpOperand *sparseOut = nullptr;
1707     unsigned outerParNest = 0;
1708     if (!isAdmissableTensorExp(merger, op, topSort, exp, &sparseOut,
1709                                outerParNest))
1710       return failure();
1711 
1712     // Recursively generates code.
1713     merger.setHasSparseOut(sparseOut != nullptr);
1714     CodeGen codegen(options, numTensors, numLoops, sparseOut, outerParNest);
1715     genBuffers(merger, codegen, rewriter, op);
1716     genStmt(merger, codegen, rewriter, op, topSort, exp, 0);
1717     genResult(merger, codegen, rewriter, op);
1718     return success();
1719   }
1720 
1721 private:
1722   /// Options to control sparse code generation.
1723   SparsificationOptions options;
1724 };
1725 
1726 } // namespace
1727 
1728 /// Populates the given patterns list with rewriting rules required for
1729 /// the sparsification of linear algebra operations.
1730 void mlir::populateSparsificationPatterns(
1731     RewritePatternSet &patterns, const SparsificationOptions &options) {
1732   patterns.add<GenericOpSparsifier>(patterns.getContext(), options);
1733 }
1734