1 //===- Loops.cpp - conversion from Linalg named and generic ops to loops --===// 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 #include "PassDetail.h" 10 #include "mlir/Dialect/Affine/EDSC/Intrinsics.h" 11 #include "mlir/Dialect/Linalg/EDSC/FoldedIntrinsics.h" 12 #include "mlir/Dialect/Linalg/IR/LinalgOps.h" 13 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h" 14 #include "mlir/Dialect/Linalg/Passes.h" 15 #include "mlir/Dialect/Linalg/Transforms/Transforms.h" 16 #include "mlir/Dialect/Linalg/Utils/Utils.h" 17 #include "mlir/Dialect/SCF/EDSC/Builders.h" 18 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h" 19 #include "mlir/IR/AffineExpr.h" 20 #include "mlir/IR/AffineMap.h" 21 #include "mlir/IR/BlockAndValueMapping.h" 22 #include "mlir/Support/LLVM.h" 23 #include "mlir/Transforms/DialectConversion.h" 24 #include "mlir/Transforms/FoldUtils.h" 25 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 26 27 #include "llvm/ADT/TypeSwitch.h" 28 29 using namespace mlir; 30 using namespace mlir::edsc; 31 using namespace mlir::edsc::intrinsics; 32 using namespace mlir::linalg; 33 34 using edsc::op::operator+; 35 36 static SmallVector<Value, 8> makeCanonicalAffineApplies(OpBuilder &b, 37 Location loc, 38 AffineMap map, 39 ArrayRef<Value> vals) { 40 if (map.isEmpty()) 41 return {}; 42 43 assert(map.getNumInputs() == vals.size()); 44 SmallVector<Value, 8> res; 45 res.reserve(map.getNumResults()); 46 auto dims = map.getNumDims(); 47 for (auto e : map.getResults()) { 48 auto exprMap = AffineMap::get(dims, map.getNumSymbols(), e); 49 SmallVector<Value, 4> operands(vals.begin(), vals.end()); 50 canonicalizeMapAndOperands(&exprMap, &operands); 51 res.push_back(affine_apply(exprMap, operands)); 52 } 53 return res; 54 } 55 56 static SmallVector<Value, 4> permuteIvs(ArrayRef<Value> ivs, 57 Optional<AffineMap> permutation) { 58 return permutation ? applyMapToValues(ScopedContext::getBuilderRef(), 59 ScopedContext::getLocation(), 60 permutation.getValue(), ivs) 61 : SmallVector<Value, 4>(ivs.begin(), ivs.end()); 62 } 63 64 template <typename IndexedValueType, typename OpType> 65 static void inlineRegionAndEmitStore(OpType op, ArrayRef<Value> indexedValues, 66 ArrayRef<SmallVector<Value, 8>> indexing, 67 ArrayRef<Value> outputBuffers) { 68 assert(op.getOperation()->getNumRegions() == 1 && 69 "Expected single region op"); 70 auto &b = ScopedContext::getBuilderRef(); 71 auto &block = op.getOperation()->getRegion(0).front(); 72 BlockAndValueMapping map; 73 map.map(block.getArguments(), indexedValues); 74 for (auto &op : block.without_terminator()) { 75 assert(op.getNumRegions() == 0 && "expected a non-nested region"); 76 auto *newOp = b.clone(op, map); 77 map.map(op.getResults(), newOp->getResults()); 78 } 79 80 Operation &terminator = block.back(); 81 assert(isa<linalg::YieldOp>(terminator) && 82 "expected a yield op in the end of the region"); 83 for (unsigned i = 0, e = terminator.getNumOperands(); i < e; ++i) { 84 IndexedValueType O(outputBuffers[i]); 85 O(indexing[i]) = map.lookupOrDefault(terminator.getOperand(i)); 86 } 87 } 88 89 // Returns a pair that contains input indices and output indices of a 90 // SingleInputPoolingOp `op`. 91 struct InputAndOutputIndices { 92 SmallVector<Value, 8> inputs; 93 SmallVector<Value, 8> outputs; 94 }; 95 template <typename SingleInputPoolingOp> 96 static InputAndOutputIndices getInputAndOutputIndices(ArrayRef<Value> allIvs, 97 SingleInputPoolingOp op) { 98 auto &b = ScopedContext::getBuilderRef(); 99 auto loc = ScopedContext::getLocation(); 100 auto mapsRange = op.indexing_maps().template getAsRange<AffineMapAttr>(); 101 auto maps = llvm::to_vector<8>( 102 llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); })); 103 return InputAndOutputIndices{ 104 makeCanonicalAffineApplies(b, loc, maps[0], allIvs), 105 makeCanonicalAffineApplies(b, loc, maps[2], allIvs)}; 106 } 107 108 /// Emits the MLIR for the scalar part of the generic op by: 109 /// 1. Emitting load ops for each input and output view in order. This is 110 /// achieved by applying the appropriate input or output map to the 111 /// enclosing induction variables. 112 /// 2. Emitting a call to `op.fun()` that takes as arguments the scalars 113 /// from point 1. above. 114 /// 3. Emitting store ops to store the results of 2. to the output 115 /// views. 116 /// 117 /// An example output may resemble: 118 /// 119 /// ``` 120 /// scf.for %i = %c0 to %0 step %c1 { 121 /// scf.for %j = %c0 to %1 step %c1 { 122 /// scf.for %k = %c0 to %4 step %c1 { 123 /// %11 = load %arg0[%i, %j] : 124 /// memref<?x?xf32, stride_specification> 125 /// %12 = load %arg1[%i, %j, %k] : 126 /// memref<?x?x?xf32, stride_specification> 127 /// %13 = load %arg2[%i, %k, %j] : 128 /// memref<?x?x?xf32, stride_specification> 129 /// %14:2 = call @foo(%11, %12, %13) : (f32, f32, f32) -> (f32, f32) 130 /// store %14#0, %arg1[%i, %j, %k] : 131 /// memref<?x?x?Xf32, stride_specification> 132 /// store %14#1, %arg2[%i, %k, %j] : 133 /// memref<?x?x?Xf32, stride_specification> 134 /// } 135 /// } 136 /// } 137 /// ``` 138 template <typename IndexedValueType> 139 static void emitScalarImplementation(ArrayRef<Value> allIvs, 140 LinalgOp linalgOp) { 141 assert(linalgOp.hasBufferSemantics() && 142 "expected linalg op with buffer semantics"); 143 auto &b = ScopedContext::getBuilderRef(); 144 auto loc = ScopedContext::getLocation(); 145 unsigned nInputs = linalgOp.getNumInputs(); 146 unsigned nOutputs = linalgOp.getNumOutputs(); 147 SmallVector<Value, 4> indexedValues; 148 indexedValues.reserve(nInputs + nOutputs); 149 150 auto allIvsPlusDims = SmallVector<Value, 4>(allIvs.begin(), allIvs.end()); 151 152 // TODO: Avoid the loads if the corresponding argument of the 153 // region has no uses. 154 // 1.a. Emit load from input views. 155 for (unsigned i = 0; i < nInputs; ++i) { 156 auto indexing = makeCanonicalAffineApplies( 157 b, loc, linalgOp.getInputIndexingMap(i), allIvsPlusDims); 158 // Passing through IndexedValueType emits the proper load operation. 159 indexedValues.push_back(IndexedValueType(linalgOp.getInput(i))(indexing)); 160 } 161 // 1.b. Emit load from output views. 162 for (unsigned i = 0; i < nOutputs; ++i) { 163 auto indexing = makeCanonicalAffineApplies( 164 b, loc, linalgOp.getOutputIndexingMap(i), allIvsPlusDims); 165 // Passing through IndexedValueType emits the proper load operation. 166 indexedValues.push_back( 167 IndexedValueType(linalgOp.getOutputBuffer(i))(indexing)); 168 } 169 170 // TODO: When a region inliner exists, use it. 171 // 2. Inline region, currently only works for a single basic block. 172 // 3. Emit store. 173 SmallVector<SmallVector<Value, 8>, 8> indexing; 174 SmallVector<Value, 8> outputBuffers; 175 for (unsigned i = 0; i < nOutputs; ++i) { 176 indexing.push_back(makeCanonicalAffineApplies( 177 b, loc, linalgOp.getOutputIndexingMap(i), allIvsPlusDims)); 178 outputBuffers.push_back(linalgOp.getOutputBuffer(i)); 179 } 180 inlineRegionAndEmitStore<IndexedValueType>(linalgOp, indexedValues, indexing, 181 outputBuffers); 182 } 183 184 template <typename IndexedValueType> 185 static void emitScalarImplementation(ArrayRef<Value> allIvs, CopyOp copyOp) { 186 assert(copyOp.hasBufferSemantics() && 187 "expected linalg op with buffer semantics"); 188 auto nPar = copyOp.getNumParallelLoops(); 189 assert(nPar == allIvs.size()); 190 auto inputIvs = 191 permuteIvs(allIvs.take_front(nPar), copyOp.inputPermutation()); 192 auto outputIvs = 193 permuteIvs(allIvs.take_front(nPar), copyOp.outputPermutation()); 194 SmallVector<Value, 8> iivs(inputIvs.begin(), inputIvs.end()); 195 SmallVector<Value, 8> oivs(outputIvs.begin(), outputIvs.end()); 196 IndexedValueType O(copyOp.getOutputBuffer(0)), I(copyOp.getInput(0)); 197 // Emit the proper scalar assignment, whether we are dealing with a 0-D or 198 // an n-D loop nest; with or without permutations. 199 // clang-format off 200 nPar > 0 ? O(oivs) = I(iivs) : 201 O() = I(); 202 // clang-format on 203 } 204 205 template <typename IndexedValueType> 206 static void emitScalarImplementation(ArrayRef<Value> allIvs, FillOp fillOp) { 207 assert(fillOp.hasBufferSemantics() && 208 "expected linalg op with buffer semantics"); 209 auto nPar = fillOp.getNumParallelLoops(); 210 assert(nPar == allIvs.size()); 211 auto ivs = SmallVector<Value, 4>(allIvs.begin(), allIvs.begin() + nPar); 212 IndexedValueType O(fillOp.getOutputBuffer(0)); 213 // Emit the proper scalar assignment, whether we are dealing with a 0-D or 214 // an n-D loop nest; with or without permutations. 215 nPar > 0 ? O(ivs) = fillOp.value() : O() = fillOp.value(); 216 } 217 218 // Create a padded view into the given `input` tensor using the 'indices' 219 // to access the tensor. `skipPadding` lists the dimensions for which no padding 220 // is needed e.g. the non-spatial dimensions for convolutions. 221 template <typename IndexedValueType> 222 Value getPaddedInput(Value input, ArrayRef<Value> indices, 223 ArrayRef<int> skipPadding, Value padValue) { 224 // TODO: add a level of indirection to linalg.generic. 225 226 IndexedValueType indexedInput(input); 227 228 auto *context = ScopedContext::getContext(); 229 Value zeroIndex = std_constant_index(0); 230 SmallVector<Value, 8> conds; 231 SmallVector<Value, 8> clampedImIdx; 232 for (auto iter : llvm::enumerate(indices)) { 233 int idx = iter.index(); 234 auto dim = iter.value(); 235 if (is_contained(skipPadding, idx)) { 236 clampedImIdx.push_back(dim); 237 continue; 238 } 239 240 using edsc::op::sge; 241 using edsc::op::slt; 242 using edsc::op::operator||; 243 Value leftOutOfBound = slt(dim, zeroIndex); 244 if (conds.empty()) 245 conds.push_back(leftOutOfBound); 246 else 247 conds.push_back(conds.back() || leftOutOfBound); 248 Value rightBound = std_dim(input, idx); 249 conds.push_back(conds.back() || (sge(dim, rightBound))); 250 251 // When padding is involved, the indices will only be shifted to negative, 252 // so having a max op is enough. 253 auto maxMap = AffineMap::get(/*dimCount=*/1, 0, 254 {getAffineDimExpr(/*position=*/0, context), 255 getAffineConstantExpr(0, context)}, 256 context); 257 clampedImIdx.push_back(affine_max(dim.getType(), maxMap, ValueRange{dim})); 258 } 259 260 Value readInput = indexedInput(clampedImIdx); 261 return conds.empty() ? readInput 262 : (Value)std_select(conds.back(), padValue, readInput); 263 } 264 265 namespace { 266 267 /// The padding value for a given Op depends on the semantics of the Op. 268 /// The identity value for ConvOp and PoolingSumOp is 0, for PoolingMaxOp is 269 /// -inf or minInt and for PoolingMinOp is inf or maxInt. 270 template <typename OpType> 271 Attribute getPadValueAttr(Type type) { 272 llvm_unreachable("Unexpected op type for getPadValueAttr"); 273 return {}; 274 } 275 276 template <> 277 Attribute getPadValueAttr<PoolingMaxOp>(Type type) { 278 auto &b = ScopedContext::getBuilderRef(); 279 if (auto floatType = type.dyn_cast<FloatType>()) { 280 return b.getFloatAttr( 281 floatType, 282 APFloat::getInf(floatType.getFloatSemantics(), /*Negative*/ true)); 283 } 284 if (auto intType = type.dyn_cast<IntegerType>()) { 285 unsigned width = intType.getWidth(); 286 // The select instruction used to lower the PoolingMin uses a signed 287 // comparison, use a signed constant irrespective of the signedness of the 288 // integer type. 289 return b.getIntegerAttr(intType, APInt::getSignedMinValue(width)); 290 } 291 llvm_unreachable("Unsupported data type for PoolingMaxOp"); 292 return {}; 293 } 294 295 template <> 296 Attribute getPadValueAttr<PoolingMinOp>(Type type) { 297 auto &b = ScopedContext::getBuilderRef(); 298 if (auto floatType = type.dyn_cast<FloatType>()) { 299 return b.getFloatAttr(floatType, 300 APFloat::getInf(floatType.getFloatSemantics())); 301 } 302 if (auto intType = type.dyn_cast<IntegerType>()) { 303 unsigned width = intType.getWidth(); 304 // The select instruction used to lower the PoolingMin uses a signed 305 // comparison, use a signed constant irrespective of the signedness of the 306 // integer type. 307 return b.getIntegerAttr(intType, APInt::getSignedMaxValue(width)); 308 } 309 llvm_unreachable("Unsupported data type for PoolingMinOp"); 310 return {}; 311 } 312 313 template <> 314 Attribute getPadValueAttr<PoolingSumOp>(Type type) { 315 auto &b = ScopedContext::getBuilderRef(); 316 return b.getZeroAttr(type); 317 } 318 319 template <> 320 Attribute getPadValueAttr<ConvOp>(Type type) { 321 auto &b = ScopedContext::getBuilderRef(); 322 return b.getZeroAttr(type); 323 } 324 325 } // namespace 326 327 /// Returns true is `convOp` has a non-zero padding. 328 static bool hasPadding(ConvOp convOp) { 329 for (unsigned i = 0, e = convOp.getNumSpatialDimensions(); i < e; ++i) { 330 if (convOp.getLowPad(i) > 0 || convOp.getHighPad(i) > 0) 331 return true; 332 } 333 return false; 334 } 335 336 template <typename IndexedValueType> 337 static void emitScalarImplementation(ArrayRef<Value> allIvs, ConvOp convOp) { 338 assert(convOp.hasBufferSemantics() && 339 "expected linalg op with buffer semantics"); 340 auto &b = ScopedContext::getBuilderRef(); 341 auto loc = ScopedContext::getLocation(); 342 auto mapsRange = convOp.indexing_maps().getAsRange<AffineMapAttr>(); 343 auto maps = llvm::to_vector<8>( 344 llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); })); 345 SmallVector<Value, 8> fIdx( 346 makeCanonicalAffineApplies(b, loc, maps[0], allIvs)); 347 SmallVector<Value, 8> imIdx( 348 makeCanonicalAffineApplies(b, loc, maps[1], allIvs)); 349 SmallVector<Value, 8> oIdx( 350 makeCanonicalAffineApplies(b, loc, maps[2], allIvs)); 351 352 IndexedValueType F(convOp.filter()), O(convOp.output()); 353 354 // Emit scalar form. Padded conv involves an affine.max in the memory access 355 // which is not allowed by affine.load. Override to use an StdIndexedValue 356 // when there is non-zero padding. 357 if (hasPadding(convOp)) { 358 Type type = convOp.input().getType().cast<MemRefType>().getElementType(); 359 Value padValue = std_constant(type, getPadValueAttr<ConvOp>(type)); 360 Value paddedInput = getPaddedInput<StdIndexedValue>( 361 convOp.input(), imIdx, 362 /* Only need to pad the window dimensions */ 363 {0, static_cast<int>(imIdx.size()) - 1}, padValue); 364 O(oIdx) += F(fIdx) * paddedInput; 365 } else { 366 IndexedValueType I(convOp.input()); 367 O(oIdx) += F(fIdx) * I(imIdx); 368 } 369 } 370 371 template <typename PoolingOp> 372 static bool hasPadding(PoolingOp poolingOp) { 373 for (unsigned i = 0, e = poolingOp.getNumWindowLoops(); i < e; ++i) { 374 if (poolingOp.getLowPad(i) > 0 || poolingOp.getHighPad(i) > 0) 375 return true; 376 } 377 return false; 378 } 379 380 template <typename IndexedValueType, typename PoolingOp> 381 static Value getPoolingInput(PoolingOp op, ArrayRef<Value> inputIndices) { 382 if (hasPadding(op)) { 383 Type type = 384 op.input().getType().template cast<MemRefType>().getElementType(); 385 Value padValue = std_constant(type, getPadValueAttr<PoolingOp>(type)); 386 return getPaddedInput<StdIndexedValue>(op.input(), inputIndices, 387 /*Pad every dimension*/ {}, 388 padValue); 389 } 390 IndexedValueType input(op.input()); 391 return input(inputIndices); 392 } 393 394 template <typename IndexedValueType, typename OpType> 395 void emitPoolingMinMaxScalarImplementation(ArrayRef<Value> allIvs, OpType op) { 396 InputAndOutputIndices indices = getInputAndOutputIndices(allIvs, op); 397 // Emit scalar form. 398 IndexedValueType output(op.output()); 399 Value lhs = output(indices.outputs); 400 Value rhs = getPoolingInput<IndexedValueType>(op, indices.inputs); 401 using edsc::op::sgt; 402 using edsc::op::slt; 403 Value value = std::is_same<OpType, PoolingMinOp>() 404 ? std_select(slt(lhs, rhs), lhs, rhs) 405 : std_select(sgt(lhs, rhs), lhs, rhs); 406 output(indices.outputs) = value; 407 } 408 409 template <typename IndexedValueType> 410 static void emitScalarImplementation(ArrayRef<Value> allIvs, PoolingMaxOp op) { 411 emitPoolingMinMaxScalarImplementation<IndexedValueType, PoolingMaxOp>(allIvs, 412 op); 413 } 414 415 template <typename IndexedValueType> 416 static void emitScalarImplementation(ArrayRef<Value> allIvs, PoolingMinOp op) { 417 emitPoolingMinMaxScalarImplementation<IndexedValueType, PoolingMinOp>(allIvs, 418 op); 419 } 420 421 template <typename IndexedValueType> 422 static void emitScalarImplementation(ArrayRef<Value> allIvs, PoolingSumOp op) { 423 auto indices = getInputAndOutputIndices(allIvs, op); 424 IndexedValueType output(op.output()); 425 426 // Emit scalar form. 427 output(indices.outputs) += 428 getPoolingInput<IndexedValueType>(op, indices.inputs); 429 } 430 431 /// Emits the MLIR for the scalar part of the indexed generic op by: 432 /// 1. Emitting load ops for each input and output view in order. This is 433 /// achieved by applying the appropriate input or output map to the 434 /// enclosing induction variables. 435 /// 2. Emitting a call to `op.fun()` that takes as arguments the induction 436 /// variables and the scalars from point 1. above. 437 /// 3. Emitting store ops to store the results of 2. to the output views. 438 /// 439 /// An example output may resemble: 440 /// 441 /// ``` 442 /// scf.for %i = %c0 to %0 step %c1 { 443 /// scf.for %j = %c0 to %1 step %c1 { 444 /// scf.for %k = %c0 to %4 step %c1 { 445 /// %11 = load %arg0[%i, %j] : 446 /// memref<?x?xf32, stride_specification> 447 /// %12 = load %arg1[%i, %j, %k] : 448 /// memref<?x?x?xf32, stride_specification> 449 /// %13 = load %arg2[%i, %k, %j] : 450 /// memref<?x?x?xf32, stride_specification> 451 /// %14:2 = call @foo(%i, %j, %k, %11, %12, %13) : 452 /// (index, index, index, f32, f32, f32) -> (f32, f32) 453 /// store %14#0, %arg1[%i, %j, %k] : 454 /// memref<?x?x?Xf32, stride_specification> 455 /// store %14#1, %arg2[%i, %k, %j] : 456 /// memref<?x?x?Xf32, stride_specification> 457 /// } 458 /// } 459 /// } 460 /// ``` 461 template <typename IndexedValueType> 462 static void emitScalarImplementation(ArrayRef<Value> allIvs, 463 IndexedGenericOp indexedGenericOp) { 464 assert(indexedGenericOp.hasBufferSemantics() && 465 "expected linalg op with buffer semantics"); 466 auto &b = ScopedContext::getBuilderRef(); 467 auto loc = ScopedContext::getLocation(); 468 unsigned nInputs = indexedGenericOp.getNumInputs(); 469 unsigned nOutputs = indexedGenericOp.getNumOutputs(); 470 unsigned nLoops = allIvs.size(); 471 SmallVector<Value, 4> indexedValues; 472 indexedValues.reserve(nLoops + nInputs + nOutputs); 473 for (unsigned i = 0; i < nLoops; ++i) 474 indexedValues.push_back(allIvs[i]); 475 476 // TODO: Avoid the loads if the corresponding argument of the 477 // region has no uses. 478 // 1.a. Emit load from input views. 479 for (unsigned i = 0; i < nInputs; ++i) { 480 auto indexing = makeCanonicalAffineApplies( 481 b, loc, indexedGenericOp.getInputIndexingMap(i), allIvs); 482 // Pass input i through IndexedValueType emits the proper load operation. 483 indexedValues.push_back( 484 IndexedValueType(indexedGenericOp.getInput(i))(indexing)); 485 } 486 // 1.b. Emit load from output views. 487 for (unsigned i = 0; i < nOutputs; ++i) { 488 auto indexing = makeCanonicalAffineApplies( 489 b, loc, indexedGenericOp.getOutputIndexingMap(i), allIvs); 490 // Pass output i through IndexedValueType emits the proper load operation. 491 indexedValues.push_back( 492 IndexedValueType(indexedGenericOp.getOutputBuffer(i))(indexing)); 493 } 494 495 // TODO: When a region inliner exists, use it. 496 // 2. Inline region, currently only works for a single basic block. 497 // 3. Emit store. 498 SmallVector<SmallVector<Value, 8>, 8> indexing; 499 SmallVector<Value, 8> outputBuffers; 500 for (unsigned i = 0; i < nOutputs; ++i) { 501 indexing.push_back(makeCanonicalAffineApplies( 502 b, loc, indexedGenericOp.getOutputIndexingMap(i), allIvs)); 503 outputBuffers.push_back(indexedGenericOp.getOutputBuffer(i)); 504 } 505 inlineRegionAndEmitStore<IndexedValueType>(indexedGenericOp, indexedValues, 506 indexing, outputBuffers); 507 } 508 509 template <typename LoopTy> 510 static Optional<LinalgLoops> linalgOpToLoopsImpl(Operation *op, 511 OpBuilder &builder) { 512 using IndexedValueTy = typename GenerateLoopNest<LoopTy>::IndexedValueTy; 513 514 ScopedContext scope(builder, op->getLoc()); 515 516 // The flattened loopToOperandRangesMaps is expected to be an invertible 517 // permutation map (which is asserted in the inverse calculation). 518 auto linalgOp = cast<LinalgOp>(op); 519 assert(linalgOp.hasBufferSemantics() && 520 "expected linalg op with buffer semantics"); 521 auto loopRanges = linalgOp.createLoopRanges(builder, op->getLoc()); 522 SmallVector<Value, 4> allIvs; 523 GenerateLoopNest<LoopTy>::doit( 524 loopRanges, /*iterInitArgs*/ {}, linalgOp.iterator_types().getValue(), 525 [&](ValueRange ivs, ValueRange iterArgs) -> scf::ValueVector { 526 assert(iterArgs.empty() && "unexpected iterArgs"); 527 allIvs.append(ivs.begin(), ivs.end()); 528 llvm::TypeSwitch<Operation *>(op) 529 .Case<CopyOp, FillOp, ConvOp, PoolingMaxOp, PoolingMinOp, 530 PoolingSumOp, IndexedGenericOp, LinalgOp>([&](auto op) { 531 emitScalarImplementation<IndexedValueTy>(allIvs, op); 532 }) 533 .Default([&](Operation *op) { assert(false && "unexpected op"); }); 534 return scf::ValueVector{}; 535 }); 536 // Number of loop ops might be different from the number of ivs since some 537 // loops like affine.parallel and scf.parallel have multiple ivs. 538 llvm::SetVector<Operation *> loopSet; 539 for (Value iv : allIvs) { 540 if (!iv) 541 return {}; 542 // The induction variable is a block argument of the entry block of the 543 // loop operation. 544 BlockArgument ivVal = iv.dyn_cast<BlockArgument>(); 545 if (!ivVal) 546 return {}; 547 loopSet.insert(ivVal.getOwner()->getParentOp()); 548 } 549 LinalgLoops loops(loopSet.begin(), loopSet.end()); 550 return loops; 551 } 552 553 namespace { 554 template <typename LoopType> 555 class LinalgRewritePattern : public RewritePattern { 556 public: 557 LinalgRewritePattern() : RewritePattern(/*benefit=*/1, MatchAnyOpTypeTag()) {} 558 559 LogicalResult matchAndRewrite(Operation *op, 560 PatternRewriter &rewriter) const override { 561 if (!isa<LinalgOp>(op)) 562 return failure(); 563 if (!linalgOpToLoopsImpl<LoopType>(op, rewriter)) 564 return failure(); 565 rewriter.eraseOp(op); 566 return success(); 567 } 568 }; 569 570 struct FoldAffineOp; 571 } // namespace 572 573 template <typename LoopType> 574 static void lowerLinalgToLoopsImpl(FuncOp funcOp, MLIRContext *context) { 575 OwningRewritePatternList patterns; 576 patterns.insert<LinalgRewritePattern<LoopType>>(); 577 DimOp::getCanonicalizationPatterns(patterns, context); 578 AffineApplyOp::getCanonicalizationPatterns(patterns, context); 579 patterns.insert<FoldAffineOp>(context); 580 // Just apply the patterns greedily. 581 applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); 582 } 583 584 namespace { 585 /// Local folding pattern for AffineApplyOp that we can apply greedily. 586 /// This replaces AffineApplyOp by the proper value in cases where the 587 /// associated map is trivial. 588 /// A trivial map here is defined as a map with a single result and either: 589 /// 1. Zero operand + returns a single AffineConstantExpr 590 /// 2. One operand + returns a single AffineDimExpr 591 /// 3. One operand + returns a single AffineSymbolExpr 592 // 593 /// In the first case, the AffineApplyOp is replaced by a new constant. In the 594 /// other cases, it is replaced by its unique operand. 595 struct FoldAffineOp : public RewritePattern { 596 FoldAffineOp(MLIRContext *context) 597 : RewritePattern(AffineApplyOp::getOperationName(), 0, context) {} 598 599 LogicalResult matchAndRewrite(Operation *op, 600 PatternRewriter &rewriter) const override { 601 AffineApplyOp affineApplyOp = cast<AffineApplyOp>(op); 602 auto map = affineApplyOp.getAffineMap(); 603 if (map.getNumResults() != 1 || map.getNumInputs() > 1) 604 return failure(); 605 606 AffineExpr expr = map.getResult(0); 607 if (map.getNumInputs() == 0) { 608 if (auto val = expr.dyn_cast<AffineConstantExpr>()) { 609 rewriter.replaceOpWithNewOp<ConstantIndexOp>(op, val.getValue()); 610 return success(); 611 } 612 return failure(); 613 } 614 if (expr.dyn_cast<AffineDimExpr>() || expr.dyn_cast<AffineSymbolExpr>()) { 615 rewriter.replaceOp(op, op->getOperand(0)); 616 return success(); 617 } 618 return failure(); 619 } 620 }; 621 622 struct LowerToAffineLoops 623 : public LinalgLowerToAffineLoopsBase<LowerToAffineLoops> { 624 void runOnFunction() override { 625 lowerLinalgToLoopsImpl<AffineForOp>(getFunction(), &getContext()); 626 } 627 }; 628 629 struct LowerToLoops : public LinalgLowerToLoopsBase<LowerToLoops> { 630 void runOnFunction() override { 631 lowerLinalgToLoopsImpl<scf::ForOp>(getFunction(), &getContext()); 632 } 633 }; 634 635 struct LowerToParallelLoops 636 : public LinalgLowerToParallelLoopsBase<LowerToParallelLoops> { 637 void runOnFunction() override { 638 lowerLinalgToLoopsImpl<scf::ParallelOp>(getFunction(), &getContext()); 639 } 640 }; 641 } // namespace 642 643 std::unique_ptr<OperationPass<FuncOp>> mlir::createConvertLinalgToLoopsPass() { 644 return std::make_unique<LowerToLoops>(); 645 } 646 647 std::unique_ptr<OperationPass<FuncOp>> 648 mlir::createConvertLinalgToParallelLoopsPass() { 649 return std::make_unique<LowerToParallelLoops>(); 650 } 651 652 std::unique_ptr<OperationPass<FuncOp>> 653 mlir::createConvertLinalgToAffineLoopsPass() { 654 return std::make_unique<LowerToAffineLoops>(); 655 } 656 657 /// Emits a loop nest with the proper body for `op`. 658 template <typename LoopTy> 659 Optional<LinalgLoops> mlir::linalg::linalgLowerOpToLoops(OpBuilder &builder, 660 Operation *op) { 661 return linalgOpToLoopsImpl<LoopTy>(op, builder); 662 } 663 664 template Optional<LinalgLoops> 665 mlir::linalg::linalgLowerOpToLoops<AffineForOp>(OpBuilder &builder, 666 Operation *op); 667 template Optional<LinalgLoops> 668 mlir::linalg::linalgLowerOpToLoops<scf::ForOp>(OpBuilder &builder, 669 Operation *op); 670 template Optional<LinalgLoops> 671 mlir::linalg::linalgLowerOpToLoops<scf::ParallelOp>(OpBuilder &builder, 672 Operation *op); 673 674 /// Emits a loop nest of `affine.for` with the proper body for `op`. 675 LogicalResult mlir::linalg::linalgOpToAffineLoops(OpBuilder &builder, 676 Operation *op) { 677 Optional<LinalgLoops> loops = linalgLowerOpToLoops<AffineForOp>(builder, op); 678 return loops ? success() : failure(); 679 } 680 681 /// Emits a loop nest of `scf.for` with the proper body for `op`. 682 LogicalResult mlir::linalg::linalgOpToLoops(OpBuilder &builder, Operation *op) { 683 Optional<LinalgLoops> loops = linalgLowerOpToLoops<scf::ForOp>(builder, op); 684 return loops ? success() : failure(); 685 } 686 687 /// Emits a loop nest of `scf.parallel` with the proper body for `op`. 688 LogicalResult mlir::linalg::linalgOpToParallelLoops(OpBuilder &builder, 689 Operation *op) { 690 Optional<LinalgLoops> loops = 691 linalgLowerOpToLoops<scf::ParallelOp>(builder, op); 692 return loops ? success() : failure(); 693 } 694