1 //===- Utils.cpp - Utilities to support the Linalg dialect ----------------===// 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 utilities for the Linalg dialect. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Dialect/Linalg/Utils/Utils.h" 14 15 #include "mlir/Analysis/SliceAnalysis.h" 16 #include "mlir/Dialect/Affine/Analysis/AffineStructures.h" 17 #include "mlir/Dialect/Affine/IR/AffineOps.h" 18 #include "mlir/Dialect/Affine/IR/AffineValueMap.h" 19 #include "mlir/Dialect/Affine/LoopUtils.h" 20 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 21 #include "mlir/Dialect/Arithmetic/Utils/Utils.h" 22 #include "mlir/Dialect/Linalg/IR/Linalg.h" 23 #include "mlir/Dialect/MemRef/IR/MemRef.h" 24 #include "mlir/Dialect/SCF/IR/SCF.h" 25 #include "mlir/Dialect/Tensor/IR/Tensor.h" 26 #include "mlir/Dialect/Tensor/Utils/Utils.h" 27 #include "mlir/Dialect/Utils/StaticValueUtils.h" 28 #include "mlir/IR/AffineExpr.h" 29 #include "mlir/IR/AffineExprVisitor.h" 30 #include "mlir/IR/AffineMap.h" 31 #include "mlir/IR/Matchers.h" 32 #include "mlir/IR/OpImplementation.h" 33 #include "mlir/Pass/Pass.h" 34 #include "llvm/ADT/TypeSwitch.h" 35 #include "llvm/Support/Debug.h" 36 37 #define DEBUG_TYPE "linalg-utils" 38 39 using namespace mlir; 40 using namespace presburger; 41 using namespace mlir::linalg; 42 using namespace mlir::scf; 43 44 static bool isZero(Value v) { 45 if (auto cst = v.getDefiningOp<arith::ConstantIndexOp>()) 46 return cst.value() == 0; 47 return false; 48 } 49 50 namespace { 51 52 // Helper visitor to determine whether an AffineExpr is tiled. 53 // This is achieved by traversing every AffineDimExpr with position `pos` and 54 // checking whether the corresponding `tileSizes[pos]` is non-zero. 55 // This also enforces only positive coefficients occur in multiplications. 56 // 57 // Example: 58 // `d0 + 2 * d1 + d3` is tiled by [0, 0, 0, 2] but not by [0, 0, 2, 0] 59 // 60 struct TileCheck : public AffineExprVisitor<TileCheck> { 61 TileCheck(ValueRange tileSizes) : tileSizes(tileSizes) {} 62 63 void visitDimExpr(AffineDimExpr expr) { 64 isTiled |= !isZero(tileSizes[expr.getPosition()]); 65 } 66 void visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) { 67 visit(expr.getLHS()); 68 visit(expr.getRHS()); 69 if (expr.getKind() == mlir::AffineExprKind::Mul) 70 assert(expr.getRHS().cast<AffineConstantExpr>().getValue() > 0 && 71 "nonpositive multiplying coefficient"); 72 } 73 bool isTiled = false; 74 ValueRange tileSizes; 75 }; 76 77 } // namespace 78 79 static bool isTiled(AffineExpr expr, ValueRange tileSizes) { 80 if (!expr) 81 return false; 82 TileCheck t(tileSizes); 83 t.visit(expr); 84 return t.isTiled; 85 } 86 87 // Checks whether the `map varies with respect to a non-zero `tileSize`. 88 static bool isTiled(AffineMap map, ValueRange tileSizes) { 89 if (!map) 90 return false; 91 for (unsigned r = 0; r < map.getNumResults(); ++r) 92 if (isTiled(map.getResult(r), tileSizes)) 93 return true; 94 return false; 95 } 96 97 Optional<RegionMatcher::BinaryOpKind> 98 RegionMatcher::matchAsScalarBinaryOp(GenericOp op) { 99 auto ®ion = op.region(); 100 if (!llvm::hasSingleElement(region)) 101 return llvm::None; 102 103 Block &block = region.front(); 104 if (block.getNumArguments() != 2 || 105 !block.getArgument(0).getType().isSignlessIntOrFloat() || 106 !block.getArgument(1).getType().isSignlessIntOrFloat()) 107 return llvm::None; 108 109 auto &ops = block.getOperations(); 110 if (!llvm::hasSingleElement(block.without_terminator())) 111 return llvm::None; 112 113 using mlir::matchers::m_Val; 114 auto a = m_Val(block.getArgument(0)); 115 auto b = m_Val(block.getArgument(1)); 116 117 auto addPattern = m_Op<linalg::YieldOp>(m_Op<arith::AddIOp>(a, b)); 118 if (addPattern.match(&ops.back())) 119 return BinaryOpKind::IAdd; 120 121 return llvm::None; 122 } 123 124 /// Explicit instantiation of loop nest generator for different loop types. 125 template struct mlir::linalg::GenerateLoopNest<scf::ForOp>; 126 template struct mlir::linalg::GenerateLoopNest<scf::ParallelOp>; 127 template struct mlir::linalg::GenerateLoopNest<AffineForOp>; 128 129 /// Given a list of subview ranges, extract individual values for lower, upper 130 /// bounds and steps and put them into the corresponding vectors. 131 static void unpackRanges(ArrayRef<Range> ranges, SmallVectorImpl<Value> &lbs, 132 SmallVectorImpl<Value> &ubs, 133 SmallVectorImpl<Value> &steps) { 134 for (Range range : ranges) { 135 lbs.emplace_back(range.offset); 136 ubs.emplace_back(range.size); 137 steps.emplace_back(range.stride); 138 } 139 } 140 141 namespace mlir { 142 namespace linalg { 143 144 bool isPermutation(ArrayRef<int64_t> permutation) { 145 // Count the number of appearances for all indices. 146 SmallVector<int64_t> indexCounts(permutation.size(), 0); 147 for (auto index : permutation) { 148 // Exit if the index is out-of-range. 149 if (index < 0 || index >= static_cast<int64_t>(permutation.size())) 150 return false; 151 indexCounts[index]++; 152 } 153 // Return true if all indices appear once. 154 return count(indexCounts, 1) == static_cast<int64_t>(permutation.size()); 155 } 156 157 /// Helper function that creates a memref::DimOp or tensor::DimOp depending on 158 /// the type of `source`. 159 Value createOrFoldDimOp(OpBuilder &b, Location loc, Value source, int64_t dim) { 160 if (source.getType().isa<UnrankedMemRefType, MemRefType>()) 161 return b.createOrFold<memref::DimOp>(loc, source, dim); 162 if (source.getType().isa<UnrankedTensorType, RankedTensorType>()) 163 return b.createOrFold<tensor::DimOp>(loc, source, dim); 164 llvm_unreachable("Expected MemRefType or TensorType"); 165 } 166 167 /// Given an operation, retrieves the value of each dynamic dimension through 168 /// constructing the necessary DimOp operators. 169 SmallVector<Value, 4> getDynOperands(Location loc, Value val, OpBuilder &b) { 170 SmallVector<Value, 4> dynOperands; 171 auto shapedType = val.getType().cast<ShapedType>(); 172 for (const auto &dim : llvm::enumerate(shapedType.getShape())) { 173 if (dim.value() == ShapedType::kDynamicSize) 174 dynOperands.push_back(createOrFoldDimOp(b, loc, val, dim.index())); 175 } 176 return dynOperands; 177 } 178 179 void getUpperBoundForIndex(Value value, AffineMap &boundMap, 180 SmallVectorImpl<Value> &boundOperands, 181 bool constantRequired) { 182 // Initialize `boundMap` and `boundOperands` to the identity returning 183 // `value`. This combination is the default result of the method if no 184 // simplification is possible. 185 assert(value.getType().isIndex() && "expect value to have index type"); 186 boundMap = AffineMap::getMultiDimIdentityMap(1, value.getContext()); 187 boundOperands.assign({value}); 188 canonicalizeMapAndOperands(&boundMap, &boundOperands); 189 190 // Continue only if there is an affine index computation to simplify. 191 Operation *definingOp = value.getDefiningOp(); 192 if (!definingOp || !isa<AffineApplyOp, AffineMinOp>(definingOp)) 193 return; 194 195 // Get the backward slice containing the affine index computation. 196 SetVector<Operation *> backwardSlice; 197 getBackwardSlice(definingOp, &backwardSlice, [](Operation *op) { 198 return isa<AffineApplyOp, AffineMinOp>(op); 199 }); 200 backwardSlice.insert(definingOp); 201 202 // Setup a system of affine constraints that describe the index computation. 203 FlatAffineValueConstraints constraints; 204 205 // Helper to find or create an identifier for the given value. 206 auto findOrCreateId = [&](Value value) { 207 if (!constraints.containsId(value)) { 208 constraints.appendDimId(value); 209 return true; 210 } 211 unsigned pos; 212 constraints.findId(value, &pos); 213 return pos < constraints.getNumDimIds(); 214 }; 215 // Helper to get the position for the given value. 216 auto getPosition = [&](Value value) { 217 unsigned pos; 218 bool exists = constraints.findId(value, &pos); 219 (void)exists; 220 assert(exists && "expect to find the identifier"); 221 return pos; 222 }; 223 224 // Add the affine operations in `backwardSlice` to the constraints. 225 for (Operation *op : llvm::reverse(backwardSlice)) { 226 // Add an identifier for all op results and operands. 227 if (!(llvm::all_of(op->getResults(), findOrCreateId) && 228 llvm::all_of(op->getOperands(), findOrCreateId))) 229 return; 230 231 // Add AffineApplyOps to the constraints. 232 if (auto applyOp = dyn_cast<AffineApplyOp>(op)) { 233 AffineMap map = constraints.computeAlignedMap(applyOp.getAffineMap(), 234 applyOp.getOperands()); 235 if (failed(constraints.addBound(IntegerPolyhedron::EQ, 236 getPosition(applyOp.getResult()), map))) 237 return; 238 continue; 239 } 240 // Add AffineMinOps to the constraints. 241 auto minOp = cast<AffineMinOp>(op); 242 AffineMap map = constraints.computeAlignedMap(minOp.getAffineMap(), 243 minOp.getOperands()); 244 if (failed(constraints.addBound(IntegerPolyhedron::UB, 245 getPosition(minOp.getResult()), map, 246 /*isClosedBound=*/true))) 247 return; 248 } 249 250 // Obtain an upper bound for the affine index computation by projecting out 251 // all temporary results and expressing the upper bound for `value` in terms 252 // of the terminals of the index computation. 253 unsigned pos = getPosition(value); 254 if (constantRequired) { 255 auto ubConst = constraints.getConstantBound( 256 FlatAffineValueConstraints::BoundType::UB, pos); 257 if (!ubConst) 258 return; 259 260 boundMap = AffineMap::getConstantMap(*ubConst, value.getContext()); 261 return; 262 } 263 264 SmallVector<AffineMap> lowerBounds(1), upperBounds(1); 265 constraints.getSliceBounds(pos, 1, value.getContext(), &lowerBounds, 266 &upperBounds, 267 /*getClosedUB=*/true); 268 // Verify `upperBounds[0]` is valid and has at least one result. 269 if (!upperBounds[0] || upperBounds[0].getNumResults() == 0) 270 return; 271 272 // Set `boundMap` and `boundOperands` to the computed upper bound. 273 boundMap = upperBounds[0]; 274 constraints.getAllValues(&boundOperands); 275 erase_value(boundOperands, value); 276 canonicalizeMapAndOperands(&boundMap, &boundOperands); 277 } 278 279 FailureOr<int64_t> getConstantUpperBoundForIndex(Value value) { 280 // Compute an upper bound for `value`. 281 AffineMap boundMap; 282 SmallVector<Value> boundOperands; 283 getUpperBoundForIndex(value, boundMap, boundOperands, 284 /*constantRequired=*/true); 285 286 // Search the results of `boundMap` for constant upper bounds. 287 SmallVector<int64_t> constantBounds; 288 for (AffineExpr result : boundMap.getResults()) 289 if (auto constExpr = result.dyn_cast<AffineConstantExpr>()) 290 constantBounds.push_back(constExpr.getValue()); 291 292 // Return the minimal upper bound or failure if none is found. 293 if (constantBounds.empty()) 294 return failure(); 295 return *std::min_element(constantBounds.begin(), constantBounds.end()); 296 } 297 298 tensor::ExtractSliceOp makeComposedExtractSliceOp( 299 OpBuilder &b, Location loc, Value source, ArrayRef<OpFoldResult> offsets, 300 ArrayRef<OpFoldResult> sizes, ArrayRef<OpFoldResult> strides) { 301 assert(source && "expect source to be nonzero"); 302 303 // Do not fold if the producer is not an ExtractSliceOp. 304 auto producerOp = source.getDefiningOp<tensor::ExtractSliceOp>(); 305 if (!producerOp) 306 return b.create<tensor::ExtractSliceOp>(loc, source, offsets, sizes, 307 strides); 308 309 // Do not fold if the producer is rank reducing or if there are any non-unit 310 // strides. Supporting non-unit strides complicates the offset computation 311 // since the consumer offsets need to be multiplied by the producer strides. 312 // TODO: support non-unit strides once there are use cases. 313 SmallVector<OpFoldResult> allStrides = producerOp.getMixedStrides(); 314 allStrides.append(strides.begin(), strides.end()); 315 bool hasNonUnitStride = any_of(allStrides, [](OpFoldResult ofr) { 316 return getConstantIntValue(ofr) != static_cast<int64_t>(1); 317 }); 318 if (hasNonUnitStride || 319 producerOp.getSourceType().getRank() != 320 producerOp.getResult().getType().cast<ShapedType>().getRank()) 321 return b.create<tensor::ExtractSliceOp>(loc, source, offsets, sizes, 322 strides); 323 324 // Fold the producer by adding the offests and extracting the slice directly 325 // from the producer source tensor. 326 SmallVector<OpFoldResult> foldedOffsets(offsets.begin(), offsets.end()); 327 AffineExpr dim1, dim2; 328 bindDims(b.getContext(), dim1, dim2); 329 for (const auto &en : enumerate(producerOp.getMixedOffsets())) { 330 SmallVector<Value> offsetValues = { 331 getValueOrCreateConstantIndexOp(b, loc, foldedOffsets[en.index()]), 332 getValueOrCreateConstantIndexOp(b, loc, en.value())}; 333 foldedOffsets[en.index()] = 334 makeComposedAffineApply(b, loc, dim1 + dim2, offsetValues).getResult(); 335 } 336 return b.create<tensor::ExtractSliceOp>(loc, producerOp.source(), 337 foldedOffsets, sizes, strides); 338 } 339 340 Value makeComposedPadHighOp(OpBuilder &b, Location loc, RankedTensorType type, 341 Value source, Value pad, bool nofold) { 342 // Exit if `source` is not defined by an ExtractSliceOp. 343 auto sliceOp = source.getDefiningOp<tensor::ExtractSliceOp>(); 344 if (!sliceOp) 345 return tensor::createPadHighOp(type, source, pad, nofold, loc, b); 346 347 // Search the `source` use-def chain for padded LinalgOps. 348 Value current = sliceOp.source(); 349 while (current) { 350 auto linalgOp = current.getDefiningOp<LinalgOp>(); 351 if (!linalgOp) 352 break; 353 OpResult opResult = current.cast<OpResult>(); 354 current = linalgOp.getOutputOperand(opResult.getResultNumber())->get(); 355 } 356 auto padOp = current ? current.getDefiningOp<tensor::PadOp>() : nullptr; 357 358 // Exit if the search fails to match a tensor::PadOp at the end of the matched 359 // LinalgOp sequence. 360 if (!padOp) 361 return tensor::createPadHighOp(type, source, pad, nofold, loc, b); 362 363 // Exit if the padded result type does not match. 364 if (sliceOp.source().getType() != type) 365 return tensor::createPadHighOp(type, source, pad, nofold, loc, b); 366 367 // Exit if the LinalgOps are not high padded. 368 if (llvm::any_of(padOp.getMixedLowPad(), [](OpFoldResult ofr) { 369 return getConstantIntValue(ofr) != static_cast<int64_t>(0); 370 })) 371 return tensor::createPadHighOp(type, source, pad, nofold, loc, b); 372 373 // Exit if `padOpSliceOp`, which defines the slice used by 374 // `padOp`, is rank-reducing. 375 auto padOpSliceOp = padOp.source().getDefiningOp<tensor::ExtractSliceOp>(); 376 if (!padOpSliceOp || 377 sliceOp.getMixedSizes().size() != padOpSliceOp.getMixedSizes().size()) 378 return tensor::createPadHighOp(type, source, pad, nofold, loc, b); 379 380 // Exit if the sizes of the dynamic sizes of `sliceOp` do not match the size 381 // of the slice padded by `padOp`. 382 if (llvm::any_of( 383 llvm::zip(sliceOp.getMixedSizes(), padOpSliceOp.getMixedSizes()), 384 [](std::tuple<OpFoldResult, OpFoldResult> it) { 385 return !isEqualConstantIntOrValue(std::get<0>(it), std::get<1>(it)); 386 })) 387 return tensor::createPadHighOp(type, source, pad, nofold, loc, b); 388 389 // Exit if the padding values do not match. 390 Attribute padOpPadAttr, padAttr; 391 Value padOpPad = padOp.getConstantPaddingValue(); 392 if (!padOpPad || !matchPattern(padOpPad, m_Constant(&padOpPadAttr)) || 393 !matchPattern(pad, m_Constant(&padAttr)) || padOpPadAttr != padAttr) 394 return tensor::createPadHighOp(type, source, pad, nofold, loc, b); 395 396 // Return the padded result if the padding values and sizes match. 397 return sliceOp.source(); 398 } 399 400 GenericOp makeTransposeOp(OpBuilder &b, Location loc, Value inputTensor, 401 Value outputTensor, 402 ArrayRef<int64_t> transposeVector) { 403 auto resultTensorType = outputTensor.getType().cast<RankedTensorType>(); 404 Type elementType = resultTensorType.getElementType(); 405 406 assert(isPermutation(transposeVector) && 407 "expect transpose vector to be a permutation"); 408 assert(transposeVector.size() == 409 static_cast<size_t>(resultTensorType.getRank()) && 410 "expect transpose vector size to match result tensor rank"); 411 412 // Compute the transpose and the indentity indexing maps. 413 SmallVector<AffineMap> indexingMaps = { 414 inversePermutation(AffineMap::getPermutationMap( 415 SmallVector<unsigned>(transposeVector.begin(), transposeVector.end()), 416 b.getContext())), 417 AffineMap::getMultiDimIdentityMap(transposeVector.size(), 418 b.getContext())}; 419 SmallVector<llvm::StringRef> iteratorTypes(transposeVector.size(), 420 getParallelIteratorTypeName()); 421 422 // Create a GenericOp to transpose `inputTensor` into `outputTensor`. 423 auto transposeOp = b.create<GenericOp>( 424 loc, resultTensorType, inputTensor, outputTensor, 425 b.getAffineMapArrayAttr(indexingMaps), b.getStrArrayAttr(iteratorTypes), 426 /*doc=*/nullptr, 427 /*library_call=*/nullptr); 428 Region &body = transposeOp.getRegion(); 429 body.push_back(new Block()); 430 body.front().addArguments({elementType, elementType}, {loc, loc}); 431 432 // Create the body of the transpose operation. 433 OpBuilder::InsertionGuard g(b); 434 b.setInsertionPointToEnd(&body.front()); 435 b.create<YieldOp>(loc, transposeOp.getRegion().front().getArgument(0)); 436 return transposeOp; 437 } 438 439 GenericOp makeMemRefCopyOp(OpBuilder &b, Location loc, Value from, Value to) { 440 auto memrefTypeTo = to.getType().cast<MemRefType>(); 441 #ifndef NDEBUG 442 auto memrefTypeFrom = from.getType().cast<MemRefType>(); 443 assert(memrefTypeFrom.getRank() == memrefTypeTo.getRank() && 444 "`from` and `to` memref must have the same rank"); 445 #endif // NDEBUG 446 447 AffineMap id = 448 AffineMap::getMultiDimIdentityMap(memrefTypeTo.getRank(), b.getContext()); 449 SmallVector<StringRef> iteratorTypes(memrefTypeTo.getRank(), 450 getParallelIteratorTypeName()); 451 return b.create<linalg::GenericOp>( 452 loc, 453 /*inputs=*/from, 454 /*outputs=*/to, 455 /*indexingMaps=*/llvm::makeArrayRef({id, id}), 456 /*iteratorTypes=*/iteratorTypes, 457 [](OpBuilder &b, Location loc, ValueRange args) { 458 b.create<linalg::YieldOp>(loc, args.front()); 459 }); 460 } 461 462 /// Specialization to build an scf "for" nest. 463 template <> 464 void GenerateLoopNest<scf::ForOp>::doit( 465 OpBuilder &b, Location loc, ArrayRef<Range> loopRanges, LinalgOp linalgOp, 466 ArrayRef<Attribute> iteratorTypes, 467 function_ref<scf::ValueVector(OpBuilder &, Location, ValueRange, 468 ValueRange)> 469 bodyBuilderFn, 470 Optional<LinalgLoopDistributionOptions> distributionOptions, 471 ArrayRef<StringRef> distributionTypes) { 472 SmallVector<Value> iterArgInitValues = linalgOp.getOutputTensorOperands(); 473 // Create procInfo so it dominates loops, if appropriate. 474 SmallVector<ProcInfo, 4> procInfo; 475 SmallVector<DistributionMethod, 0> distributionMethod; 476 if (distributionOptions) { 477 // Collect loop ranges for parallel dimensions. 478 SmallVector<Range, 2> parallelLoopRanges; 479 for (const auto &iteratorType : enumerate(iteratorTypes)) 480 if (isParallelIterator(iteratorType.value())) 481 parallelLoopRanges.push_back(loopRanges[iteratorType.index()]); 482 483 // Get their distribution schemes. 484 distributionMethod = distributionOptions->distributionMethod; 485 if (distributionMethod.size() < parallelLoopRanges.size()) 486 parallelLoopRanges.resize(distributionMethod.size()); 487 procInfo = distributionOptions->procInfo(b, loc, parallelLoopRanges); 488 } 489 490 SmallVector<Value, 4> lbs, ubs, steps; 491 unpackRanges(loopRanges, lbs, ubs, steps); 492 LoopNest loopNest = mlir::scf::buildLoopNest( 493 b, loc, lbs, ubs, steps, iterArgInitValues, 494 [&](OpBuilder &b, Location loc, ValueRange ivs, ValueRange iterArgs) { 495 assert(iterArgs.size() == linalgOp.getOutputTensorOperands().size() && 496 "expect the number of output tensors and iter args to match"); 497 SmallVector<Value> operandValuesToUse = 498 linalgOp.getInputAndOutputOperands(); 499 if (!iterArgs.empty()) { 500 operandValuesToUse = linalgOp.getInputOperands(); 501 operandValuesToUse.append(iterArgs.begin(), iterArgs.end()); 502 } 503 return bodyBuilderFn(b, loc, ivs, operandValuesToUse); 504 }); 505 506 if (!distributionOptions || loopNest.loops.empty()) 507 return; 508 509 // Filter out scf.for loops that were created out of parallel dimensions. 510 SmallVector<scf::ForOp, 4> loops; 511 for (const auto &iteratorType : enumerate(iteratorTypes)) 512 if (isParallelIterator(iteratorType.value())) 513 loops.push_back(loopNest.loops[iteratorType.index()]); 514 515 // Distribute - only supports cyclic distribution for now. 516 for (auto it : llvm::zip(loops, procInfo, distributionMethod)) 517 if (std::get<2>(it) == DistributionMethod::Cyclic) 518 mapLoopToProcessorIds(std::get<0>(it), std::get<1>(it).procId, 519 std::get<1>(it).nprocs); 520 } 521 522 /// Specialization to build affine "for" nest. 523 template <> 524 void GenerateLoopNest<AffineForOp>::doit( 525 OpBuilder &b, Location loc, ArrayRef<Range> loopRanges, LinalgOp linalgOp, 526 ArrayRef<Attribute> iteratorTypes, 527 function_ref<scf::ValueVector(OpBuilder &, Location, ValueRange, 528 ValueRange)> 529 bodyBuilderFn, 530 Optional<LinalgLoopDistributionOptions>, ArrayRef<StringRef>) { 531 SmallVector<Value> iterArgInitValues = linalgOp.getOutputTensorOperands(); 532 assert(iterArgInitValues.empty() && "unexpected AffineForOp init values"); 533 SmallVector<Value, 4> lbs, ubs, steps; 534 unpackRanges(loopRanges, lbs, ubs, steps); 535 536 // Affine loops require constant steps. 537 SmallVector<int64_t, 4> constantSteps; 538 constantSteps.reserve(steps.size()); 539 for (Value v : steps) { 540 auto op = v.getDefiningOp<arith::ConstantIndexOp>(); 541 assert(op && "Affine loops require constant steps"); 542 constantSteps.push_back(op.value()); 543 } 544 545 mlir::buildAffineLoopNest(b, loc, lbs, ubs, constantSteps, 546 [&](OpBuilder &b, Location loc, ValueRange ivs) { 547 SmallVector<Value> operandValuesToUse = 548 linalgOp.getInputAndOutputOperands(); 549 bodyBuilderFn(b, loc, ivs, operandValuesToUse); 550 }); 551 } 552 553 /// Update the `lb`, `ub` and `step` to get per processor `lb`, `ub` and `step`. 554 void updateBoundsForCyclicDistribution(OpBuilder &b, Location loc, Value procId, 555 Value nprocs, Value &lb, Value &ub, 556 Value &step) { 557 AffineExpr d0, d1; 558 bindDims(b.getContext(), d0, d1); 559 AffineExpr s0 = getAffineSymbolExpr(0, b.getContext()); 560 lb = makeComposedAffineApply(b, loc, d0 + d1 * s0, {lb, procId, step}); 561 step = makeComposedAffineApply(b, loc, d0 * s0, {nprocs, step}); 562 } 563 564 /// Generates a loop nest consisting of scf.parallel and scf.for, depending 565 /// on the `iteratorTypes.` Consecutive parallel loops create a single 566 /// scf.parallel operation; each sequential loop creates a new scf.for 567 /// operation. The body of the innermost loop is populated by 568 /// `bodyBuilderFn` that accepts a range of induction variables for all 569 /// loops. `ivStorage` is used to store the partial list of induction 570 /// variables. 571 // TODO: this function can be made iterative instead. However, it 572 // will have at most as many recursive calls as nested loops, which rarely 573 // exceeds 10. 574 static void generateParallelLoopNest( 575 OpBuilder &b, Location loc, ValueRange lbs, ValueRange ubs, 576 ValueRange steps, ArrayRef<Attribute> iteratorTypes, 577 function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn, 578 SmallVectorImpl<Value> &ivStorage, 579 ArrayRef<DistributionMethod> distributionMethod = {}) { 580 assert(lbs.size() == ubs.size()); 581 assert(lbs.size() == steps.size()); 582 assert(lbs.size() == iteratorTypes.size()); 583 584 // If there are no (more) loops to be generated, generate the body and be 585 // done with it. 586 if (iteratorTypes.empty()) { 587 bodyBuilderFn(b, loc, ivStorage); 588 return; 589 } 590 591 // Find the outermost parallel loops and drop their types from the list. 592 unsigned nLoops = iteratorTypes.size(); 593 unsigned nOuterPar = 594 nLoops - iteratorTypes.drop_while(isParallelIterator).size(); 595 596 // If there are no outer parallel loops, generate one sequential loop and 597 // recurse. Note that we wouldn't have dropped anything from `iteratorTypes` 598 // in this case. 599 if (nOuterPar == 0) { 600 LoopNest singleLoop = buildLoopNest( 601 b, loc, lbs.take_front(), ubs.take_front(), steps.take_front(), 602 [&](OpBuilder &b, Location loc, ValueRange ivs) { 603 ivStorage.append(ivs.begin(), ivs.end()); 604 generateParallelLoopNest(b, loc, lbs.drop_front(), ubs.drop_front(), 605 steps.drop_front(), 606 iteratorTypes.drop_front(), bodyBuilderFn, 607 ivStorage, distributionMethod); 608 }); 609 return; 610 } 611 if (distributionMethod.empty()) { 612 // Generate a single parallel loop-nest operation for all outermost 613 // parallel loops and recurse. 614 b.create<scf::ParallelOp>( 615 loc, lbs.take_front(nOuterPar), ubs.take_front(nOuterPar), 616 steps.take_front(nOuterPar), 617 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange localIvs) { 618 ivStorage.append(localIvs.begin(), localIvs.end()); 619 generateParallelLoopNest( 620 nestedBuilder, nestedLoc, lbs.drop_front(nOuterPar), 621 ubs.drop_front(nOuterPar), steps.drop_front(nOuterPar), 622 iteratorTypes.drop_front(nOuterPar), bodyBuilderFn, ivStorage, 623 (distributionMethod.size() < nOuterPar) 624 ? ArrayRef<DistributionMethod>() 625 : distributionMethod.drop_front(nOuterPar)); 626 }); 627 return; 628 } 629 630 // Process all consecutive similarly distributed loops simultaneously. 631 DistributionMethod methodToUse = distributionMethod[0]; 632 unsigned numProcessed = 1; 633 for (unsigned i = 1; i < nOuterPar && i < distributionMethod.size(); ++i) { 634 if (distributionMethod[i] != methodToUse) 635 break; 636 numProcessed++; 637 } 638 639 switch (methodToUse) { 640 case DistributionMethod::Cyclic: { 641 // Generate a single parallel loop-nest operation for all outermost 642 // parallel loops and recurse. 643 b.create<scf::ParallelOp>( 644 loc, lbs.take_front(numProcessed), ubs.take_front(numProcessed), 645 steps.take_front(numProcessed), 646 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange localIvs) { 647 ivStorage.append(localIvs.begin(), localIvs.end()); 648 generateParallelLoopNest( 649 nestedBuilder, nestedLoc, lbs.drop_front(numProcessed), 650 ubs.drop_front(numProcessed), steps.drop_front(numProcessed), 651 iteratorTypes.drop_front(numProcessed), bodyBuilderFn, ivStorage, 652 (distributionMethod.size() < numProcessed) 653 ? ArrayRef<DistributionMethod>() 654 : distributionMethod.drop_front(numProcessed)); 655 }); 656 return; 657 } 658 case DistributionMethod::CyclicNumProcsGeNumIters: { 659 // Check (for the processed loops) that the iteration is in-bounds. 660 ArithBuilder ab(b, loc); 661 Value cond = ab.slt(lbs[0], ubs[0]); 662 for (unsigned i = 1; i < numProcessed; ++i) 663 cond = ab._and(cond, ab.slt(lbs[i], ubs[i])); 664 ivStorage.append(lbs.begin(), std::next(lbs.begin(), numProcessed)); 665 b.create<scf::IfOp>(loc, cond, [&](OpBuilder &b, Location loc) { 666 generateParallelLoopNest( 667 b, loc, lbs.drop_front(numProcessed), ubs.drop_front(numProcessed), 668 steps.drop_front(numProcessed), 669 iteratorTypes.drop_front(numProcessed), bodyBuilderFn, ivStorage, 670 distributionMethod.drop_front(numProcessed)); 671 b.create<scf::YieldOp>(loc, ValueRange{}); 672 }); 673 return; 674 } 675 case DistributionMethod::CyclicNumProcsEqNumIters: 676 // No check/loops needed here. Set the `%iv` to be the `%lb` and proceed 677 // with inner loop generation. 678 ivStorage.append(lbs.begin(), std::next(lbs.begin(), numProcessed)); 679 generateParallelLoopNest( 680 b, loc, lbs.drop_front(numProcessed), ubs.drop_front(numProcessed), 681 steps.drop_front(numProcessed), iteratorTypes.drop_front(numProcessed), 682 bodyBuilderFn, ivStorage, distributionMethod.drop_front(numProcessed)); 683 return; 684 } 685 } 686 687 /// Specialization for generating a mix of parallel and sequential scf loops. 688 template <> 689 void GenerateLoopNest<scf::ParallelOp>::doit( 690 OpBuilder &b, Location loc, ArrayRef<Range> loopRanges, LinalgOp linalgOp, 691 ArrayRef<Attribute> iteratorTypes, 692 function_ref<scf::ValueVector(OpBuilder &, Location, ValueRange, 693 ValueRange)> 694 bodyBuilderFn, 695 Optional<LinalgLoopDistributionOptions> distributionOptions, 696 ArrayRef<StringRef> distributionTypes) { 697 SmallVector<Value> iterArgInitValues = linalgOp.getOutputTensorOperands(); 698 assert(iterArgInitValues.empty() && "unexpected ParallelOp init values"); 699 // This function may be passed more iterator types than ranges. 700 assert(iteratorTypes.size() >= loopRanges.size() && 701 "expected iterator type for all ranges"); 702 iteratorTypes = iteratorTypes.take_front(loopRanges.size()); 703 SmallVector<Value, 8> lbsStorage, ubsStorage, stepsStorage, ivs; 704 unsigned numLoops = iteratorTypes.size(); 705 ivs.reserve(numLoops); 706 lbsStorage.reserve(numLoops); 707 ubsStorage.reserve(numLoops); 708 stepsStorage.reserve(numLoops); 709 710 // Get the loop lb, ub, and step. 711 unpackRanges(loopRanges, lbsStorage, ubsStorage, stepsStorage); 712 713 // Modify the lb, ub, and step based on the distribution options. 714 SmallVector<DistributionMethod, 0> distributionMethod; 715 if (distributionOptions) { 716 auto &options = *distributionOptions; 717 distributionMethod.assign(distributionOptions->distributionMethod.begin(), 718 distributionOptions->distributionMethod.end()); 719 SmallVector<Range, 2> parallelLoopRanges; 720 for (const auto &iteratorType : enumerate(iteratorTypes)) { 721 if (isParallelIterator(iteratorType.value())) 722 parallelLoopRanges.push_back(loopRanges[iteratorType.index()]); 723 } 724 if (distributionMethod.size() < parallelLoopRanges.size()) 725 parallelLoopRanges.resize(distributionMethod.size()); 726 SmallVector<ProcInfo, 2> procInfo = 727 options.procInfo(b, loc, parallelLoopRanges); 728 unsigned index = 0; 729 for (const auto &iteratorType : enumerate(iteratorTypes)) { 730 if (index >= procInfo.size()) 731 break; 732 if (isParallelIterator(iteratorType.value())) { 733 unsigned i = iteratorType.index(); 734 updateBoundsForCyclicDistribution(b, loc, procInfo[index].procId, 735 procInfo[index].nprocs, lbsStorage[i], 736 ubsStorage[i], stepsStorage[i]); 737 index++; 738 } 739 } 740 } 741 ValueRange lbs(lbsStorage), ubs(ubsStorage), steps(stepsStorage); 742 generateParallelLoopNest( 743 b, loc, lbs, ubs, steps, iteratorTypes, 744 [&](OpBuilder &b, Location loc, ValueRange ivs) { 745 SmallVector<Value> operandValuesToUse = 746 linalgOp.getInputAndOutputOperands(); 747 bodyBuilderFn(b, loc, ivs, operandValuesToUse); 748 }, 749 ivs, distributionMethod); 750 751 assert(ivs.size() == iteratorTypes.size() && "did not generate enough loops"); 752 } 753 754 static Value fullyComposeAndAffineApply(OpBuilder &b, Location loc, 755 AffineExpr expr, ValueRange operands) { 756 AffineMap map = AffineMap::inferFromExprList({expr}).front(); 757 SmallVector<Value> normalizedOperands(operands.begin(), operands.end()); 758 mlir::fullyComposeAffineMapAndOperands(&map, &normalizedOperands); 759 canonicalizeMapAndOperands(&map, &normalizedOperands); 760 return b.createOrFold<AffineApplyOp>(loc, map, normalizedOperands); 761 } 762 763 Value makeTiledShape(OpBuilder &builder, Location loc, Value valueToTile, 764 ValueRange tileSizes, AffineMap map, ValueRange lbs, 765 ValueRange ubs, ValueRange subShapeSizes, 766 bool omitPartialTileCheck) { 767 auto shapedType = valueToTile.getType().dyn_cast<ShapedType>(); 768 assert(shapedType && "only shaped types can be tiled"); 769 ArrayRef<int64_t> shape = shapedType.getShape(); 770 int64_t rank = shapedType.getRank(); 771 772 // Construct a new subview / extract_slice for the tile. 773 SmallVector<OpFoldResult, 4> offsets, sizes, strides; 774 offsets.reserve(rank); 775 sizes.reserve(rank); 776 strides.reserve(rank); 777 for (unsigned r = 0; r < rank; ++r) { 778 LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: for dim#" << r); 779 if (!isTiled(map.getSubMap({r}), tileSizes)) { 780 offsets.push_back(builder.getIndexAttr(0)); 781 Value dim = createOrFoldDimOp(builder, loc, valueToTile, r); 782 sizes.push_back(getAsOpFoldResult(dim)); 783 strides.push_back(builder.getIndexAttr(1)); 784 LLVM_DEBUG(llvm::dbgs() << ": not tiled: use size: " << dim << "\n"); 785 continue; 786 } 787 LLVM_DEBUG(llvm::dbgs() << ": tiled: figure out subsize...\n"); 788 789 // Tiling creates a new slice at the proper index, the slice step is 1 790 // (i.e. the op does not subsample, stepping occurs in the loop). 791 auto m = map.getSubMap({r}); 792 LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: submap: " << m << "\n"); 793 auto offset = applyMapToValues(builder, loc, m, lbs).front(); 794 offsets.push_back(getAsOpFoldResult(offset)); 795 auto closedIntSize = 796 applyMapToValues(builder, loc, m, subShapeSizes).front(); 797 // Resulting size needs to be made half open interval again. 798 AffineExpr s0 = getAffineSymbolExpr(0, builder.getContext()); 799 Value size = 800 fullyComposeAndAffineApply(builder, loc, s0 + 1, closedIntSize); 801 LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: raw size: " << size << "\n"); 802 LLVM_DEBUG(llvm::dbgs() 803 << "makeTiledShape: new offset: " << offset << "\n"); 804 strides.push_back(builder.getIndexAttr(1)); 805 806 if (omitPartialTileCheck) { 807 // We statically know that the partial/boundary tile condition is 808 // unnecessary. 809 LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: new size: " << size << "\n"); 810 sizes.push_back(getAsOpFoldResult(size)); 811 continue; 812 } 813 814 // The size of the subview / extract_slice should be trimmed to avoid 815 // out-of-bounds accesses, unless: 816 // a. We statically know the subshape size divides the shape size evenly. 817 // b. The subshape size is 1. According to the way the loops are set up, 818 // tensors with "0" dimensions would never be constructed. 819 int64_t shapeSize = shape[r]; 820 auto sizeCst = size.getDefiningOp<arith::ConstantIndexOp>(); 821 auto hasTileSizeOne = sizeCst && sizeCst.value() == 1; 822 auto dividesEvenly = sizeCst && !ShapedType::isDynamic(shapeSize) && 823 ((shapeSize % sizeCst.value()) == 0); 824 if (!hasTileSizeOne && !dividesEvenly) { 825 LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: shapeSize=" << shapeSize 826 << ", size: " << size 827 << ": make sure in bound with affine.min\n"); 828 829 AffineExpr dim0, dim1, dim2; 830 bindDims(builder.getContext(), dim0, dim1, dim2); 831 832 // Get the dimension size for this dimension. We need to first calculate 833 // the max index and then plus one. This is important because for 834 // convolution ops, we have its input window dimension's affine map of the 835 // form `(d0 * s0 + d1)`, where `d0`/`d1 is an output/filter window 836 // dimension and `s0` is stride. Directly use the dimension size of 837 // output/filer window dimensions will cause incorrect calculation. 838 AffineMap minusOneMap = 839 AffineMap::inferFromExprList({ArrayRef<AffineExpr>{dim0 - 1}}) 840 .front(); 841 AffineMap plusOneMap = 842 AffineMap::inferFromExprList({ArrayRef<AffineExpr>{dim0 + 1}}) 843 .front(); 844 auto maxIndices = llvm::to_vector<8>(llvm::map_range(ubs, [&](Value ub) { 845 return makeComposedAffineApply(builder, loc, minusOneMap, {ub}) 846 .getResult(); 847 })); 848 Value maxIndex = applyMapToValues(builder, loc, m, maxIndices).front(); 849 Value d = makeComposedAffineApply(builder, loc, plusOneMap, {maxIndex}); 850 851 // Compute min(dim - offset, size) to avoid out-of-bounds accesses. 852 AffineMap minMap = AffineMap::inferFromExprList( 853 {ArrayRef<AffineExpr>{dim1 - dim2, dim0}}) 854 .front(); 855 SmallVector<Value, 4> operands{size, d, offset}; 856 fullyComposeAffineMapAndOperands(&minMap, &operands); 857 canonicalizeMapAndOperands(&minMap, &operands); 858 size = builder.create<AffineMinOp>(loc, builder.getIndexType(), minMap, 859 operands); 860 } 861 LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: new size: " << size << "\n"); 862 sizes.push_back(getAsOpFoldResult(size)); 863 } 864 865 auto *sliceOp = TypeSwitch<ShapedType, Operation *>(shapedType) 866 .Case([&](MemRefType) { 867 return builder.create<memref::SubViewOp>( 868 loc, valueToTile, offsets, sizes, strides); 869 }) 870 .Case([&](RankedTensorType) { 871 return makeComposedExtractSliceOp( 872 builder, loc, valueToTile, offsets, sizes, strides); 873 }) 874 .Default([](ShapedType) -> Operation * { 875 llvm_unreachable("Unexpected shaped type"); 876 }); 877 return sliceOp->getResult(0); 878 } 879 880 SmallVector<Value> computeTileOffsets(OpBuilder &b, Location loc, 881 ValueRange ivs, ValueRange tileSizes) { 882 SmallVector<Value> offsets; 883 for (unsigned idx = 0, idxIvs = 0, e = tileSizes.size(); idx < e; ++idx) { 884 LLVM_DEBUG(llvm::dbgs() << "makeTiledShapes: for loop#" << idx << "\n"); 885 bool isTiled = !isZero(tileSizes[idx]); 886 offsets.push_back( 887 isTiled ? ivs[idxIvs++] 888 : b.create<arith::ConstantIndexOp>(loc, 0).getResult()); 889 LLVM_DEBUG(llvm::dbgs() 890 << "computeTileOffsets: " << offsets.back() << "\n"); 891 } 892 return offsets; 893 } 894 895 SmallVector<Value> computeTileSizes(OpBuilder &b, Location loc, 896 ValueRange tileSizes, 897 ArrayRef<Value> sizeBounds) { 898 SmallVector<Value> sizes; 899 for (unsigned idx = 0, e = tileSizes.size(); idx < e; ++idx) { 900 bool isTiled = !isZero(tileSizes[idx]); 901 // Before composing, we need to make range a closed interval. 902 Value size = isTiled ? tileSizes[idx] : sizeBounds[idx]; 903 AffineExpr d0 = getAffineDimExpr(0, b.getContext()); 904 sizes.push_back(fullyComposeAndAffineApply(b, loc, d0 - 1, size)); 905 LLVM_DEBUG(llvm::dbgs() << "computeTileSizes: " << sizes.back() << "\n"); 906 } 907 return sizes; 908 } 909 910 SmallVector<Value, 4> makeTiledShapes(OpBuilder &b, Location loc, 911 LinalgOp linalgOp, 912 ArrayRef<Value> valuesToTile, 913 ValueRange ivs, ValueRange tileSizes, 914 ArrayRef<Value> sizeBounds, 915 bool omitPartialTileCheck) { 916 assert(ivs.size() == static_cast<size_t>(llvm::count_if( 917 llvm::make_range(tileSizes.begin(), tileSizes.end()), 918 [](Value v) { return !isZero(v); })) && 919 "expected as many ivs as non-zero sizes"); 920 921 // Construct (potentially temporary) mins and maxes on which to apply maps 922 // that define tile subshapes. 923 SmallVector<Value> lbs = computeTileOffsets(b, loc, ivs, tileSizes); 924 SmallVector<Value> subShapeSizes = 925 computeTileSizes(b, loc, tileSizes, sizeBounds); 926 927 assert(static_cast<int64_t>(valuesToTile.size()) == 928 linalgOp.getNumInputsAndOutputs() && 929 "expected one value to tile for every operand"); 930 SmallVector<Value, 4> tiledShapes; 931 tiledShapes.reserve(valuesToTile.size()); 932 for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) { 933 Value shapedOp = valuesToTile[opOperand->getOperandNumber()]; 934 LLVM_DEBUG(llvm::dbgs() << "makeTiledShapes: for operand " << shapedOp); 935 AffineMap map = linalgOp.getTiedIndexingMap(opOperand); 936 // Use `opOperand` as is if it is not tiled and not an output tensor. Having 937 // an extract/insert slice pair for all output tensors simplifies follow up 938 // transformations such as padding and bufferization since the 939 // extract/insert slice pairs make the accessed iteration argument 940 // subdomains explicit. 941 if (!isTiled(map, tileSizes) && !linalgOp.isOutputTensor(opOperand)) { 942 tiledShapes.push_back(shapedOp); 943 LLVM_DEBUG(llvm::dbgs() << ": not tiled: use shape: " 944 << opOperand->get().getType() << "\n"); 945 continue; 946 } 947 LLVM_DEBUG(llvm::dbgs() << ": tiled: figure out subshape...\n"); 948 949 tiledShapes.push_back(makeTiledShape(b, loc, shapedOp, tileSizes, map, lbs, 950 sizeBounds, subShapeSizes, 951 omitPartialTileCheck)); 952 } 953 954 return tiledShapes; 955 } 956 957 void addTileLoopIvsToIndexOpResults(OpBuilder &b, LinalgOp tiledOp, 958 ArrayRef<Value> ivs) { 959 if (tiledOp.hasIndexSemantics()) { 960 for (IndexOp indexOp : tiledOp.getBlock()->getOps<IndexOp>()) { 961 if (ivs[indexOp.dim()] == nullptr) 962 continue; 963 OpBuilder::InsertionGuard guard(b); 964 b.setInsertionPointAfter(indexOp); 965 AffineExpr index, offset; 966 bindDims(b.getContext(), index, offset); 967 AffineApplyOp applyOp = makeComposedAffineApply( 968 b, indexOp.getLoc(), index + offset, 969 ValueRange{indexOp.getResult(), ivs[indexOp.dim()]}); 970 indexOp.getResult().replaceAllUsesExcept(applyOp, applyOp); 971 } 972 } 973 } 974 975 } // namespace linalg 976 } // namespace mlir 977