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