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