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