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 "mlir/Dialect/Affine/IR/AffineOps.h"
14 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
15 #include "mlir/Dialect/Linalg/Utils/Utils.h"
16 #include "mlir/Dialect/MemRef/IR/MemRef.h"
17 #include "mlir/Dialect/SCF/SCF.h"
18 #include "mlir/Dialect/SCF/Transforms.h"
19 #include "mlir/Dialect/SparseTensor/IR/SparseTensor.h"
20 #include "mlir/Dialect/SparseTensor/Transforms/Passes.h"
21 #include "mlir/Dialect/SparseTensor/Utils/Merger.h"
22 #include "mlir/Dialect/StandardOps/IR/Ops.h"
23 #include "mlir/Dialect/Vector/VectorOps.h"
24 #include "mlir/IR/Matchers.h"
25 #include "mlir/IR/TensorEncoding.h"
26 #include "llvm/ADT/SmallBitVector.h"
27 
28 using namespace mlir;
29 using namespace mlir::sparse_tensor;
30 
31 //===----------------------------------------------------------------------===//
32 // Declarations of data structures.
33 //===----------------------------------------------------------------------===//
34 
35 namespace {
36 
37 // Iteration graph sorting.
38 enum SortMask { kSparseOnly = 0x0, kIncludeDense = 0x1, kIncludeUndef = 0x2 };
39 
40 // Reduction kinds.
41 enum Reduction { kSum, kProduct, kAnd, kOr, kXor };
42 
43 // Code generation.
44 struct CodeGen {
45   CodeGen(SparsificationOptions o, unsigned numTensors, unsigned numLoops)
46       : options(o), loops(numLoops), sizes(numLoops), buffers(numTensors),
47         pointers(numTensors, std::vector<Value>(numLoops)),
48         indices(numTensors, std::vector<Value>(numLoops)),
49         highs(numTensors, std::vector<Value>(numLoops)),
50         pidxs(numTensors, std::vector<Value>(numLoops)),
51         idxs(numTensors, std::vector<Value>(numLoops)), redExp(-1u), redVal(),
52         curVecLength(1), curVecMask() {}
53   /// Sparsification options.
54   SparsificationOptions options;
55   /// Universal dense indices and upper bounds (by index). The loops array
56   /// is updated with the value of the universal dense index in the current
57   /// loop. The sizes array is set once with the inferred dimension sizes.
58   std::vector<Value> loops;
59   std::vector<Value> sizes;
60   /// Buffers for storing dense and sparse numerical values (by tensor).
61   /// This array is set once during bufferization of all tensors.
62   std::vector<Value> buffers;
63   /// Sparse storage schemes (1-D): pointers and indices (by tensor and index).
64   /// This array is set once during bufferization of all sparse tensors.
65   std::vector<std::vector<Value>> pointers;
66   std::vector<std::vector<Value>> indices;
67   /// Sparse iteration information (by tensor and index). These arrays
68   /// are updated to remain current within the current loop.
69   std::vector<std::vector<Value>> highs;
70   std::vector<std::vector<Value>> pidxs;
71   std::vector<std::vector<Value>> idxs;
72   /// Current reduction, updated during code generation. When indices of a
73   /// reduction are exhausted,  all inner loops can "scalarize" the reduction.
74   // TODO: currently only done for (a chain of) innermost for-loops, where it
75   // is most effective; we could generalize to more outer and while-loops.
76   unsigned redExp;
77   Value redVal;
78   Reduction redKind;
79   // Current vector length and mask.
80   unsigned curVecLength;
81   Value curVecMask;
82 };
83 
84 } // namespace
85 
86 //===----------------------------------------------------------------------===//
87 // Sparse compiler analysis methods.
88 //===----------------------------------------------------------------------===//
89 
90 /// Helper method to apply dimension ordering permutation.
91 static unsigned perm(const SparseTensorEncodingAttr &enc, unsigned d) {
92   if (enc) {
93     auto order = enc.getDimOrdering();
94     if (order) {
95       assert(order.isPermutation());
96       return order.getDimPosition(d);
97     }
98   }
99   return d;
100 }
101 
102 /// Helper method to translate dim level type to internal representation.
103 static Dim toDim(const SparseTensorEncodingAttr &enc, unsigned d) {
104   if (enc) {
105     SparseTensorEncodingAttr::DimLevelType tp = enc.getDimLevelType()[d];
106     if (tp == SparseTensorEncodingAttr::DimLevelType::Compressed)
107       return Dim::kSparse;
108     if (tp == SparseTensorEncodingAttr::DimLevelType::Singleton)
109       return Dim::kSingle;
110   }
111   return Dim::kDense;
112 }
113 
114 /// Helper method to inspect affine expressions. Rejects cases where the
115 /// same index is used in more than one dimension of a tensor. Also rejects
116 /// affine expressions that are not a direct index for annotated tensors.
117 /// TODO: accept more affine cases for sparse tensors
118 static bool findAffine(Merger &merger, unsigned tensor, AffineExpr a, Dim dim,
119                        bool isDense) {
120   switch (a.getKind()) {
121   case AffineExprKind::DimId: {
122     unsigned idx = a.cast<AffineDimExpr>().getPosition();
123     if (!merger.isDim(tensor, idx, Dim::kUndef))
124       return false; // used more than once
125     merger.setDim(tensor, idx, dim);
126     return true;
127   }
128   case AffineExprKind::Add:
129   case AffineExprKind::Mul: {
130     if (!isDense)
131       return false;
132     auto binOp = a.cast<AffineBinaryOpExpr>();
133     return findAffine(merger, tensor, binOp.getLHS(), dim, isDense) &&
134            findAffine(merger, tensor, binOp.getRHS(), dim, isDense);
135   }
136   case AffineExprKind::Constant:
137     return isDense;
138   default:
139     return false;
140   }
141 }
142 
143 /// Helper method to inspect sparse encodings in the tensor types.
144 /// Fills the per-dimension sparsity information for all tensors.
145 /// Returns true if the sparse annotations and affine subscript
146 /// expressions of all tensors are admissable. Returns false if
147 /// no annotations are found or inadmissable constructs occur.
148 static bool findSparseAnnotations(Merger &merger, linalg::GenericOp op) {
149   bool annotated = false;
150   for (OpOperand *t : op.getInputAndOutputOperands()) {
151     auto map = op.getTiedIndexingMap(t);
152     auto enc = getSparseTensorEncoding(t->get().getType());
153     if (enc)
154       annotated = true;
155     assert(map.getNumResults() == op.getRank(t));
156     for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) {
157       unsigned tensor = t->getOperandNumber();
158       AffineExpr a = map.getResult(perm(enc, d));
159       if (!findAffine(merger, tensor, a, toDim(enc, d), !enc))
160         return false; // inadmissable affine expression
161     }
162   }
163   return annotated;
164 }
165 
166 /// A DFS helper to compute a topological sort. Note that recursion is
167 /// bounded by the number of implicit loops, which is always small.
168 /// Returns false when a cycle is detected.
169 static bool topSortDFS(unsigned i, std::vector<unsigned> &visit,
170                        std::vector<unsigned> &topSort,
171                        std::vector<std::vector<bool>> &adjM) {
172   if (visit[i] != 0)
173     return visit[i] != 1; // 1 denotes cycle!
174   visit[i] = 1;
175   for (unsigned j = 0, e = visit.size(); j < e; j++)
176     if (adjM[i][j])
177       if (!topSortDFS(j, visit, topSort, adjM))
178         return false;
179   visit[i] = 2;
180   topSort.push_back(i);
181   return true;
182 }
183 
184 /// Helper method to add all constraints from the indices in one affine
185 /// expression before all indices in the other affine expression. For
186 /// example i0+i1 < i2+i3+1 yields i0<i2, i0<i3, i1<i2, and i1<i3.
187 static void addAffineOrderings(std::vector<std::vector<bool>> &adjM,
188                                AffineExpr a, AffineExpr b, unsigned fidx) {
189   switch (a.getKind()) {
190   case AffineExprKind::DimId: {
191     unsigned idx = a.cast<AffineDimExpr>().getPosition();
192     if (b)
193       addAffineOrderings(adjM, b, AffineExpr(), idx);
194     else
195       adjM[fidx][idx] = true;
196     break;
197   }
198   case AffineExprKind::Add:
199   case AffineExprKind::Mul: {
200     auto binOp = a.cast<AffineBinaryOpExpr>();
201     addAffineOrderings(adjM, binOp.getLHS(), b, fidx);
202     addAffineOrderings(adjM, binOp.getRHS(), b, fidx);
203     break;
204   }
205   default:
206     break;
207   }
208 }
209 
210 /// Computes a topologically sorted iteration graph for the linalg operation.
211 /// Ensures all tensors are visited in natural index order. This is essential
212 /// for sparse storage formats since these only support access along fixed
213 /// dimensions. Even for dense storage formats, however, the natural index
214 /// order yields innermost unit-stride access with better spatial locality.
215 static bool computeIterationGraph(Merger &merger, linalg::GenericOp op,
216                                   std::vector<unsigned> &topSort,
217                                   unsigned mask) {
218   // Set up an n x n from/to adjacency matrix of the iteration graph
219   // for the implicit loop indices i_0 .. i_n-1.
220   unsigned n = op.getNumLoops();
221   std::vector<std::vector<bool>> adjM(n, std::vector<bool>(n, false));
222 
223   // Iterate over the indexing maps of every tensor in the tensor expression.
224   for (OpOperand *t : op.getInputAndOutputOperands()) {
225     auto map = op.getTiedIndexingMap(t);
226     auto enc = getSparseTensorEncoding(t->get().getType());
227     assert(map.getNumDims() == n);
228     // Skip dense tensor constraints when not requested.
229     if (!(mask & SortMask::kIncludeDense) && !enc)
230       continue;
231     // Each tensor expression and optional dimension ordering (row-major
232     // by default) puts an ordering constraint on the loop indices. For
233     // example, the tensor expresion A_ijk forces the ordering i < j < k
234     // on the loop indices if no explicit dimension ordering is given.
235     for (unsigned d = 1, rank = map.getNumResults(); d < rank; d++) {
236       AffineExpr f = map.getResult(perm(enc, d - 1));
237       AffineExpr t = map.getResult(perm(enc, d));
238       addAffineOrderings(adjM, f, t, 0);
239     }
240     // Push unrelated loops into sparse iteration space, so these
241     // will be skipped more often.
242     if (mask & SortMask::kIncludeUndef) {
243       unsigned tensor = t->getOperandNumber();
244       for (unsigned i = 0; i < n; i++)
245         if (merger.isDim(tensor, i, Dim::kSparse))
246           for (unsigned j = 0; j < n; j++)
247             if (merger.isDim(tensor, j, Dim::kUndef))
248               adjM[i][j] = true;
249     }
250   }
251 
252   // Topologically sort the iteration graph to determine loop order.
253   // Report failure for a cyclic iteration graph.
254   topSort.clear();
255   topSort.reserve(n);
256   std::vector<unsigned> visit(n, 0);
257   for (unsigned i = 0; i < n; i++)
258     if (visit[i] == 0)
259       if (!topSortDFS(i, visit, topSort, adjM))
260         return false; // cycle!
261   std::reverse(std::begin(topSort), std::end(topSort));
262   return true;
263 }
264 
265 /// Returns true when the tensor expression is admissable for codegen.
266 /// Since all sparse input tensors are admissable, we just need to check
267 /// whether the output tensor in the tensor expression codegen is admissable.
268 static bool isAdmissableTensorExp(Merger &merger, linalg::GenericOp op,
269                                   unsigned exp) {
270   OpOperand *lhs = op.getOutputOperand(0);
271   unsigned tensor = lhs->getOperandNumber();
272   auto enc = getSparseTensorEncoding(lhs->get().getType());
273   // An non-annotated output tensor is assumed dense, and becomes a random
274   // access n-dim memref. Admissable since insertions cannot occur.
275   if (!enc)
276     return true;
277   // An all-dense annotated "sparse" output tensor becomes a linearized random
278   // access 1-dim memref. Also admissable since insertions cannot occur.
279   bool allDense = true;
280   unsigned numLoops = op.iterator_types().getValue().size();
281   for (unsigned i = 0; i < numLoops; i++)
282     if (merger.isDim(tensor, i, Dim::kSparse)) {
283       allDense = false;
284       break;
285     }
286   if (allDense)
287     return true;
288   // A tensor expression with a sparse output tensor that changes its values
289   // but not its nonzero structure, an operation called "simply dynamic" in
290   // [Bik96,Ch9], is also admissable without special codegen.
291   if (merger.isConjunction(tensor, exp))
292     return true;
293   // Reject for now since this requires changes to the nonzero structure.
294   // TODO: implement "workspaces" [Kjolstad2019]
295   return false;
296 }
297 
298 //===----------------------------------------------------------------------===//
299 // Sparse compiler synthesis methods.
300 //===----------------------------------------------------------------------===//
301 
302 /// Maps reduction kind to name encoding.
303 static StringRef getReductionName(Reduction kind) {
304   switch (kind) {
305   case kSum:
306     return "add";
307   case kProduct:
308     return "mul";
309   case kAnd:
310     return "and";
311   case kOr:
312     return "or";
313   case kXor:
314     return "xor";
315   }
316   llvm_unreachable("unknown reduction kind");
317 }
318 
319 /// Maps operation to reduction.
320 static Reduction getReduction(Kind kind) {
321   switch (kind) {
322   case Kind::kAddF:
323   case Kind::kAddI:
324   case Kind::kSubF:
325   case Kind::kSubI:
326     return kSum;
327   case Kind::kMulF:
328   case Kind::kMulI:
329     return kProduct;
330   case Kind::kAndI:
331     return kAnd;
332   case Kind::kOrI:
333     return kOr;
334   case Kind::kXorI:
335     return kXor;
336   default:
337     llvm_unreachable("unexpected reduction operator");
338   }
339 }
340 
341 /// Generates an initial value for a vector reductions, following the scheme
342 /// given in Chapter 5 of "The Software Vectorization Handbook", where the
343 /// initial scalar value is correctly embedded in the vector reduction value,
344 /// and a straightforward horizontal reduction will complete the operation.
345 static Value genReductionInit(PatternRewriter &rewriter, Location loc,
346                               Reduction kind, VectorType vtp, Value r) {
347   switch (kind) {
348   case kSum:
349   case kXor: {
350     // Initialize reduction vector to: | 0 | .. | 0 | r |
351     Attribute zero = rewriter.getZeroAttr(vtp);
352     Value vec = rewriter.create<ConstantOp>(loc, vtp, zero);
353     return rewriter.create<vector::InsertElementOp>(loc, r, vec, 0);
354   }
355   case kProduct: {
356     // Initialize reduction vector to: | 1 | .. | 1 | r |
357     Type etp = vtp.getElementType();
358     Attribute one;
359     if (etp.isa<FloatType>())
360       one = rewriter.getFloatAttr(etp, 1.0);
361     else
362       one = rewriter.getIntegerAttr(etp, 1);
363     Value vec =
364         rewriter.create<ConstantOp>(loc, vtp, DenseElementsAttr::get(vtp, one));
365     return rewriter.create<vector::InsertElementOp>(loc, r, vec, 0);
366   }
367   case kAnd:
368   case kOr:
369     // Initialize reduction vector to: | r | .. | r | r |
370     return rewriter.create<vector::BroadcastOp>(loc, vtp, r);
371   }
372   llvm_unreachable("unknown reduction kind");
373 }
374 
375 /// Maps sparse integer option to actual integral storage type.
376 static Type genIntType(PatternRewriter &rewriter, unsigned width) {
377   if (width == 0)
378     return rewriter.getIndexType();
379   return rewriter.getIntegerType(width);
380 }
381 
382 /// Detects in-place annotation on tensor argument.
383 static bool getInPlace(Value val) {
384   if (auto arg = val.dyn_cast<BlockArgument>())
385     if (auto funcOp = dyn_cast<FuncOp>(arg.getOwner()->getParentOp()))
386       if (auto attr = funcOp.getArgAttrOfType<BoolAttr>(
387               arg.getArgNumber(), linalg::LinalgDialect::kInplaceableAttrName))
388         return attr.getValue();
389   return false;
390 }
391 
392 /// Generates buffer for the output tensor.
393 static Value genOutputBuffer(CodeGen &codegen, PatternRewriter &rewriter,
394                              linalg::GenericOp op, MemRefType denseTp,
395                              ArrayRef<Value> args) {
396   Location loc = op.getLoc();
397   Value tensor = op.getOutputOperand(0)->get();
398   // The output tensor simply could materialize from the buffer that will
399   // be generated for the tensor present in the outs() clause. This has
400   // the major advantage that the sparse kernel only updates the nonzero
401   // positions for the output tensor.
402   if (getInPlace(tensor))
403     return rewriter.create<memref::BufferCastOp>(loc, denseTp, tensor);
404   // By default, a new buffer is allocated which is initialized to the
405   // tensor defined in the outs() clause. This is always correct but
406   // introduces a dense initialization component that may negatively
407   // impact the running complexity of the sparse kernel.
408   Value init = rewriter.create<memref::BufferCastOp>(loc, denseTp, tensor);
409   Value alloc = rewriter.create<memref::AllocOp>(loc, denseTp, args);
410   rewriter.create<memref::CopyOp>(loc, init, alloc);
411   return alloc;
412 }
413 
414 /// Local bufferization of all dense and sparse data structures.
415 /// This code enables testing the first prototype sparse compiler.
416 // TODO: replace this with a proliferated bufferization strategy
417 static bool genBuffers(Merger &merger, CodeGen &codegen,
418                        PatternRewriter &rewriter, linalg::GenericOp op) {
419   Location loc = op.getLoc();
420   assert(op.getNumInputsAndOutputs() == op.getNumInputs() + 1);
421   // For every tensor, find lower and upper bound on dimensions, set the
422   // same bounds on loop indices, and obtain dense or sparse buffer(s).
423   SmallVector<Value, 4> args;
424   for (OpOperand *t : op.getInputAndOutputOperands()) {
425     unsigned tensor = t->getOperandNumber();
426     auto shape = op.getShape(t);
427     auto map = op.getTiedIndexingMap(t);
428     auto enc = getSparseTensorEncoding(t->get().getType());
429     // Scan all dimensions of current tensor.
430     args.clear();
431     for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) {
432       AffineExpr a = map.getResult(perm(enc, d));
433       if (a.getKind() != AffineExprKind::DimId)
434         continue; // compound
435       unsigned idx = a.cast<AffineDimExpr>().getPosition();
436       // Handle sparse storage schemes.
437       if (merger.isDim(tensor, idx, Dim::kSparse)) {
438         auto dynShape = {ShapedType::kDynamicSize};
439         auto ptrTp = MemRefType::get(
440             dynShape, genIntType(rewriter, enc.getPointerBitWidth()));
441         auto indTp = MemRefType::get(
442             dynShape, genIntType(rewriter, enc.getIndexBitWidth()));
443         Value dim = rewriter.create<ConstantIndexOp>(loc, d);
444         // Generate sparse primitives to obtains pointer and indices.
445         codegen.pointers[tensor][idx] =
446             rewriter.create<ToPointersOp>(loc, ptrTp, t->get(), dim);
447         codegen.indices[tensor][idx] =
448             rewriter.create<ToIndicesOp>(loc, indTp, t->get(), dim);
449       }
450       // Find upper bound in current dimension.
451       unsigned p = perm(enc, d);
452       Value up = linalg::createOrFoldDimOp(rewriter, loc, t->get(), p);
453       if (shape[p] == MemRefType::kDynamicSize)
454         args.push_back(up);
455       assert(codegen.highs[tensor][idx] == nullptr);
456       codegen.sizes[idx] = codegen.highs[tensor][idx] = up;
457     }
458     // Perform the required bufferization. Dense inputs materialize
459     // from the input tensors. Dense outputs need special handling.
460     // Sparse inputs use sparse primitives to obtain the values.
461     // We also accept in-place all-dense annotated "sparse" outputs.
462     Type elementType = getElementTypeOrSelf(t->get().getType());
463     if (!enc) {
464       // Non-annotated dense tensors.
465       auto denseTp = MemRefType::get(shape, elementType);
466       if (tensor < op.getNumInputs())
467         codegen.buffers[tensor] =
468             rewriter.create<memref::BufferCastOp>(loc, denseTp, t->get());
469       else
470         codegen.buffers[tensor] =
471             genOutputBuffer(codegen, rewriter, op, denseTp, args);
472     } else {
473       // Annotated sparse tensors.
474       if (tensor == op.getNumInputs() && !getInPlace(t->get()))
475         return false; // reject output if not in-place
476       auto dynShape = {ShapedType::kDynamicSize};
477       auto sparseTp = MemRefType::get(dynShape, elementType);
478       codegen.buffers[tensor] =
479           rewriter.create<ToValuesOp>(loc, sparseTp, t->get());
480     }
481   }
482   return true;
483 }
484 
485 /// Constructs vector type.
486 static VectorType vectorType(CodeGen &codegen, Type etp) {
487   return VectorType::get(codegen.curVecLength, etp);
488 }
489 
490 /// Constructs vector type from pointer.
491 static VectorType vectorType(CodeGen &codegen, Value ptr) {
492   return vectorType(codegen, ptr.getType().cast<MemRefType>().getElementType());
493 }
494 
495 /// Constructs vector iteration mask.
496 static Value genVectorMask(CodeGen &codegen, PatternRewriter &rewriter,
497                            Value iv, Value lo, Value hi, Value step) {
498   Location loc = iv.getLoc();
499   VectorType mtp = vectorType(codegen, rewriter.getIntegerType(1));
500   // Special case if the vector length evenly divides the trip count (for
501   // example, "for i = 0, 128, 16"). A constant all-true mask is generated
502   // so that all subsequent masked memory operations are immediately folded
503   // into unconditional memory operations.
504   IntegerAttr loInt, hiInt, stepInt;
505   if (matchPattern(lo, m_Constant(&loInt)) &&
506       matchPattern(hi, m_Constant(&hiInt)) &&
507       matchPattern(step, m_Constant(&stepInt))) {
508     if (((hiInt.getInt() - loInt.getInt()) % stepInt.getInt()) == 0)
509       return rewriter.create<vector::BroadcastOp>(
510           loc, mtp, rewriter.create<ConstantIntOp>(loc, 1, 1));
511   }
512   // Otherwise, generate a vector mask that avoids overrunning the upperbound
513   // during vector execution. Here we rely on subsequent loop optimizations to
514   // avoid executing the mask in all iterations, for example, by splitting the
515   // loop into an unconditional vector loop and a scalar cleanup loop.
516   auto minMap = AffineMap::get(
517       /*dimCount=*/2, /*symbolCount=*/1,
518       {rewriter.getAffineSymbolExpr(0),
519        rewriter.getAffineDimExpr(0) - rewriter.getAffineDimExpr(1)},
520       rewriter.getContext());
521   Value end =
522       rewriter.createOrFold<AffineMinOp>(loc, minMap, ValueRange{hi, iv, step});
523   return rewriter.create<vector::CreateMaskOp>(loc, mtp, end);
524 }
525 
526 /// Generates a vectorized load lhs = a[ind[lo:hi]] or lhs = a[lo:hi].
527 static Value genVectorLoad(CodeGen &codegen, PatternRewriter &rewriter,
528                            Value ptr, ArrayRef<Value> args) {
529   Location loc = ptr.getLoc();
530   VectorType vtp = vectorType(codegen, ptr);
531   Value pass = rewriter.create<ConstantOp>(loc, vtp, rewriter.getZeroAttr(vtp));
532   if (args.back().getType().isa<VectorType>()) {
533     SmallVector<Value, 4> scalarArgs(args.begin(), args.end());
534     Value indexVec = args.back();
535     scalarArgs.back() = rewriter.create<ConstantIndexOp>(loc, 0);
536     return rewriter.create<vector::GatherOp>(
537         loc, vtp, ptr, scalarArgs, indexVec, codegen.curVecMask, pass);
538   }
539   return rewriter.create<vector::MaskedLoadOp>(loc, vtp, ptr, args,
540                                                codegen.curVecMask, pass);
541 }
542 
543 /// Generates a vectorized store a[ind[lo:hi]] = rhs or a[lo:hi] = rhs.
544 static void genVectorStore(CodeGen &codegen, PatternRewriter &rewriter,
545                            Value rhs, Value ptr, ArrayRef<Value> args) {
546   Location loc = ptr.getLoc();
547   if (args.back().getType().isa<VectorType>()) {
548     SmallVector<Value, 4> scalarArgs(args.begin(), args.end());
549     Value indexVec = args.back();
550     scalarArgs.back() = rewriter.create<ConstantIndexOp>(loc, 0);
551     rewriter.create<vector::ScatterOp>(loc, ptr, scalarArgs, indexVec,
552                                        codegen.curVecMask, rhs);
553     return;
554   }
555   rewriter.create<vector::MaskedStoreOp>(loc, ptr, args, codegen.curVecMask,
556                                          rhs);
557 }
558 
559 /// Generates a vectorized invariant. Here we rely on subsequent loop
560 /// optimizations to hoist the invariant broadcast out of the vector loop.
561 static Value genVectorInvariantValue(CodeGen &codegen,
562                                      PatternRewriter &rewriter, Value val) {
563   VectorType vtp = vectorType(codegen, val.getType());
564   return rewriter.create<vector::BroadcastOp>(val.getLoc(), vtp, val);
565 }
566 
567 /// Generates an affine expression.
568 //
569 // TODO: generalize for sparse tensor subscripts
570 //
571 static Value genAffine(CodeGen &codegen, PatternRewriter &rewriter,
572                        AffineExpr a, Location loc) {
573   switch (a.getKind()) {
574   case AffineExprKind::DimId: {
575     unsigned idx = a.cast<AffineDimExpr>().getPosition();
576     return codegen.loops[idx]; // universal dense index
577   }
578   case AffineExprKind::Add: {
579     auto binOp = a.cast<AffineBinaryOpExpr>();
580     return rewriter.create<AddIOp>(
581         loc, genAffine(codegen, rewriter, binOp.getLHS(), loc),
582         genAffine(codegen, rewriter, binOp.getRHS(), loc));
583   }
584   case AffineExprKind::Mul: {
585     auto binOp = a.cast<AffineBinaryOpExpr>();
586     return rewriter.create<MulIOp>(
587         loc, genAffine(codegen, rewriter, binOp.getLHS(), loc),
588         genAffine(codegen, rewriter, binOp.getRHS(), loc));
589   }
590   case AffineExprKind::Constant: {
591     int64_t c = a.cast<AffineConstantExpr>().getValue();
592     return rewriter.create<ConstantIndexOp>(loc, c);
593   }
594   default:
595     llvm_unreachable("unexpected affine subscript");
596   }
597 }
598 
599 /// Generates subscript for load/store on a dense or sparse tensor.
600 static Value genSubscript(CodeGen &codegen, PatternRewriter &rewriter,
601                           linalg::GenericOp op, OpOperand *t,
602                           SmallVector<Value, 4> &args) {
603   unsigned tensor = t->getOperandNumber();
604   auto map = op.getTiedIndexingMap(t);
605   auto enc = getSparseTensorEncoding(t->get().getType());
606   unsigned rank = map.getNumResults();
607   if (enc) {
608     // Note that currently, all sparse subscripts are simple.
609     // TODO: accept affine too?
610     unsigned idx = map.getDimPosition(perm(enc, rank - 1));
611     assert(codegen.pidxs[tensor][idx] != nullptr);
612     args.push_back(codegen.pidxs[tensor][idx]); // position index
613   } else {
614     for (unsigned d = 0; d < rank; d++) {
615       AffineExpr a = map.getResult(perm(enc, d));
616       args.push_back(genAffine(codegen, rewriter, a, op.getLoc()));
617     }
618   }
619   return codegen.buffers[tensor];
620 }
621 
622 /// Generates a load on a dense or sparse tensor.
623 static Value genTensorLoad(Merger &merger, CodeGen &codegen,
624                            PatternRewriter &rewriter, linalg::GenericOp op,
625                            unsigned exp) {
626   // Test if the load was hoisted to a higher loop nest.
627   Value val = merger.exp(exp).val;
628   if (val) {
629     if (codegen.curVecLength > 1 && !val.getType().isa<VectorType>())
630       return genVectorInvariantValue(codegen, rewriter, val);
631     return val;
632   }
633   // Actual load.
634   SmallVector<Value, 4> args;
635   OpOperand *t = op.getInputAndOutputOperands()[merger.exp(exp).tensor];
636   Value ptr = genSubscript(codegen, rewriter, op, t, args);
637   if (codegen.curVecLength > 1)
638     return genVectorLoad(codegen, rewriter, ptr, args);
639   return rewriter.create<memref::LoadOp>(op.getLoc(), ptr, args);
640 }
641 
642 /// Generates a store on a dense or sparse tensor.
643 static void genTensorStore(Merger &merger, CodeGen &codegen,
644                            PatternRewriter &rewriter, linalg::GenericOp op,
645                            Value rhs) {
646   // Test if this is a scalarized reduction.
647   if (codegen.redVal) {
648     if (codegen.curVecLength > 1)
649       rhs = rewriter.create<SelectOp>(op.getLoc(), codegen.curVecMask, rhs,
650                                       codegen.redVal);
651     codegen.redVal = rhs;
652     return;
653   }
654   // Actual store.
655   SmallVector<Value, 4> args;
656   OpOperand *t = op.getOutputOperand(0);
657   Value ptr = genSubscript(codegen, rewriter, op, t, args);
658   if (codegen.curVecLength > 1)
659     genVectorStore(codegen, rewriter, rhs, ptr, args);
660   else
661     rewriter.create<memref::StoreOp>(op.getLoc(), rhs, ptr, args);
662 }
663 
664 /// Generates a pointer/index load from the sparse storage scheme. Narrower
665 /// data types need to be zero extended before casting the value into the
666 /// index type used for looping and indexing.
667 static Value genLoad(CodeGen &codegen, PatternRewriter &rewriter, Location loc,
668                      Value ptr, Value s) {
669   // See https://llvm.org/docs/GetElementPtr.html for some background on
670   // the complications described below.
671   if (codegen.curVecLength > 1) {
672     // Since the index vector is used in a subsequent gather/scatter operations,
673     // which effectively defines an unsigned pointer + signed index, we must
674     // zero extend the vector to an index width. For 8-bit and 16-bit values,
675     // an 32-bit index width suffices. For 32-bit values, zero extending the
676     // elements into 64-bit loses some performance since the 32-bit indexed
677     // gather/scatter is more efficient than the 64-bit index variant (if the
678     // negative 32-bit index space is unused, the enableSIMDIndex32 flag can
679     // preserve this performance). For 64-bit values, there is no good way
680     // to state that the indices are unsigned, with creates the potential of
681     // incorrect address calculations in the unlikely case we need such
682     // extremely large offsets.
683     Type etp = ptr.getType().cast<MemRefType>().getElementType();
684     Value vload = genVectorLoad(codegen, rewriter, ptr, {s});
685     if (!etp.isa<IndexType>()) {
686       if (etp.getIntOrFloatBitWidth() < 32)
687         vload = rewriter.create<ZeroExtendIOp>(
688             loc, vload, vectorType(codegen, rewriter.getIntegerType(32)));
689       else if (etp.getIntOrFloatBitWidth() < 64 &&
690                !codegen.options.enableSIMDIndex32)
691         vload = rewriter.create<ZeroExtendIOp>(
692             loc, vload, vectorType(codegen, rewriter.getIntegerType(64)));
693     }
694     return vload;
695   }
696   // For the scalar case, we simply zero extend narrower indices into 64-bit
697   // values before casting to index without a performance penalty. Here too,
698   // however, indices that already are 64-bit, in theory, cannot express the
699   // full range as explained above.
700   Value load = rewriter.create<memref::LoadOp>(loc, ptr, s);
701   if (!load.getType().isa<IndexType>()) {
702     if (load.getType().getIntOrFloatBitWidth() < 64)
703       load = rewriter.create<ZeroExtendIOp>(loc, load,
704                                             rewriter.getIntegerType(64));
705     load = rewriter.create<IndexCastOp>(loc, load, rewriter.getIndexType());
706   }
707   return load;
708 }
709 
710 /// Generates an invariant value.
711 static Value genInvariantValue(Merger &merger, CodeGen &codegen,
712                                PatternRewriter &rewriter, unsigned exp) {
713   Value val = merger.exp(exp).val;
714   if (codegen.curVecLength > 1)
715     return genVectorInvariantValue(codegen, rewriter, val);
716   return val;
717 }
718 
719 /// Generates an address computation "sz * p + i".
720 static Value genAddress(CodeGen &codegen, PatternRewriter &rewriter,
721                         Location loc, Value size, Value p, Value i) {
722   Value mul = rewriter.create<MulIOp>(loc, size, p);
723   if (auto vtp = i.getType().dyn_cast<VectorType>()) {
724     Value inv = rewriter.create<IndexCastOp>(loc, mul, vtp.getElementType());
725     mul = genVectorInvariantValue(codegen, rewriter, inv);
726   }
727   return rewriter.create<AddIOp>(loc, mul, i);
728 }
729 
730 /// Generates start of a reduction.
731 static Value genReductionStart(Merger &merger, CodeGen &codegen,
732                                PatternRewriter &rewriter,
733                                linalg::GenericOp op) {
734   if (codegen.redVal)
735     return codegen.redVal; // chained with previous for-loop
736   // Generate vector or scalar start of a reduction.
737   unsigned vl = codegen.curVecLength;
738   if (vl > 1) {
739     VectorType vtp = vectorType(codegen, codegen.buffers[codegen.redExp]);
740     assert(!merger.exp(codegen.redExp).val);
741     codegen.curVecLength = 1;
742     Value load = genTensorLoad(merger, codegen, rewriter, op, codegen.redExp);
743     codegen.curVecLength = vl;
744     return genReductionInit(rewriter, op.getLoc(), codegen.redKind, vtp, load);
745   }
746   return genTensorLoad(merger, codegen, rewriter, op, codegen.redExp);
747 }
748 
749 /// Generates end of a reduction.
750 static void genReductionEnd(Merger &merger, CodeGen &codegen,
751                             PatternRewriter &rewriter, linalg::GenericOp op) {
752   Value red = codegen.redVal;
753   if (!red)
754     return;
755   assert(codegen.curVecLength == 1);
756   codegen.redVal = merger.exp(codegen.redExp).val = Value(); // end chain
757   // Generate vector or scalar end of a reduction.
758   if (auto vtp = red.getType().dyn_cast<VectorType>()) {
759     StringRef name = getReductionName(codegen.redKind);
760     StringAttr kind = rewriter.getStringAttr(name);
761     red = rewriter.create<vector::ReductionOp>(
762         op.getLoc(), vtp.getElementType(), kind, red, ValueRange{});
763   }
764   genTensorStore(merger, codegen, rewriter, op, red);
765 }
766 
767 /// Recursively generates tensor expression.
768 static Value genExp(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
769                     linalg::GenericOp op, unsigned exp) {
770   Location loc = op.getLoc();
771   if (exp == -1u)
772     return Value();
773   if (merger.exp(exp).kind == Kind::kTensor)
774     return genTensorLoad(merger, codegen, rewriter, op, exp);
775   if (merger.exp(exp).kind == Kind::kInvariant)
776     return genInvariantValue(merger, codegen, rewriter, exp);
777   Value v0 = genExp(merger, codegen, rewriter, op, merger.exp(exp).children.e0);
778   Value v1 = genExp(merger, codegen, rewriter, op, merger.exp(exp).children.e1);
779   if (merger.exp(exp).kind == Kind::kNegI) {
780     // TODO: no negi in std, need to make zero explicit.
781     Type tp = op.getOutputTensorTypes()[0].getElementType();
782     v1 = v0;
783     v0 = rewriter.create<ConstantOp>(loc, tp, rewriter.getZeroAttr(tp));
784     if (codegen.curVecLength > 1)
785       v0 = genVectorInvariantValue(codegen, rewriter, v0);
786   }
787   return merger.buildExp(rewriter, loc, exp, v0, v1);
788 }
789 
790 /// Determines if affine expression is invariant.
791 static bool isInvariantAffine(const CodeGen &codegen, AffineExpr a,
792                               unsigned ldx, bool &atLevel) {
793   switch (a.getKind()) {
794   case AffineExprKind::DimId: {
795     unsigned idx = a.cast<AffineDimExpr>().getPosition();
796     if (idx == ldx)
797       atLevel = true;
798     return codegen.loops[idx] != nullptr; // no longer in play?
799   }
800   case AffineExprKind::Add:
801   case AffineExprKind::Mul: {
802     auto binOp = a.cast<AffineBinaryOpExpr>();
803     return isInvariantAffine(codegen, binOp.getLHS(), ldx, atLevel) &&
804            isInvariantAffine(codegen, binOp.getRHS(), ldx, atLevel);
805   }
806   default:
807     return true;
808   }
809 }
810 
811 /// Hoists loop invariant tensor loads for which indices have been exhausted.
812 static void genInvariants(Merger &merger, CodeGen &codegen,
813                           PatternRewriter &rewriter, linalg::GenericOp op,
814                           unsigned exp, unsigned ldx, bool hoist,
815                           Kind last = Kind::kTensor) {
816   if (exp == -1u)
817     return;
818   if (merger.exp(exp).kind == Kind::kTensor) {
819     // Inspect tensor indices.
820     bool atLevel = ldx == -1u;
821     OpOperand *t = op.getInputAndOutputOperands()[merger.exp(exp).tensor];
822     auto map = op.getTiedIndexingMap(t);
823     auto enc = getSparseTensorEncoding(t->get().getType());
824     for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) {
825       AffineExpr a = map.getResult(perm(enc, d));
826       if (!isInvariantAffine(codegen, a, ldx, atLevel))
827         return; // still in play
828     }
829     // All exhausted at this level (atLevel denotes exactly at this level).
830     OpOperand *lhs = op.getOutputOperand(0);
831     if (lhs == t) {
832       codegen.redExp = hoist ? exp : -1u;
833       codegen.redKind = getReduction(last);
834     } else if (atLevel) {
835       merger.exp(exp).val =
836           hoist ? genTensorLoad(merger, codegen, rewriter, op, exp) : Value();
837     }
838   } else if (merger.exp(exp).kind != Kind::kInvariant) {
839     // Traverse into the binary operations. Note that we only hoist
840     // tensor loads, since subsequent MLIR/LLVM passes know how to
841     // deal with all other kinds of derived loop invariants.
842     Kind last = merger.exp(exp).kind;
843     unsigned e0 = merger.exp(exp).children.e0;
844     unsigned e1 = merger.exp(exp).children.e1;
845     genInvariants(merger, codegen, rewriter, op, e0, ldx, hoist, last);
846     genInvariants(merger, codegen, rewriter, op, e1, ldx, hoist, last);
847   }
848 }
849 
850 /// Generates initialization code for the subsequent loop sequence at
851 /// current index level. Returns true if the loop sequence needs to
852 /// maintain the universal index.
853 static bool genInit(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
854                     linalg::GenericOp op, std::vector<unsigned> &topSort,
855                     unsigned at, llvm::BitVector &inits) {
856   bool needsUniv = false;
857   Location loc = op.getLoc();
858   unsigned idx = topSort[at];
859 
860   // Initialize sparse positions.
861   for (unsigned b = 0, be = inits.size(); b < be; b++) {
862     if (inits[b]) {
863       unsigned tensor = merger.tensor(b);
864       assert(idx == merger.index(b));
865       if (merger.isDim(b, Dim::kSparse)) {
866         // Initialize sparse index.
867         unsigned pat = at;
868         for (; pat != 0; pat--) {
869           if (codegen.pidxs[tensor][topSort[pat - 1]])
870             break;
871         }
872         Value ptr = codegen.pointers[tensor][idx];
873         Value one = rewriter.create<ConstantIndexOp>(loc, 1);
874         Value p0 = (pat == 0) ? rewriter.create<ConstantIndexOp>(loc, 0)
875                               : codegen.pidxs[tensor][topSort[pat - 1]];
876         codegen.pidxs[tensor][idx] = genLoad(codegen, rewriter, loc, ptr, p0);
877         Value p1 = rewriter.create<AddIOp>(loc, p0, one);
878         codegen.highs[tensor][idx] = genLoad(codegen, rewriter, loc, ptr, p1);
879       } else {
880         // Dense index still in play.
881         needsUniv = true;
882       }
883     }
884   }
885 
886   // Initialize the universal dense index.
887   codegen.loops[idx] = rewriter.create<ConstantIndexOp>(loc, 0);
888   return needsUniv;
889 }
890 
891 /// Returns vectorization strategy. Any implicit inner loop in the Linalg
892 /// operation is a candidate. Whether it is actually converted to SIMD code
893 /// depends on the requested strategy.
894 static bool isVectorFor(CodeGen &codegen, bool isInner, bool isSparse) {
895   switch (codegen.options.vectorizationStrategy) {
896   case SparseVectorizationStrategy::kNone:
897     return false;
898   case SparseVectorizationStrategy::kDenseInnerLoop:
899     return isInner && !isSparse;
900   case SparseVectorizationStrategy::kAnyStorageInnerLoop:
901     return isInner;
902   }
903   llvm_unreachable("unexpected vectorization strategy");
904 }
905 
906 /// Returns parallelization strategy. Any implicit loop in the Linalg operation
907 /// that is marked "parallel" is a candidate. Whether it is actually converted
908 /// to a parallel operation depends on the requested strategy.
909 static bool isParallelFor(CodeGen &codegen, bool isOuter, bool isReduction,
910                           bool isSparse, bool isVector) {
911   switch (codegen.options.parallelizationStrategy) {
912   case SparseParallelizationStrategy::kNone:
913     return false;
914   case SparseParallelizationStrategy::kDenseOuterLoop:
915     return isOuter && !isSparse && !isReduction && !isVector;
916   case SparseParallelizationStrategy::kAnyStorageOuterLoop:
917     return isOuter && !isReduction && !isVector;
918   case SparseParallelizationStrategy::kDenseAnyLoop:
919     return !isSparse && !isReduction && !isVector;
920   case SparseParallelizationStrategy::kAnyStorageAnyLoop:
921     return !isReduction && !isVector;
922   }
923   llvm_unreachable("unexpected parallelization strategy");
924 }
925 
926 /// Checks unit strides for dense tensors. The iteration graph may have ignored
927 /// dense access patterns in order to avoid cycles (sparse access patterns are
928 /// always placed innermost), but that means dense access has become strided.
929 /// For now, we reject vectorization of such cases.
930 /// TODO: implement strided load/stores on dense arrays
931 static bool denseUnitStrides(Merger &merger, linalg::GenericOp op,
932                              unsigned ldx) {
933   for (OpOperand *t : op.getInputAndOutputOperands()) {
934     if (!getSparseTensorEncoding(t->get().getType())) {
935       auto map = op.getTiedIndexingMap(t);
936       for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) {
937         AffineExpr a = map.getResult(d);
938         if (a.getKind() != AffineExprKind::DimId)
939           return false; // very conservative
940         unsigned idx = a.cast<AffineDimExpr>().getPosition();
941         if (idx == ldx && d != rank - 1)
942           return false;
943       }
944     }
945   }
946   return true;
947 }
948 
949 /// Generates a for-loop on a single index.
950 static Operation *genFor(Merger &merger, CodeGen &codegen,
951                          PatternRewriter &rewriter, linalg::GenericOp op,
952                          bool isOuter, bool isInner, unsigned idx,
953                          llvm::BitVector &indices) {
954   unsigned fb = indices.find_first();
955   unsigned tensor = merger.tensor(fb);
956   assert(idx == merger.index(fb));
957   auto iteratorTypes = op.iterator_types().getValue();
958   bool isReduction = isReductionIterator(iteratorTypes[idx]);
959   bool isSparse = merger.isDim(fb, Dim::kSparse);
960   bool isVector = isVectorFor(codegen, isInner, isSparse) &&
961                   denseUnitStrides(merger, op, idx);
962   bool isParallel =
963       isParallelFor(codegen, isOuter, isReduction, isSparse, isVector);
964 
965   // Prepare vector length.
966   if (isVector)
967     codegen.curVecLength = codegen.options.vectorLength;
968 
969   // Loop bounds and increment.
970   Location loc = op.getLoc();
971   Value lo = isSparse ? codegen.pidxs[tensor][idx] : codegen.loops[idx];
972   Value hi = isSparse ? codegen.highs[tensor][idx] : codegen.sizes[idx];
973   Value step = rewriter.create<ConstantIndexOp>(loc, codegen.curVecLength);
974 
975   // Emit a parallel loop.
976   if (isParallel) {
977     assert(!isVector);
978     scf::ParallelOp parOp = rewriter.create<scf::ParallelOp>(loc, lo, hi, step);
979     if (isSparse)
980       codegen.pidxs[tensor][idx] = parOp.getInductionVars()[0];
981     else
982       codegen.loops[idx] = parOp.getInductionVars()[0];
983     rewriter.setInsertionPointToStart(parOp.getBody());
984     return parOp;
985   }
986 
987   // Emit a sequential loop, potentially with a scalarized reduction.
988   bool scalarRed = isInner && codegen.redExp != -1u;
989   SmallVector<Value, 4> operands;
990   if (scalarRed) {
991     Value load = genReductionStart(merger, codegen, rewriter, op);
992     operands.push_back(load);
993   }
994   scf::ForOp forOp = rewriter.create<scf::ForOp>(loc, lo, hi, step, operands);
995   if (scalarRed) {
996     codegen.redVal = merger.exp(codegen.redExp).val =
997         forOp.getRegionIterArgs().front();
998   }
999   // Assign induction variable to sparse or dense index.
1000   Value iv = forOp.getInductionVar();
1001   if (isSparse)
1002     codegen.pidxs[tensor][idx] = iv;
1003   else
1004     codegen.loops[idx] = iv;
1005   rewriter.setInsertionPointToStart(forOp.getBody());
1006   // Share vector iteration mask between all subsequent loads/stores.
1007   if (isVector)
1008     codegen.curVecMask = genVectorMask(codegen, rewriter, iv, lo, hi, step);
1009   return forOp;
1010 }
1011 
1012 /// Emit a while-loop for co-iteration over multiple indices.
1013 static Operation *genWhile(Merger &merger, CodeGen &codegen,
1014                            PatternRewriter &rewriter, linalg::GenericOp op,
1015                            unsigned idx, bool needsUniv,
1016                            llvm::BitVector &indices) {
1017   SmallVector<Type, 4> types;
1018   SmallVector<Value, 4> operands;
1019   // Construct the while-loop with a parameter for each index.
1020   Type indexType = rewriter.getIndexType();
1021   for (unsigned b = 0, be = indices.size(); b < be; b++) {
1022     if (indices[b] && merger.isDim(b, Dim::kSparse)) {
1023       unsigned tensor = merger.tensor(b);
1024       assert(idx == merger.index(b));
1025       types.push_back(indexType);
1026       assert(codegen.pidxs[tensor][idx].getType().isa<IndexType>() &&
1027              "type mismatch for sparse index");
1028       operands.push_back(codegen.pidxs[tensor][idx]);
1029     }
1030   }
1031   if (needsUniv) {
1032     types.push_back(indexType);
1033     assert(codegen.loops[idx].getType().isa<IndexType>() &&
1034            "type mismatch for universal index");
1035     operands.push_back(codegen.loops[idx]);
1036   }
1037   Location loc = op.getLoc();
1038   scf::WhileOp whileOp = rewriter.create<scf::WhileOp>(loc, types, operands);
1039   Block *before = rewriter.createBlock(&whileOp.before(), {}, types);
1040   Block *after = rewriter.createBlock(&whileOp.after(), {}, types);
1041 
1042   // Build the "before" region, which effectively consists
1043   // of a conjunction of "i < upper" tests on all induction.
1044   rewriter.setInsertionPointToStart(&whileOp.before().front());
1045   Value cond;
1046   unsigned o = 0;
1047   for (unsigned b = 0, be = indices.size(); b < be; b++) {
1048     if (indices[b] && merger.isDim(b, Dim::kSparse)) {
1049       unsigned tensor = merger.tensor(b);
1050       assert(idx == merger.index(b));
1051       Value op1 = before->getArgument(o);
1052       Value op2 = codegen.highs[tensor][idx];
1053       Value opc = rewriter.create<CmpIOp>(loc, CmpIPredicate::ult, op1, op2);
1054       cond = cond ? rewriter.create<AndOp>(loc, cond, opc) : opc;
1055       codegen.pidxs[tensor][idx] = after->getArgument(o++);
1056     }
1057   }
1058   if (needsUniv)
1059     codegen.loops[idx] = after->getArgument(o++);
1060   assert(o == operands.size());
1061   rewriter.create<scf::ConditionOp>(loc, cond, before->getArguments());
1062   rewriter.setInsertionPointToStart(&whileOp.after().front());
1063   return whileOp;
1064 }
1065 
1066 /// Generates a for-loop or a while-loop, depending on whether it implements
1067 /// singleton iteration or co-iteration over the given conjunction.
1068 static Operation *genLoop(Merger &merger, CodeGen &codegen,
1069                           PatternRewriter &rewriter, linalg::GenericOp op,
1070                           std::vector<unsigned> &topSort, unsigned at,
1071                           bool needsUniv, llvm::BitVector &indices) {
1072   unsigned idx = topSort[at];
1073   if (indices.count() == 1) {
1074     bool isOuter = at == 0;
1075     bool isInner = at == topSort.size() - 1;
1076     return genFor(merger, codegen, rewriter, op, isOuter, isInner, idx,
1077                   indices);
1078   }
1079   genReductionEnd(merger, codegen, rewriter, op); // cannot chain
1080   return genWhile(merger, codegen, rewriter, op, idx, needsUniv, indices);
1081 }
1082 
1083 /// Generates the local variables for this loop, consisting of the sparse
1084 /// indices, restored universal dense index, and dense positions.
1085 static void genLocals(Merger &merger, CodeGen &codegen,
1086                       PatternRewriter &rewriter, linalg::GenericOp op,
1087                       std::vector<unsigned> &topSort, unsigned at,
1088                       bool needsUniv, llvm::BitVector &locals) {
1089   Location loc = op.getLoc();
1090   unsigned idx = topSort[at];
1091 
1092   // Initialize sparse indices.
1093   Value min;
1094   for (unsigned b = 0, be = locals.size(); b < be; b++) {
1095     if (locals[b] && merger.isDim(b, Dim::kSparse)) {
1096       unsigned tensor = merger.tensor(b);
1097       assert(idx == merger.index(b));
1098       Value ptr = codegen.indices[tensor][idx];
1099       Value s = codegen.pidxs[tensor][idx];
1100       Value load = genLoad(codegen, rewriter, loc, ptr, s);
1101       codegen.idxs[tensor][idx] = load;
1102       if (!needsUniv) {
1103         if (min) {
1104           Value cmp =
1105               rewriter.create<CmpIOp>(loc, CmpIPredicate::ult, load, min);
1106           min = rewriter.create<SelectOp>(loc, cmp, load, min);
1107         } else {
1108           min = load;
1109         }
1110       }
1111     }
1112   }
1113 
1114   // Merge dense universal index over minimum.
1115   if (min) {
1116     assert(!needsUniv);
1117     codegen.loops[idx] = min;
1118   }
1119 
1120   // Initialize dense positions. Note that we generate dense indices of the
1121   // output tensor unconditionally, since they may not appear in the lattice,
1122   // but may be needed for linearized codegen.
1123   for (unsigned b = 0, be = locals.size(); b < be; b++) {
1124     if ((locals[b] || merger.isOutTensor(b, idx)) &&
1125         merger.isDim(b, Dim::kDense)) {
1126       unsigned tensor = merger.tensor(b);
1127       assert(idx == merger.index(b));
1128       unsigned pat = at;
1129       for (; pat != 0; pat--)
1130         if (codegen.pidxs[tensor][topSort[pat - 1]])
1131           break;
1132       Value p = (pat == 0) ? rewriter.create<ConstantIndexOp>(loc, 0)
1133                            : codegen.pidxs[tensor][topSort[pat - 1]];
1134       codegen.pidxs[tensor][idx] = genAddress(
1135           codegen, rewriter, loc, codegen.sizes[idx], p, codegen.loops[idx]);
1136     }
1137   }
1138 }
1139 
1140 /// Generates the induction structure for a while-loop.
1141 static void genWhileInduction(Merger &merger, CodeGen &codegen,
1142                               PatternRewriter &rewriter, linalg::GenericOp op,
1143                               unsigned idx, bool needsUniv,
1144                               llvm::BitVector &induction, ResultRange results) {
1145   Location loc = op.getLoc();
1146   unsigned o = 0;
1147   SmallVector<Value, 4> operands;
1148   Value one = rewriter.create<ConstantIndexOp>(loc, 1);
1149   for (unsigned b = 0, be = induction.size(); b < be; b++) {
1150     if (induction[b] && merger.isDim(b, Dim::kSparse)) {
1151       unsigned tensor = merger.tensor(b);
1152       assert(idx == merger.index(b));
1153       Value op1 = codegen.idxs[tensor][idx];
1154       Value op2 = codegen.loops[idx];
1155       Value op3 = codegen.pidxs[tensor][idx];
1156       Value cmp = rewriter.create<CmpIOp>(loc, CmpIPredicate::eq, op1, op2);
1157       Value add = rewriter.create<AddIOp>(loc, op3, one);
1158       operands.push_back(rewriter.create<SelectOp>(loc, cmp, add, op3));
1159       codegen.pidxs[tensor][idx] = results[o++];
1160     }
1161   }
1162   if (needsUniv) {
1163     operands.push_back(rewriter.create<AddIOp>(loc, codegen.loops[idx], one));
1164     codegen.loops[idx] = results[o++];
1165   }
1166   assert(o == operands.size());
1167   rewriter.create<scf::YieldOp>(loc, operands);
1168 }
1169 
1170 /// Generates a single if-statement within a while-loop.
1171 static scf::IfOp genIf(Merger &merger, CodeGen &codegen,
1172                        PatternRewriter &rewriter, linalg::GenericOp op,
1173                        unsigned idx, llvm::BitVector &conditions) {
1174   Location loc = op.getLoc();
1175   Value cond;
1176   for (unsigned b = 0, be = conditions.size(); b < be; b++) {
1177     if (conditions[b]) {
1178       unsigned tensor = merger.tensor(b);
1179       assert(idx == merger.index(b));
1180       Value clause;
1181       if (merger.isDim(b, Dim::kSparse)) {
1182         Value op1 = codegen.idxs[tensor][idx];
1183         Value op2 = codegen.loops[idx];
1184         clause = rewriter.create<CmpIOp>(loc, CmpIPredicate::eq, op1, op2);
1185       } else {
1186         clause = rewriter.create<ConstantIntOp>(loc, 1, 1); // true
1187       }
1188       cond = cond ? rewriter.create<AndOp>(loc, cond, clause) : clause;
1189     }
1190   }
1191   scf::IfOp ifOp = rewriter.create<scf::IfOp>(loc, cond, /*else*/ true);
1192   rewriter.setInsertionPointToStart(&ifOp.thenRegion().front());
1193   return ifOp;
1194 }
1195 
1196 /// Recursively generates code while computing iteration lattices in order
1197 /// to manage the complexity of implementing co-iteration over unions
1198 /// and intersections of sparse iterations spaces.
1199 static void genStmt(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
1200                     linalg::GenericOp op, std::vector<unsigned> &topSort,
1201                     unsigned exp, unsigned at) {
1202   // At each leaf, assign remaining tensor (sub)expression to output tensor.
1203   if (at == topSort.size()) {
1204     Value rhs = genExp(merger, codegen, rewriter, op, exp);
1205     genTensorStore(merger, codegen, rewriter, op, rhs);
1206     return;
1207   }
1208   assert(codegen.curVecLength == 1);
1209 
1210   // Construct iteration lattices for current loop index, with L0 at top.
1211   // Then emit initialization code for the loop sequence at this level.
1212   // We maintain the universal dense index if dense indices are still
1213   // in play for a non-singleton loop sequence.
1214   Location loc = op.getLoc();
1215   unsigned idx = topSort[at];
1216   unsigned lts = merger.optimizeSet(merger.buildLattices(exp, idx));
1217   unsigned lsize = merger.set(lts).size();
1218   assert(lsize != 0);
1219   unsigned l0 = merger.set(lts)[0];
1220   unsigned ldx = at == 0 ? -1u : topSort[at - 1];
1221   genInvariants(merger, codegen, rewriter, op, exp, ldx, /*hoist=*/true);
1222   bool needsUniv = false;
1223   if (genInit(merger, codegen, rewriter, op, topSort, at,
1224               merger.lat(l0).bits)) {
1225     // Maintain the universal index only if it is actually
1226     // consumed by a subsequent lattice point.
1227     for (unsigned i = 1; i < lsize; i++) {
1228       unsigned li = merger.set(lts)[i];
1229       if (!merger.hasAnyDimOf(merger.lat(li).simple, Dim::kSparse)) {
1230         needsUniv = true;
1231         break;
1232       }
1233     }
1234   }
1235 
1236   // Emit a loop for every lattice point L0 >= Li.
1237   for (unsigned i = 0; i < lsize; i++) {
1238     unsigned li = merger.set(lts)[i];
1239 
1240     // Emit loop.
1241     codegen.curVecLength = 1;
1242     llvm::BitVector indices = merger.lat(li).simple;
1243     Operation *loop =
1244         genLoop(merger, codegen, rewriter, op, topSort, at, needsUniv, indices);
1245     genLocals(merger, codegen, rewriter, op, topSort, at, needsUniv,
1246               merger.lat(li).bits);
1247 
1248     // Visit all lattices points with Li >= Lj to generate the
1249     // loop-body, possibly with if statements for coiteration.
1250     bool isWhile = dyn_cast<scf::WhileOp>(loop) != nullptr;
1251     for (unsigned j = 0; j < lsize; j++) {
1252       unsigned lj = merger.set(lts)[j];
1253       unsigned ej = merger.lat(lj).exp;
1254       if (li == lj || merger.latGT(li, lj)) {
1255         // Recurse into body of each branch.
1256         if (isWhile) {
1257           scf::IfOp ifOp =
1258               genIf(merger, codegen, rewriter, op, idx, merger.lat(lj).simple);
1259           genStmt(merger, codegen, rewriter, op, topSort, ej, at + 1);
1260           rewriter.setInsertionPointToStart(&ifOp.elseRegion().front());
1261         } else {
1262           genStmt(merger, codegen, rewriter, op, topSort, ej, at + 1);
1263         }
1264       }
1265     }
1266 
1267     // Wrap-up induction and restore insertion point.
1268     if (isWhile) {
1269       scf::WhileOp whileOp = cast<scf::WhileOp>(loop);
1270       rewriter.setInsertionPointToEnd(&whileOp.after().front());
1271       genWhileInduction(merger, codegen, rewriter, op, idx, needsUniv,
1272                         merger.lat(li).bits, whileOp.results());
1273     } else {
1274       needsUniv = false;
1275       if (codegen.redVal) {
1276         rewriter.create<scf::YieldOp>(loc, codegen.redVal);
1277         codegen.redVal = loop->getResult(0);
1278       }
1279     }
1280     rewriter.setInsertionPointAfter(loop);
1281   }
1282 
1283   // Wrap-up loop sequence.
1284   codegen.curVecLength = 1;
1285   genReductionEnd(merger, codegen, rewriter, op);
1286   genInvariants(merger, codegen, rewriter, op, exp, ldx, /*hoist=*/false);
1287   codegen.loops[idx] = Value();
1288 }
1289 
1290 /// Converts the result computed by the sparse kernel into the required form.
1291 static void genResult(Merger &merger, CodeGen &codegen,
1292                       PatternRewriter &rewriter, linalg::GenericOp op) {
1293   Location loc = op.getLoc();
1294   OpOperand *lhs = op.getOutputOperand(0);
1295   Type resType = lhs->get().getType();
1296   unsigned tensor = lhs->getOperandNumber();
1297   auto map = op.getTiedIndexingMap(lhs);
1298   auto enc = getSparseTensorEncoding(resType);
1299   Value result = codegen.buffers.back(); // value array
1300   if (enc) {
1301     // The sparse annotation unambigiously defines the arrays needed
1302     // to "reconstruct" the sparse tensor from the storage scheme
1303     // (even though lowering should never need this eventually).
1304     SmallVector<Value, 4> args;
1305     for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) {
1306       AffineExpr a = map.getResult(perm(enc, d));
1307       if (a.getKind() != AffineExprKind::DimId)
1308         continue; // compound
1309       unsigned idx = a.cast<AffineDimExpr>().getPosition();
1310       if (merger.isDim(tensor, idx, Dim::kSparse)) {
1311         args.push_back(codegen.pointers[tensor][idx]);
1312         args.push_back(codegen.indices[tensor][idx]);
1313       }
1314     }
1315     args.push_back(result);
1316     result = rewriter.create<ToTensorOp>(loc, resType, args);
1317   } else {
1318     // To "reconstruct" an non-annotated tensor, sipmly load it
1319     // from the bufferized value.
1320     result = rewriter.create<memref::TensorLoadOp>(loc, resType, result);
1321   }
1322   rewriter.replaceOp(op, result);
1323 }
1324 
1325 //===----------------------------------------------------------------------===//
1326 // Sparse compiler rewriting methods.
1327 //===----------------------------------------------------------------------===//
1328 
1329 namespace {
1330 
1331 /// Sparse rewriting rule for generic Lingalg operation.
1332 struct GenericOpSparsifier : public OpRewritePattern<linalg::GenericOp> {
1333 public:
1334   GenericOpSparsifier(MLIRContext *context, SparsificationOptions o)
1335       : OpRewritePattern<linalg::GenericOp>(context), options(o) {}
1336 
1337   LogicalResult matchAndRewrite(linalg::GenericOp op,
1338                                 PatternRewriter &rewriter) const override {
1339     // Detects sparse annotations and translate the per-dimension sparsity
1340     // information for all tensors to loop indices in the kernel.
1341     assert(op.getNumOutputs() == 1);
1342     unsigned numTensors = op.getNumInputsAndOutputs();
1343     unsigned numLoops = op.iterator_types().getValue().size();
1344     Merger merger(numTensors, numLoops);
1345     if (!findSparseAnnotations(merger, op))
1346       return failure();
1347 
1348     // Computes a topologically sorted iteration graph to ensure
1349     // tensors are visited in natural index order. Fails on cycles.
1350     // This assumes that higher-level passes have already put the
1351     // tensors in each tensor expression in a feasible order.
1352     std::vector<unsigned> topSort;
1353     if (!computeIterationGraph(merger, op, topSort,
1354                                SortMask::kIncludeUndef |
1355                                    SortMask::kIncludeDense) &&
1356         !computeIterationGraph(merger, op, topSort, SortMask::kIncludeUndef) &&
1357         !computeIterationGraph(merger, op, topSort, SortMask::kIncludeDense) &&
1358         !computeIterationGraph(merger, op, topSort, SortMask::kSparseOnly))
1359       return failure();
1360 
1361     // Builds the tensor expression for the Linalg operation in SSA form.
1362     Optional<unsigned> exp = merger.buildTensorExpFromLinalg(op);
1363     if (!exp.hasValue())
1364       return failure();
1365 
1366     // Rejects an inadmissable tensor expression.
1367     if (!isAdmissableTensorExp(merger, op, exp.getValue()))
1368       return failure();
1369 
1370     // Recursively generates code.
1371     CodeGen codegen(options, numTensors, numLoops);
1372     if (!genBuffers(merger, codegen, rewriter, op))
1373       return failure(); // could not bufferize
1374     genStmt(merger, codegen, rewriter, op, topSort, exp.getValue(), 0);
1375     genResult(merger, codegen, rewriter, op);
1376     return success();
1377   }
1378 
1379 private:
1380   /// Options to control sparse code generation.
1381   SparsificationOptions options;
1382 };
1383 
1384 } // namespace
1385 
1386 /// Populates the given patterns list with rewriting rules required for
1387 /// the sparsification of linear algebra operations.
1388 void mlir::populateSparsificationPatterns(
1389     RewritePatternSet &patterns, const SparsificationOptions &options) {
1390   patterns.add<GenericOpSparsifier>(patterns.getContext(), options);
1391 }
1392