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<memref::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 (exp == -1u) 613 return Value(); 614 if (merger.exp(exp).kind == Kind::kTensor) 615 return genTensorLoad(merger, codegen, rewriter, op, exp); 616 if (merger.exp(exp).kind == Kind::kInvariant) 617 return genInvariantValue(merger, codegen, rewriter, exp); 618 Value v0 = genExp(merger, codegen, rewriter, op, merger.exp(exp).children.e0); 619 Value v1 = genExp(merger, codegen, rewriter, op, merger.exp(exp).children.e1); 620 if (merger.exp(exp).kind == Kind::kNegI) { 621 // TODO: no negi in std, need to make zero explicit. 622 Type tp = op.getOutputTensorTypes()[0].getElementType(); 623 v1 = v0; 624 v0 = rewriter.create<ConstantOp>(loc, tp, rewriter.getZeroAttr(tp)); 625 if (codegen.curVecLength > 1) 626 v0 = genVectorInvariantValue(codegen, rewriter, v0); 627 } 628 return merger.buildExp(rewriter, loc, exp, v0, v1); 629 } 630 631 /// Hoists loop invariant tensor loads for which indices have been exhausted. 632 static void genInvariants(Merger &merger, CodeGen &codegen, 633 PatternRewriter &rewriter, linalg::GenericOp op, 634 unsigned exp, unsigned ldx, bool hoist) { 635 if (exp == -1u) 636 return; 637 if (merger.exp(exp).kind == Kind::kTensor) { 638 // Inspect tensor indices. 639 bool atLevel = ldx == -1u; 640 OpOperand *t = op.getInputAndOutputOperands()[merger.exp(exp).tensor]; 641 auto map = op.getTiedIndexingMap(t); 642 auto enc = getSparseTensorEncoding(t->get().getType()); 643 for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) { 644 unsigned idx = map.getDimPosition(perm(enc, d)); 645 if (!codegen.loops[idx]) 646 return; // still in play 647 else if (idx == ldx) 648 atLevel = true; 649 } 650 // All exhausted at this level (atLevel denotes exactly at this level). 651 OpOperand *lhs = op.getOutputOperand(0); 652 if (lhs == t) { 653 codegen.redExp = hoist ? exp : -1u; 654 } else if (atLevel) { 655 merger.exp(exp).val = 656 hoist ? genTensorLoad(merger, codegen, rewriter, op, exp) : Value(); 657 } 658 } else if (merger.exp(exp).kind != Kind::kInvariant) { 659 // Traverse into the binary operations. Note that we only hoist 660 // tensor loads, since subsequent MLIR/LLVM passes know how to 661 // deal with all other kinds of derived loop invariants. 662 unsigned e0 = merger.exp(exp).children.e0; 663 unsigned e1 = merger.exp(exp).children.e1; 664 genInvariants(merger, codegen, rewriter, op, e0, ldx, hoist); 665 genInvariants(merger, codegen, rewriter, op, e1, ldx, hoist); 666 } 667 } 668 669 /// Generates initialization code for the subsequent loop sequence at 670 /// current index level. Returns true if the loop sequence needs to 671 /// maintain the universal index. 672 static bool genInit(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter, 673 linalg::GenericOp op, std::vector<unsigned> &topSort, 674 unsigned at, llvm::BitVector &inits) { 675 bool needsUniv = false; 676 Location loc = op.getLoc(); 677 unsigned idx = topSort[at]; 678 679 // Initialize sparse positions. 680 for (unsigned b = 0, be = inits.size(); b < be; b++) { 681 if (inits[b]) { 682 unsigned tensor = merger.tensor(b); 683 assert(idx == merger.index(b)); 684 if (merger.isDim(b, Dim::kSparse)) { 685 // Initialize sparse index. 686 unsigned pat = at; 687 for (; pat != 0; pat--) { 688 if (codegen.pidxs[tensor][topSort[pat - 1]]) 689 break; 690 } 691 Value ptr = codegen.pointers[tensor][idx]; 692 Value one = rewriter.create<ConstantIndexOp>(loc, 1); 693 Value p0 = (pat == 0) ? rewriter.create<ConstantIndexOp>(loc, 0) 694 : codegen.pidxs[tensor][topSort[pat - 1]]; 695 codegen.pidxs[tensor][idx] = genLoad(codegen, rewriter, loc, ptr, p0); 696 Value p1 = rewriter.create<AddIOp>(loc, p0, one); 697 codegen.highs[tensor][idx] = genLoad(codegen, rewriter, loc, ptr, p1); 698 } else { 699 // Dense index still in play. 700 needsUniv = true; 701 } 702 } 703 } 704 705 // Initialize the universal dense index. 706 codegen.loops[idx] = rewriter.create<ConstantIndexOp>(loc, 0); 707 return needsUniv; 708 } 709 710 /// Returns vectorization strategy. Any implicit inner loop in the Linalg 711 /// operation is a candidate. Whether it is actually converted to SIMD code 712 /// depends on the requested strategy. 713 static bool isVectorFor(CodeGen &codegen, bool isInner, bool isSparse) { 714 switch (codegen.options.vectorizationStrategy) { 715 case SparseVectorizationStrategy::kNone: 716 return false; 717 case SparseVectorizationStrategy::kDenseInnerLoop: 718 return isInner && !isSparse; 719 case SparseVectorizationStrategy::kAnyStorageInnerLoop: 720 return isInner; 721 } 722 llvm_unreachable("unexpected vectorization strategy"); 723 } 724 725 /// Returns parallelization strategy. Any implicit loop in the Linalg operation 726 /// that is marked "parallel" is a candidate. Whether it is actually converted 727 /// to a parallel operation depends on the requested strategy. 728 static bool isParallelFor(CodeGen &codegen, bool isOuter, bool isReduction, 729 bool isSparse, bool isVector) { 730 switch (codegen.options.parallelizationStrategy) { 731 case SparseParallelizationStrategy::kNone: 732 return false; 733 case SparseParallelizationStrategy::kDenseOuterLoop: 734 return isOuter && !isSparse && !isReduction && !isVector; 735 case SparseParallelizationStrategy::kAnyStorageOuterLoop: 736 return isOuter && !isReduction && !isVector; 737 case SparseParallelizationStrategy::kDenseAnyLoop: 738 return !isSparse && !isReduction && !isVector; 739 case SparseParallelizationStrategy::kAnyStorageAnyLoop: 740 return !isReduction && !isVector; 741 } 742 llvm_unreachable("unexpected parallelization strategy"); 743 } 744 745 /// Checks unit strides for dense tensors. The iteration graph may have ignored 746 /// dense access patterns in order to avoid cycles (sparse access patterns are 747 /// always placed innermost), but that means dense access has become strided. 748 /// For now, we reject vectorization of such cases. 749 /// TODO: implement strided load/stores on dense arrays 750 static bool denseUnitStrides(Merger &merger, linalg::GenericOp op, 751 unsigned idx) { 752 for (OpOperand *t : op.getInputAndOutputOperands()) { 753 if (!getSparseTensorEncoding(t->get().getType())) { 754 auto map = op.getTiedIndexingMap(t); 755 for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) { 756 if (map.getDimPosition(d) == idx && d != rank - 1) 757 return false; 758 } 759 } 760 } 761 return true; 762 } 763 764 /// Generates a for-loop on a single index. 765 static Operation *genFor(Merger &merger, CodeGen &codegen, 766 PatternRewriter &rewriter, linalg::GenericOp op, 767 bool isOuter, bool isInner, unsigned idx, 768 llvm::BitVector &indices) { 769 unsigned fb = indices.find_first(); 770 unsigned tensor = merger.tensor(fb); 771 assert(idx == merger.index(fb)); 772 auto iteratorTypes = op.iterator_types().getValue(); 773 bool isReduction = linalg::isReductionIteratorType(iteratorTypes[idx]); 774 bool isSparse = merger.isDim(fb, Dim::kSparse); 775 bool isVector = isVectorFor(codegen, isInner, isSparse) && 776 denseUnitStrides(merger, op, idx); 777 bool isParallel = 778 isParallelFor(codegen, isOuter, isReduction, isSparse, isVector); 779 780 // Prepare vector length. 781 if (isVector) 782 codegen.curVecLength = codegen.options.vectorLength; 783 784 // Loop bounds and increment. 785 Location loc = op.getLoc(); 786 Value lo = isSparse ? codegen.pidxs[tensor][idx] : codegen.loops[idx]; 787 Value hi = isSparse ? codegen.highs[tensor][idx] : codegen.sizes[idx]; 788 Value step = rewriter.create<ConstantIndexOp>(loc, codegen.curVecLength); 789 790 // Emit a parallel loop. 791 if (isParallel) { 792 assert(!isVector); 793 scf::ParallelOp parOp = rewriter.create<scf::ParallelOp>(loc, lo, hi, step); 794 if (isSparse) 795 codegen.pidxs[tensor][idx] = parOp.getInductionVars()[0]; 796 else 797 codegen.loops[idx] = parOp.getInductionVars()[0]; 798 rewriter.setInsertionPointToStart(parOp.getBody()); 799 return parOp; 800 } 801 802 // Emit a sequential loop, potentially with a scalarized reduction. 803 bool scalarRed = isInner && codegen.redExp != -1u; 804 SmallVector<Value, 4> operands; 805 if (scalarRed) { 806 Value load = genReductionStart(merger, codegen, rewriter, op); 807 operands.push_back(load); 808 } 809 scf::ForOp forOp = rewriter.create<scf::ForOp>(loc, lo, hi, step, operands); 810 if (scalarRed) { 811 codegen.redVal = merger.exp(codegen.redExp).val = 812 forOp.getRegionIterArgs().front(); 813 } 814 // Assign induction variable to sparse or dense index. 815 Value iv = forOp.getInductionVar(); 816 if (isSparse) 817 codegen.pidxs[tensor][idx] = iv; 818 else 819 codegen.loops[idx] = iv; 820 rewriter.setInsertionPointToStart(forOp.getBody()); 821 // Share vector iteration mask between all subsequent loads/stores. 822 if (isVector) 823 codegen.curVecMask = genVectorMask(codegen, rewriter, iv, lo, hi, step); 824 return forOp; 825 } 826 827 /// Emit a while-loop for co-iteration over multiple indices. 828 static Operation *genWhile(Merger &merger, CodeGen &codegen, 829 PatternRewriter &rewriter, linalg::GenericOp op, 830 unsigned idx, bool needsUniv, 831 llvm::BitVector &indices) { 832 SmallVector<Type, 4> types; 833 SmallVector<Value, 4> operands; 834 // Construct the while-loop with a parameter for each index. 835 Type indexType = rewriter.getIndexType(); 836 for (unsigned b = 0, be = indices.size(); b < be; b++) { 837 if (indices[b] && merger.isDim(b, Dim::kSparse)) { 838 unsigned tensor = merger.tensor(b); 839 assert(idx == merger.index(b)); 840 types.push_back(indexType); 841 assert(codegen.pidxs[tensor][idx].getType().isa<IndexType>() && 842 "type mismatch for sparse index"); 843 operands.push_back(codegen.pidxs[tensor][idx]); 844 } 845 } 846 if (needsUniv) { 847 types.push_back(indexType); 848 assert(codegen.loops[idx].getType().isa<IndexType>() && 849 "type mismatch for universal index"); 850 operands.push_back(codegen.loops[idx]); 851 } 852 Location loc = op.getLoc(); 853 scf::WhileOp whileOp = rewriter.create<scf::WhileOp>(loc, types, operands); 854 Block *before = rewriter.createBlock(&whileOp.before(), {}, types); 855 Block *after = rewriter.createBlock(&whileOp.after(), {}, types); 856 857 // Build the "before" region, which effectively consists 858 // of a conjunction of "i < upper" tests on all induction. 859 rewriter.setInsertionPointToStart(&whileOp.before().front()); 860 Value cond; 861 unsigned o = 0; 862 for (unsigned b = 0, be = indices.size(); b < be; b++) { 863 if (indices[b] && merger.isDim(b, Dim::kSparse)) { 864 unsigned tensor = merger.tensor(b); 865 assert(idx == merger.index(b)); 866 Value op1 = before->getArgument(o); 867 Value op2 = codegen.highs[tensor][idx]; 868 Value opc = rewriter.create<CmpIOp>(loc, CmpIPredicate::ult, op1, op2); 869 cond = cond ? rewriter.create<AndOp>(loc, cond, opc) : opc; 870 codegen.pidxs[tensor][idx] = after->getArgument(o++); 871 } 872 } 873 if (needsUniv) 874 codegen.loops[idx] = after->getArgument(o++); 875 assert(o == operands.size()); 876 rewriter.create<scf::ConditionOp>(loc, cond, before->getArguments()); 877 rewriter.setInsertionPointToStart(&whileOp.after().front()); 878 return whileOp; 879 } 880 881 /// Generates a for-loop or a while-loop, depending on whether it implements 882 /// singleton iteration or co-iteration over the given conjunction. 883 static Operation *genLoop(Merger &merger, CodeGen &codegen, 884 PatternRewriter &rewriter, linalg::GenericOp op, 885 std::vector<unsigned> &topSort, unsigned at, 886 bool needsUniv, llvm::BitVector &indices) { 887 unsigned idx = topSort[at]; 888 if (indices.count() == 1) { 889 bool isOuter = at == 0; 890 bool isInner = at == topSort.size() - 1; 891 return genFor(merger, codegen, rewriter, op, isOuter, isInner, idx, 892 indices); 893 } 894 genReductionEnd(merger, codegen, rewriter, op); // cannot chain 895 return genWhile(merger, codegen, rewriter, op, idx, needsUniv, indices); 896 } 897 898 /// Generates the local variables for this loop, consisting of the sparse 899 /// indices, restored universal dense index, and dense positions. 900 static void genLocals(Merger &merger, CodeGen &codegen, 901 PatternRewriter &rewriter, linalg::GenericOp op, 902 std::vector<unsigned> &topSort, unsigned at, 903 bool needsUniv, llvm::BitVector &locals) { 904 Location loc = op.getLoc(); 905 unsigned idx = topSort[at]; 906 907 // Initialize sparse indices. 908 Value min; 909 for (unsigned b = 0, be = locals.size(); b < be; b++) { 910 if (locals[b] && merger.isDim(b, Dim::kSparse)) { 911 unsigned tensor = merger.tensor(b); 912 assert(idx == merger.index(b)); 913 Value ptr = codegen.indices[tensor][idx]; 914 Value s = codegen.pidxs[tensor][idx]; 915 Value load = genLoad(codegen, rewriter, loc, ptr, s); 916 codegen.idxs[tensor][idx] = load; 917 if (!needsUniv) { 918 if (min) { 919 Value cmp = 920 rewriter.create<CmpIOp>(loc, CmpIPredicate::ult, load, min); 921 min = rewriter.create<SelectOp>(loc, cmp, load, min); 922 } else { 923 min = load; 924 } 925 } 926 } 927 } 928 929 // Merge dense universal index over minimum. 930 if (min) { 931 assert(!needsUniv); 932 codegen.loops[idx] = min; 933 } 934 935 // Initialize dense positions. Note that we generate dense indices of the 936 // output tensor unconditionally, since they may not appear in the lattice, 937 // but may be needed for linearized codegen. 938 for (unsigned b = 0, be = locals.size(); b < be; b++) { 939 if ((locals[b] || merger.isOutTensor(b, idx)) && 940 merger.isDim(b, Dim::kDense)) { 941 unsigned tensor = merger.tensor(b); 942 assert(idx == merger.index(b)); 943 unsigned pat = at; 944 for (; pat != 0; pat--) 945 if (codegen.pidxs[tensor][topSort[pat - 1]]) 946 break; 947 Value p = (pat == 0) ? rewriter.create<ConstantIndexOp>(loc, 0) 948 : codegen.pidxs[tensor][topSort[pat - 1]]; 949 codegen.pidxs[tensor][idx] = genAddress( 950 codegen, rewriter, loc, codegen.sizes[idx], p, codegen.loops[idx]); 951 } 952 } 953 } 954 955 /// Generates the induction structure for a while-loop. 956 static void genWhileInduction(Merger &merger, CodeGen &codegen, 957 PatternRewriter &rewriter, linalg::GenericOp op, 958 unsigned idx, bool needsUniv, 959 llvm::BitVector &induction, ResultRange results) { 960 Location loc = op.getLoc(); 961 unsigned o = 0; 962 SmallVector<Value, 4> operands; 963 Value one = rewriter.create<ConstantIndexOp>(loc, 1); 964 for (unsigned b = 0, be = induction.size(); b < be; b++) { 965 if (induction[b] && merger.isDim(b, Dim::kSparse)) { 966 unsigned tensor = merger.tensor(b); 967 assert(idx == merger.index(b)); 968 Value op1 = codegen.idxs[tensor][idx]; 969 Value op2 = codegen.loops[idx]; 970 Value op3 = codegen.pidxs[tensor][idx]; 971 Value cmp = rewriter.create<CmpIOp>(loc, CmpIPredicate::eq, op1, op2); 972 Value add = rewriter.create<AddIOp>(loc, op3, one); 973 operands.push_back(rewriter.create<SelectOp>(loc, cmp, add, op3)); 974 codegen.pidxs[tensor][idx] = results[o++]; 975 } 976 } 977 if (needsUniv) { 978 operands.push_back(rewriter.create<AddIOp>(loc, codegen.loops[idx], one)); 979 codegen.loops[idx] = results[o++]; 980 } 981 assert(o == operands.size()); 982 rewriter.create<scf::YieldOp>(loc, operands); 983 } 984 985 /// Generates a single if-statement within a while-loop. 986 static scf::IfOp genIf(Merger &merger, CodeGen &codegen, 987 PatternRewriter &rewriter, linalg::GenericOp op, 988 unsigned idx, llvm::BitVector &conditions) { 989 Location loc = op.getLoc(); 990 Value cond; 991 for (unsigned b = 0, be = conditions.size(); b < be; b++) { 992 if (conditions[b]) { 993 unsigned tensor = merger.tensor(b); 994 assert(idx == merger.index(b)); 995 Value clause; 996 if (merger.isDim(b, Dim::kSparse)) { 997 Value op1 = codegen.idxs[tensor][idx]; 998 Value op2 = codegen.loops[idx]; 999 clause = rewriter.create<CmpIOp>(loc, CmpIPredicate::eq, op1, op2); 1000 } else { 1001 clause = rewriter.create<ConstantIntOp>(loc, 1, 1); // true 1002 } 1003 cond = cond ? rewriter.create<AndOp>(loc, cond, clause) : clause; 1004 } 1005 } 1006 scf::IfOp ifOp = rewriter.create<scf::IfOp>(loc, cond, /*else*/ true); 1007 rewriter.setInsertionPointToStart(&ifOp.thenRegion().front()); 1008 return ifOp; 1009 } 1010 1011 /// Recursively generates code while computing iteration lattices in order 1012 /// to manage the complexity of implementing co-iteration over unions 1013 /// and intersections of sparse iterations spaces. 1014 static void genStmt(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter, 1015 linalg::GenericOp op, std::vector<unsigned> &topSort, 1016 unsigned exp, unsigned at) { 1017 // At each leaf, assign remaining tensor (sub)expression to output tensor. 1018 if (at == topSort.size()) { 1019 OpOperand *lhs = op.getOutputOperand(0); 1020 Value rhs = genExp(merger, codegen, rewriter, op, exp); 1021 genTensorStore(merger, codegen, rewriter, op, lhs, rhs); 1022 return; 1023 } 1024 assert(codegen.curVecLength == 1); 1025 1026 // Construct iteration lattices for current loop index, with L0 at top. 1027 // Then emit initialization code for the loop sequence at this level. 1028 // We maintain the universal dense index if dense indices are still 1029 // in play for a non-singleton loop sequence. 1030 Location loc = op.getLoc(); 1031 unsigned idx = topSort[at]; 1032 unsigned lts = merger.optimizeSet(merger.buildLattices(exp, idx)); 1033 unsigned lsize = merger.set(lts).size(); 1034 assert(lsize != 0); 1035 unsigned l0 = merger.set(lts)[0]; 1036 unsigned ldx = at == 0 ? -1u : topSort[at - 1]; 1037 genInvariants(merger, codegen, rewriter, op, exp, ldx, /*hoist=*/true); 1038 bool needsUniv = false; 1039 if (genInit(merger, codegen, rewriter, op, topSort, at, 1040 merger.lat(l0).bits)) { 1041 // Maintain the universal index only if it is actually 1042 // consumed by a subsequent lattice point. 1043 for (unsigned i = 1; i < lsize; i++) { 1044 unsigned li = merger.set(lts)[i]; 1045 if (!merger.hasAnyDimOf(merger.lat(li).simple, Dim::kSparse)) { 1046 needsUniv = true; 1047 break; 1048 } 1049 } 1050 } 1051 1052 // Emit a loop for every lattice point L0 >= Li. 1053 for (unsigned i = 0; i < lsize; i++) { 1054 unsigned li = merger.set(lts)[i]; 1055 1056 // Emit loop. 1057 codegen.curVecLength = 1; 1058 llvm::BitVector indices = merger.lat(li).simple; 1059 Operation *loop = 1060 genLoop(merger, codegen, rewriter, op, topSort, at, needsUniv, indices); 1061 genLocals(merger, codegen, rewriter, op, topSort, at, needsUniv, 1062 merger.lat(li).bits); 1063 1064 // Visit all lattices points with Li >= Lj to generate the 1065 // loop-body, possibly with if statements for coiteration. 1066 bool isWhile = dyn_cast<scf::WhileOp>(loop) != nullptr; 1067 for (unsigned j = 0; j < lsize; j++) { 1068 unsigned lj = merger.set(lts)[j]; 1069 unsigned ej = merger.lat(lj).exp; 1070 if (li == lj || merger.latGT(li, lj)) { 1071 // Recurse into body of each branch. 1072 if (isWhile) { 1073 scf::IfOp ifOp = 1074 genIf(merger, codegen, rewriter, op, idx, merger.lat(lj).simple); 1075 genStmt(merger, codegen, rewriter, op, topSort, ej, at + 1); 1076 rewriter.setInsertionPointToStart(&ifOp.elseRegion().front()); 1077 } else { 1078 genStmt(merger, codegen, rewriter, op, topSort, ej, at + 1); 1079 } 1080 } 1081 } 1082 1083 // Wrap-up induction and restore insertion point. 1084 if (isWhile) { 1085 scf::WhileOp whileOp = cast<scf::WhileOp>(loop); 1086 rewriter.setInsertionPointToEnd(&whileOp.after().front()); 1087 genWhileInduction(merger, codegen, rewriter, op, idx, needsUniv, 1088 merger.lat(li).bits, whileOp.results()); 1089 } else { 1090 needsUniv = false; 1091 if (codegen.redVal) { 1092 rewriter.create<scf::YieldOp>(loc, codegen.redVal); 1093 codegen.redVal = loop->getResult(0); 1094 } 1095 } 1096 rewriter.setInsertionPointAfter(loop); 1097 } 1098 1099 // Wrap-up loop sequence. 1100 codegen.curVecLength = 1; 1101 genReductionEnd(merger, codegen, rewriter, op); 1102 genInvariants(merger, codegen, rewriter, op, exp, ldx, /*hoist=*/false); 1103 codegen.loops[idx] = Value(); 1104 } 1105 1106 /// Converts the result computed by the sparse kernel into the required form. 1107 static void genResult(Merger &merger, CodeGen &codegen, 1108 PatternRewriter &rewriter, linalg::GenericOp op) { 1109 Location loc = op.getLoc(); 1110 OpOperand *lhs = op.getOutputOperand(0); 1111 Type resType = lhs->get().getType(); 1112 unsigned tensor = lhs->getOperandNumber(); 1113 auto map = op.getTiedIndexingMap(lhs); 1114 auto enc = getSparseTensorEncoding(resType); 1115 Value result = codegen.buffers.back(); // value array 1116 if (enc) { 1117 // The sparse annotation unambigiously defines the arrays needed 1118 // to "reconstruct" the sparse tensor from the storage scheme 1119 // (even though lowering should never need this eventually). 1120 SmallVector<Value, 4> args; 1121 for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) { 1122 unsigned idx = map.getDimPosition(perm(enc, d)); 1123 if (merger.isDim(tensor, idx, Dim::kSparse)) { 1124 args.push_back(codegen.pointers[tensor][idx]); 1125 args.push_back(codegen.indices[tensor][idx]); 1126 } 1127 } 1128 args.push_back(result); 1129 result = rewriter.create<ToTensorOp>(loc, resType, args); 1130 } else { 1131 // To "reconstruct" an non-annotated tensor, sipmly load it 1132 // from the bufferized value. 1133 result = rewriter.create<memref::TensorLoadOp>(loc, resType, result); 1134 } 1135 rewriter.replaceOp(op, result); 1136 } 1137 1138 namespace { 1139 1140 /// Sparse rewriting rule for generic Lingalg operation. 1141 struct GenericOpSparsifier : public OpRewritePattern<linalg::GenericOp> { 1142 public: 1143 GenericOpSparsifier(MLIRContext *context, SparsificationOptions o) 1144 : OpRewritePattern<linalg::GenericOp>(context), options(o) {} 1145 1146 LogicalResult matchAndRewrite(linalg::GenericOp op, 1147 PatternRewriter &rewriter) const override { 1148 // Detects sparse annotations and translate the per-dimension sparsity 1149 // information for all tensors to loop indices in the kernel. 1150 assert(op.getNumOutputs() == 1); 1151 unsigned numTensors = op.getNumInputsAndOutputs(); 1152 unsigned numLoops = op.iterator_types().getValue().size(); 1153 Merger merger(numTensors, numLoops); 1154 if (!findSparseAnnotations(merger, op)) 1155 return failure(); 1156 1157 // Computes a topologically sorted iteration graph to ensure 1158 // tensors are visited in natural index order. Fails on cycles. 1159 // This assumes that higher-level passes have already put the 1160 // tensors in each tensor expression in a feasible order. 1161 std::vector<unsigned> topSort; 1162 if (!computeIterationGraph(merger, op, topSort, /*sparseOnly=*/false) && 1163 !computeIterationGraph(merger, op, topSort, /*sparseOnly=*/true)) 1164 return failure(); 1165 1166 // Builds the tensor expression for the Linalg operation in SSA form. 1167 Optional<unsigned> exp = merger.buildTensorExpFromLinalg(op); 1168 if (!exp.hasValue()) 1169 return failure(); 1170 1171 // Rejects an inadmissable tensor expression. 1172 if (!isAdmissableTensorExp(merger, op, exp.getValue())) 1173 return failure(); 1174 1175 // Recursively generates code. 1176 CodeGen codegen(options, numTensors, numLoops); 1177 if (!genBuffers(merger, codegen, rewriter, op)) 1178 return failure(); // could not bufferize 1179 genStmt(merger, codegen, rewriter, op, topSort, exp.getValue(), 0); 1180 genResult(merger, codegen, rewriter, op); 1181 return success(); 1182 } 1183 1184 private: 1185 /// Options to control sparse code generation. 1186 SparsificationOptions options; 1187 }; 1188 1189 } // namespace 1190 1191 /// Populates the given patterns list with rewriting rules required for 1192 /// the sparsification of linear algebra operations. 1193 void mlir::populateSparsificationPatterns( 1194 RewritePatternSet &patterns, const SparsificationOptions &options) { 1195 patterns.add<GenericOpSparsifier>(patterns.getContext(), options); 1196 } 1197