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