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