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