1 //===- Fusion.cpp - Implementation of linalg Fusion -----------------------===// 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 the linalg dialect Fusion pass. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PassDetail.h" 14 #include "mlir/Dialect/Affine/IR/AffineOps.h" 15 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h" 16 #include "mlir/Dialect/Linalg/IR/LinalgOps.h" 17 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h" 18 #include "mlir/Dialect/Linalg/Passes.h" 19 #include "mlir/Dialect/Linalg/Transforms/Transforms.h" 20 #include "mlir/Dialect/Linalg/Utils/Utils.h" 21 #include "mlir/Dialect/MemRef/EDSC/Intrinsics.h" 22 #include "mlir/Dialect/MemRef/IR/MemRef.h" 23 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h" 24 #include "mlir/Dialect/Tensor/IR/Tensor.h" 25 #include "mlir/IR/AffineExpr.h" 26 #include "mlir/IR/AffineMap.h" 27 #include "mlir/IR/Dominance.h" 28 #include "mlir/Support/LLVM.h" 29 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 30 #include "mlir/Transforms/RegionUtils.h" 31 #include "llvm/ADT/MapVector.h" 32 #include "llvm/ADT/ScopeExit.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 36 #include <set> 37 38 #define DEBUG_TYPE "linalg-fusion" 39 40 using namespace mlir; 41 using namespace mlir::edsc; 42 using namespace mlir::edsc::intrinsics; 43 using namespace mlir::linalg; 44 45 using llvm::dbgs; 46 47 /// Implements a simple high-level fusion pass on linalg structured operations. 48 /// 49 /// In each block, linalg ops are processed in reverse textual order. 50 /// Given a linalg op `O`, fusion occurs by: 51 /// 1. inspecting the linalg ops that write into the views read by `O`. There 52 /// are 2 cases: 53 /// a) buffer case: use the SSA value of the views and a simple alias 54 /// analysis on subview ops to determine producer-consumer dependences; 55 /// b) tensor case: use SSA use-def chains on subtensor ops; 56 /// 2. greedily fuse the linalg ops that produce the subview/subtensor. 57 /// 3. inspect the fused ops and determine whether they have other remaining 58 /// LinalgOp uses. If not, then erase the original producing linalg op. 59 /// 60 /// More advanced use cases, analyses as well as profitability heuristics are 61 /// left for future work. 62 63 struct ShapeDimension { 64 Value shape; 65 unsigned dimension; 66 }; 67 68 // Given an `op`, returns the first (`shape`, `dimension`) pair that identifies 69 // the loop range at `loopDepth`. The semantics of the loopToOperandRangesMaps 70 // guarantees at least one such dimension is found. If multiple candidates exist 71 // they must agree by construction (i.e. have the same size) and we just return 72 // the first one. 73 static ShapeDimension 74 getShapeDefiningLoopRange(LinalgOp op, unsigned loopDepth, 75 bool fromSubViewOpOnly = false) { 76 auto maps = op.indexing_maps(); 77 // Iterate over the inputs and outputs in order. 78 // Extract the subranges from the linearized ranges. 79 for (auto en : llvm::enumerate(op.getShapedOperands())) { 80 // The method `getRangeFromOperandShape` requires using SubViewOp or 81 // SubTensorOps. If the value isnt defined from there continue. 82 // todo: The method should be adapted to get the values from 83 // `ViewInterface`. The interface needs a `getOrCreateRanges` method which 84 // currently returns a `linalg.range`. The fix here is to move this op to 85 // `std` dialect and add the method to `ViewInterface`. 86 if (fromSubViewOpOnly && !isa_and_nonnull<memref::SubViewOp, SubTensorOp>( 87 en.value().getDefiningOp())) 88 continue; 89 90 unsigned idx = en.index(); 91 auto map = maps[idx].cast<AffineMapAttr>().getValue(); 92 LLVM_DEBUG(llvm::dbgs() 93 << "getShapeDefiningLoopRange I/O idx: " << idx << "\n"); 94 LLVM_DEBUG(llvm::dbgs() 95 << "getShapeDefiningLoopRange map: " << map << "\n"); 96 Value shape = en.value(); 97 SmallVector<Value, 8> shapeRanges(map.getNumResults(), nullptr); 98 for (auto en2 : llvm::enumerate(map.getResults())) { 99 auto dimExpr = en2.value().dyn_cast<AffineDimExpr>(); 100 if (!dimExpr) 101 continue; 102 if (loopDepth == en2.value().cast<AffineDimExpr>().getPosition()) { 103 LLVM_DEBUG(llvm::dbgs() << "getShapeDefiningLoopRange loopDepth: " 104 << loopDepth << "\n"); 105 LLVM_DEBUG(llvm::dbgs() 106 << "getShapeDefiningLoopRange shape: " << shape << "\n"); 107 return ShapeDimension{shape, static_cast<unsigned>(en2.index())}; 108 } 109 } 110 } 111 llvm_unreachable("Expect to be able to extract a shape defining loop range"); 112 } 113 114 /// Fuses the producer by cloning the `producer`. The `fusedLoopsAndRanges` 115 /// provides the loop range information for the fused loops. The rest are 116 /// obtained from the producer itself, since they are not tiled + fused. 117 static LinalgOp fuse(OpBuilder &builder, LinalgOp producer, 118 const DenseMap<unsigned, Range> &fusedLoopsAndRanges) { 119 SmallVector<Value, 8> ivs, tileSizes, sizeBounds; 120 SmallVector<Range, 8> loopRanges; 121 auto zero = std_constant_index(0); 122 auto one = std_constant_index(1); 123 Location loc = producer.getLoc(); 124 125 for (unsigned i = 0, e = producer.getNumLoops(); i < e; ++i) { 126 auto it = fusedLoopsAndRanges.find(i); 127 if (it != fusedLoopsAndRanges.end()) { 128 ivs.push_back(it->second.offset); 129 tileSizes.push_back(it->second.size); 130 sizeBounds.push_back(nullptr); 131 loopRanges.push_back(it->second); 132 LLVM_DEBUG(llvm::dbgs() << "tiled loop#" << i << " with LoopRange " 133 << loopRanges.back() << "\n"); 134 } else { 135 auto shapeDim = getShapeDefiningLoopRange(producer, i); 136 Value dim = memref_dim(shapeDim.shape, shapeDim.dimension); 137 tileSizes.push_back(zero); 138 sizeBounds.push_back(dim); 139 loopRanges.push_back(Range{zero, dim, one}); 140 LLVM_DEBUG(llvm::dbgs() << "full loop#" << i << " with LoopRange " 141 << loopRanges.back() << "\n"); 142 } 143 } 144 145 SmallVector<Value, 8> clonedShapes; 146 clonedShapes.reserve(producer.getNumShapedOperands()); 147 148 // Compute subranges for all tensor input/output operands. 149 auto tiledOperands = llvm::to_vector<4>(producer.getShapedOperands()); 150 clonedShapes.append(makeTiledShapes(builder, loc, producer, tiledOperands, 151 ivs, tileSizes, sizeBounds)); 152 153 // Append the other operands. 154 auto operands = producer.getAssumedNonShapedOperands(); 155 clonedShapes.append(operands.begin(), operands.end()); 156 157 // Iterate over the results in order. 158 // Extract the subtensor type from the linearized range. 159 // Since we do not enforce any canonicalizations on the fly, this is always 160 // fully dynamic at construction time. 161 SmallVector<Type, 4> resultTypes; 162 resultTypes.reserve(producer->getNumResults()); 163 for (RankedTensorType t : producer.getOutputTensorTypes()) { 164 unsigned rank = t.getRank(); 165 SmallVector<int64_t, 4> staticOffsetsVector( 166 rank, ShapedType::kDynamicStrideOrOffset); 167 SmallVector<int64_t, 4> staticSizesVector(rank, ShapedType::kDynamicSize); 168 SmallVector<int64_t, 4> staticStridesVector( 169 rank, ShapedType::kDynamicStrideOrOffset); 170 resultTypes.push_back(SubTensorOp::inferResultType( 171 t.cast<RankedTensorType>(), staticOffsetsVector, staticSizesVector, 172 staticStridesVector)); 173 } 174 175 Operation *clonedOp = producer.clone(builder, loc, resultTypes, clonedShapes); 176 // When the producer is an IndexedGenericOp, we have to transform its block 177 // IV arguments according to the tiling of the consumer, i.e. offset them by 178 // the values computed in `loopRanges`. 179 if (auto indexedGenericOp = dyn_cast<IndexedGenericOp>(clonedOp)) { 180 auto &block = indexedGenericOp.region().front(); 181 OpBuilder::InsertionGuard g(builder); 182 builder.setInsertionPointToStart(&block); 183 for (unsigned i = 0, e = indexedGenericOp.getNumLoops(); i < e; ++i) { 184 Value oldIndex = block.getArgument(i); 185 // TODO: replace by an affine_apply. 186 AddIOp newIndex = builder.create<AddIOp>(indexedGenericOp.getLoc(), 187 oldIndex, loopRanges[i].offset); 188 oldIndex.replaceAllUsesExcept(newIndex, 189 SmallPtrSet<Operation *, 1>{newIndex}); 190 } 191 } 192 // When the producer has index semantics, we have to transform the indices of 193 // the producer according to the tiling of the consumer, i.e. offset them by 194 // the values computed in `loopRanges`. 195 if (producer.hasIndexSemantics()) { 196 assert(clonedOp->getNumRegions() == 1 && 197 clonedOp->getRegion(0).getBlocks().size() == 1 && 198 "expected producer to have one block."); 199 // Shift all indices by the tile offset. 200 Block &block = clonedOp->getRegion(0).front(); 201 for (IndexOp indexOp : block.getOps<IndexOp>()) { 202 OpBuilder::InsertionGuard g(builder); 203 builder.setInsertionPointAfter(indexOp); 204 AffineExpr index, offset; 205 bindDims(builder.getContext(), index, offset); 206 AffineApplyOp applyOp = builder.create<AffineApplyOp>( 207 indexOp.getLoc(), index + offset, 208 ValueRange{indexOp.getResult(), loopRanges[indexOp.dim()].offset}); 209 indexOp.getResult().replaceAllUsesExcept( 210 applyOp, SmallPtrSet<Operation *, 1>{applyOp}); 211 } 212 } 213 214 return clonedOp; 215 } 216 217 /// Get the loop range for a dimension `dim` based on the `shapedOperand`. It is 218 /// expected to be defined by a subview op or a subtensor op. 219 static Range getRangeFromOperandShape(OpBuilder &b, Location loc, 220 Value shapedOperand, unsigned dim) { 221 Operation *shapeProducingOp = shapedOperand.getDefiningOp(); 222 if (auto subViewOp = dyn_cast<memref::SubViewOp>(shapeProducingOp)) 223 return subViewOp.getOrCreateRanges(b, loc)[dim]; 224 if (auto subTensorOp = dyn_cast<SubTensorOp>(shapeProducingOp)) 225 return subTensorOp.getOrCreateRanges(b, loc)[dim]; 226 llvm_unreachable("SubviewOp or SubTensorOp expected"); 227 } 228 229 /// Fuses the producer of `producerIdx` into the loop immediately enclosing 230 /// `consumer`. This is achieved by "recomputing" the `producer` at the time it 231 /// is needed just before the `consumer. 232 /// 233 /// Depending on the type of `consumer.getShapedOperand(consumerIdx)`, there are 234 /// 2 cases: 235 /// 1. Buffer case: `producerIdx` is the index of the buffer in 236 /// `producer.getOutputBuffers()`. 237 /// 2. Tensor case: `producerIdx` is the index of the tensor in 238 /// `producer.getResults()`. 239 static LinalgOp fuse(OpBuilder &b, LinalgOp producerOp, AffineMap producerMap, 240 OpOperand &consumerOpOperand) { 241 LLVM_DEBUG(llvm::dbgs() << "Producer map: " << producerMap << "\n"); 242 DenseMap<unsigned, Range> fusedLoopsAndRanges; 243 Value shapedOperand = consumerOpOperand.get(); 244 for (auto en : llvm::enumerate(producerMap.getResults())) { 245 unsigned posInProducerLoop = en.value().cast<AffineDimExpr>().getPosition(); 246 fusedLoopsAndRanges[posInProducerLoop] = getRangeFromOperandShape( 247 b, consumerOpOperand.getOwner()->getLoc(), shapedOperand, en.index()); 248 } 249 return fuse(b, producerOp, fusedLoopsAndRanges); 250 } 251 252 // Encode structural fusion safety preconditions. 253 // Some of these will be lifted in the future with better analysis. 254 static bool isStructurallyFusableProducer(LinalgOp producer, Value consumedView, 255 LinalgOp consumer) { 256 assert(producer.hasBufferSemantics() && 257 "expected linalg op with buffer semantics"); 258 assert(consumer.hasBufferSemantics() && 259 "expected linalg op with buffer semantics"); 260 if (producer.getNumOutputs() != 1) { 261 LLVM_DEBUG(llvm::dbgs() << "\nNot structurally fusable (multi-output)"); 262 return false; 263 } 264 // Only fuse when the producer block dominates. 265 DominanceInfo dom(producer.getOperation()); 266 if (!dom.dominates(producer->getBlock(), consumer->getBlock())) { 267 LLVM_DEBUG( 268 llvm::dbgs() 269 << "\nNot structurally fusable (producer block does not dominate)"); 270 return false; 271 } 272 return true; 273 } 274 275 bool mlir::linalg::isProducerLastWriteOfView(const LinalgDependenceGraph &graph, 276 LinalgOp consumer, 277 Value consumedView, 278 LinalgOp producer) { 279 assert(producer.hasBufferSemantics() && 280 "expected linalg op with buffer semantics"); 281 assert(consumer.hasBufferSemantics() && 282 "expected linalg op with buffer semantics"); 283 // Make some simple structural checks that alleviate the need for more 284 // complex analyses. 285 if (!isStructurallyFusableProducer(producer, consumedView, consumer)) { 286 LLVM_DEBUG(llvm::dbgs() << "\n***Not static last write due to structure:\t" 287 << *producer.getOperation()); 288 return false; 289 } 290 // Check for any interleaved write to consumedView. 291 if (!graph.findCoveringWrites(producer, consumer, consumedView).empty()) { 292 LLVM_DEBUG(llvm::dbgs() << "\n***Not fusable due to interleaved write:\t" 293 << *producer.getOperation()); 294 return false; 295 } 296 return true; 297 } 298 299 bool mlir::linalg::isFusableInto(const LinalgDependenceGraph &graph, 300 LinalgOp consumer, Value consumedView, 301 LinalgOp producer) { 302 assert(producer.hasBufferSemantics() && 303 "expected linalg op with buffer semantics"); 304 assert(consumer.hasBufferSemantics() && 305 "expected linalg op with buffer semantics"); 306 if (!isProducerLastWriteOfView(graph, consumer, consumedView, producer)) 307 return false; 308 // Check for any fusion-preventing dependence to any shape read/written that 309 // would violate dependences. 310 if (!graph.findCoveringDependences(producer, consumer).empty()) { 311 LLVM_DEBUG(llvm::dbgs() 312 << "\n***Not fusable due to an interleaved dependence:\t" 313 << *producer.getOperation()); 314 return false; 315 } 316 if (auto convOp = dyn_cast<linalg::ConvOp>(producer.getOperation())) { 317 // TODO: add a level of indirection to linalg.generic. 318 if (convOp.padding()) 319 return false; 320 } 321 if (auto convOp = dyn_cast<linalg::ConvOp>(consumer.getOperation())) { 322 // TODO: add a level of indirection to linalg.generic. 323 if (convOp.padding()) 324 return false; 325 } 326 return true; 327 } 328 329 /// For `consumer` with buffer semantics, find the Linalg operation on buffers 330 /// that is the last writer of `consumerOpOperand`. For now the fusable 331 /// dependence is returned as an instance of the `dependenceGraph`. 332 static Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> 333 findFusableProducer(OpOperand &consumerOpOperand, 334 const LinalgDependenceGraph &dependenceGraph) { 335 LLVM_DEBUG(llvm::dbgs() << "findFusableProducer for: " 336 << consumerOpOperand.get() << " @" 337 << consumerOpOperand.getOperandNumber() << " in " 338 << *consumerOpOperand.getOwner() << "\n"); 339 LinalgOp consumerOp = dyn_cast<LinalgOp>(consumerOpOperand.getOwner()); 340 if (!consumerOp) 341 return {}; 342 343 // Only consider RAW and WAW atm. 344 for (auto depType : { 345 LinalgDependenceGraph::DependenceType::RAW, 346 LinalgDependenceGraph::DependenceType::WAW, 347 }) { 348 LLVM_DEBUG(llvm::dbgs() 349 << "Dependencies into: " << *consumerOp.getOperation() << "\n"); 350 for (auto dependence : llvm::make_filter_range( 351 dependenceGraph.getDependencesInto(consumerOp, depType), 352 [&](LinalgDependenceGraph::LinalgDependenceGraphElem elem) { 353 LLVM_DEBUG(llvm::dbgs() << "Inspect dependence btw: " 354 << elem.getIndexingValue() << " and " 355 << elem.getDependentValue() << "\n"); 356 Value v = elem.getIndexingValue(); 357 Optional<unsigned> operandNum = 358 elem.getIndexingOpViewOperandNum(); 359 return isa<LinalgOp>(elem.getDependentOp()) && 360 v == consumerOpOperand.get() && operandNum && 361 operandNum.getValue() == 362 consumerOpOperand.getOperandNumber(); 363 })) { 364 // Consumer consumes this view, `isStructurallyFusableProducer` also 365 // checks whether it is a strict subview of the producer view. 366 auto producer = cast<LinalgOp>(dependence.getDependentOp()); 367 LLVM_DEBUG(llvm::dbgs() 368 << "\n" 369 << LinalgDependenceGraph::getDependenceTypeStr(depType) 370 << "producer: " << *dependence.getDependentOp() 371 << " view: " << dependence.getDependentValue() << "\n"); 372 373 // If the producer and consumer have tensor semantics, the only dependence 374 // between them is through a RAW dependence and they are fusable by 375 // construction. For buffer semantics need additional checks. 376 if (producer.hasBufferSemantics() && consumerOp.hasBufferSemantics() && 377 isFusableInto(dependenceGraph, consumerOp, consumerOpOperand.get(), 378 producer)) 379 return dependence; 380 if (producer.hasTensorSemantics() && consumerOp.hasTensorSemantics()) { 381 assert(dependence.dependenceType == 382 LinalgDependenceGraph::DependenceType::RAW); 383 return dependence; 384 } 385 } 386 } 387 return {}; 388 } 389 390 Optional<FusionInfo> 391 mlir::linalg::fuseProducerOfBuffer(OpBuilder &b, OpOperand &consumerOpOperand, 392 const LinalgDependenceGraph &graph) { 393 Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> fusableDependence = 394 findFusableProducer(consumerOpOperand, graph); 395 if (!fusableDependence) 396 return llvm::None; 397 398 LinalgOp producerOp = dyn_cast<LinalgOp>(fusableDependence->getDependentOp()); 399 if (!producerOp) 400 return llvm::None; 401 402 // If producer is already in the same block as consumer, we are done. 403 if (consumerOpOperand.get().getParentBlock() == 404 fusableDependence->getDependentValue().getParentBlock()) 405 return llvm::None; 406 407 Optional<AffineMap> producerMap = 408 fusableDependence->getDependentOpViewIndexingMap(); 409 if (!producerMap) 410 return llvm::None; 411 412 // Must be a subview or a slice to guarantee there are loops we can fuse 413 // into. 414 auto subView = consumerOpOperand.get().getDefiningOp<memref::SubViewOp>(); 415 if (!subView) { 416 LLVM_DEBUG(llvm::dbgs() << "\nNot fusable (not a subview)"); 417 return llvm::None; 418 } 419 420 // Fuse `producer` just before `consumer`. 421 OpBuilder::InsertionGuard g(b); 422 b.setInsertionPoint(consumerOpOperand.getOwner()); 423 ScopedContext scope(b, consumerOpOperand.getOwner()->getLoc()); 424 LLVM_DEBUG(llvm::dbgs() << "Fuse into consumer: " 425 << *consumerOpOperand.getOwner() << "\n"); 426 427 auto fusedProducer = fuse(b, producerOp, *producerMap, consumerOpOperand); 428 return FusionInfo{producerOp, fusedProducer}; 429 } 430 431 /// Walk back use-def chain through scf::For yields. 432 /// Sets `producer` and `outputIndex` if it finds a producer LinalgOp 433 434 // TODO(ravishankarm, ntv): This can be moved into the dependence graphs 435 // dependence tracking since the dependence tracking is similar to what is done 436 // w.r.t to buffers. 437 static void getProducerOfTensor(Value tensor, OpResult &opResult) { 438 if (!tensor.getType().isa<RankedTensorType>()) 439 return; 440 441 while (true) { 442 LLVM_DEBUG(llvm::dbgs() << "\ngetProducerOfTensor: " << tensor); 443 if (auto linalgOp = tensor.getDefiningOp<LinalgOp>()) { 444 opResult = tensor.cast<OpResult>(); 445 return; 446 } 447 if (auto subTensorOp = tensor.getDefiningOp<SubTensorOp>()) { 448 tensor = subTensorOp.source(); 449 continue; 450 } 451 if (auto blockArg = tensor.dyn_cast<BlockArgument>()) { 452 if (auto forOp = blockArg.getDefiningOp<scf::ForOp>()) { 453 tensor = *(forOp.getIterOperands().begin() + blockArg.getArgNumber()); 454 continue; 455 } 456 } 457 return; 458 } 459 } 460 461 Optional<FusionInfo> 462 mlir::linalg::fuseProducerOfTensor(OpBuilder &b, OpOperand &consumerOpOperand) { 463 Value inputTensor = consumerOpOperand.get(); 464 OpResult producerOpResult; 465 getProducerOfTensor(inputTensor, producerOpResult); 466 if (!producerOpResult) { 467 LLVM_DEBUG(llvm::dbgs() << "\nUnable to find producer"); 468 return {}; 469 } 470 return fuseProducerOfTensor(b, producerOpResult, consumerOpOperand); 471 } 472 473 Optional<FusionInfo> 474 mlir::linalg::fuseProducerOfTensor(OpBuilder &b, OpResult producerOpResult, 475 OpOperand &consumerOpOperand) { 476 auto producerOp = dyn_cast<LinalgOp>(producerOpResult.getOwner()); 477 if (!producerOp) 478 return llvm::None; 479 480 LinalgOp consumerOp = dyn_cast<LinalgOp>(consumerOpOperand.getOwner()); 481 if (!consumerOp) 482 return llvm::None; 483 484 Value inputTensor = consumerOpOperand.get(); 485 486 // Must be a subtensor to guarantee there are loops we can fuse into. 487 auto subTensor = inputTensor.getDefiningOp<SubTensorOp>(); 488 if (!subTensor) { 489 LLVM_DEBUG(llvm::dbgs() 490 << "\nNot fusable, not a subtensor: " << inputTensor); 491 return {}; 492 } 493 494 // If producer is already in the same block as consumer, we are done. 495 if (consumerOpOperand.get().getParentBlock() == 496 producerOpResult.getParentBlock()) 497 return {}; 498 499 // Insert fused `producer` just before `consumer`. 500 OpBuilder::InsertionGuard g(b); 501 b.setInsertionPoint(consumerOp); 502 ScopedContext scope(b, consumerOp->getLoc()); 503 LLVM_DEBUG(llvm::dbgs() << "Fuse into consumer: " << *consumerOp << "\n"); 504 LinalgOp fusedProducer = 505 fuse(b, producerOp, 506 producerOp.getOutputIndexingMap(producerOpResult.getResultNumber()), 507 consumerOpOperand); 508 509 // Replace use. 510 // Canonicalizations are not guaranteed to have happened before constructing 511 // `fusedProducer`. In the tensor case this can result in temporary type 512 // mismatches. Insert a `tensor.cast` op to propagate the transformation 513 // invariant that types are compatible. 514 Value def = fusedProducer->getResult(producerOpResult.getResultNumber()); 515 Type consumerType = consumerOpOperand.get().getType(); 516 if (consumerType != def.getType()) 517 def = b.create<tensor::CastOp>(fusedProducer.getLoc(), consumerType, def); 518 consumerOpOperand.set(def); 519 return FusionInfo{cast<LinalgOp>(producerOpResult.getOwner()), fusedProducer}; 520 } 521 522 /// Prune all dimensions that are of reduction iterator type from `map`. 523 static AffineMap pruneReductionDimsFromMap(ArrayRef<Attribute> iteratorTypes, 524 AffineMap map) { 525 llvm::SmallDenseSet<unsigned> projectedDims; 526 for (auto attr : llvm::enumerate(iteratorTypes)) { 527 if (!isParallelIterator(attr.value())) 528 projectedDims.insert(attr.index()); 529 } 530 return getProjectedMap(map, projectedDims); 531 } 532 533 /// Returns the mapping from iterations in the consumer that write to the same 534 /// location as the iterations in the producer. To do so use 535 /// - indexing map of the fused view in the consumer : consumerIndexMap 536 /// - indexing map of the fused view in the producer : producerIndexMap 537 /// consumerLoopToProducerLoop = 538 /// inverse(producerIndexMap).compose(consumerIndexMap) 539 static Optional<AffineMap> getConsumerLoopToProducerLoopMap( 540 LinalgDependenceGraph::LinalgDependenceGraphElem dependence) { 541 auto producer = dyn_cast<LinalgOp>(dependence.getDependentOp()); 542 if (!producer) 543 return None; 544 545 Optional<AffineMap> producerIndexingMap = 546 dependence.getDependentOpViewIndexingMap(); 547 Optional<AffineMap> consumerIndexingMap = 548 dependence.getIndexingOpViewIndexingMap(); 549 if (!producerIndexingMap || !consumerIndexingMap) 550 return None; 551 552 AffineMap prunedProducerIndexingMap = pruneReductionDimsFromMap( 553 producer.iterator_types().getValue(), *producerIndexingMap); 554 if (!prunedProducerIndexingMap.isPermutation()) 555 return None; 556 557 if (consumerIndexingMap->getNumResults() != 558 prunedProducerIndexingMap.getNumResults()) 559 return None; 560 561 LLVM_DEBUG({ 562 llvm::dbgs() << "\t producerMap : "; 563 producerIndexingMap->print(llvm::dbgs()); 564 llvm::dbgs() << " pruned : "; 565 prunedProducerIndexingMap.print(llvm::dbgs()); 566 llvm::dbgs() << "\n"; 567 llvm::dbgs() << "\t consumerMap : "; 568 consumerIndexingMap->print(llvm::dbgs()); 569 llvm::dbgs() << "\n"; 570 }); 571 572 AffineMap invProducerIndexMap = inversePermutation(prunedProducerIndexingMap); 573 if (!invProducerIndexMap) 574 return None; 575 576 return invProducerIndexMap.compose(*consumerIndexingMap); 577 } 578 579 /// Given a projected permutation `map`, returns true if the map changes the 580 /// order in which the fused loop dimension appear. 581 static bool doesTransposeAccess(AffineMap map, 582 const std::set<unsigned> &fusableLoops) { 583 Optional<unsigned> lastFusableLoop; 584 for (unsigned pos : llvm::map_range(map.getResults(), [](AffineExpr expr) { 585 return expr.cast<AffineDimExpr>().getPosition(); 586 })) { 587 if (!fusableLoops.count(pos)) 588 continue; 589 if (!lastFusableLoop) { 590 lastFusableLoop = pos; 591 continue; 592 } 593 if (pos <= lastFusableLoop.getValue()) 594 return true; 595 lastFusableLoop = pos; 596 } 597 return false; 598 } 599 600 /// Returns the positions of the loop in `op` that can be tiled based on the 601 /// operations that are to be fused with it. For example, in a 602 /// 603 /// linalg.matmul ins(%a, %b : ...) outs(%c : ...) 604 /// 605 /// if the producer of %a needs to be fused with this op, only the `i` loop of 606 /// the matmul can be tiled while fusing. If producer of %a, and %b are to be 607 /// fused, then no loops can be tiled while fusing. The conditions used are: 608 /// 1. Only parallel loops can be used for tile + fuse. Find the number of 609 /// common outer parallel loops between the op and its producers being fused. 610 /// 2. Of the parallel loops only some can be fused. Only those loops can be 611 /// fused such where the fusable loops iteration space only touches one tile 612 /// of the fused operation. This is because the producer (which is writing 613 /// the fused subview) has update semantics. 614 /// 615 /// Since an inverse computation is needed, we need to consider the projection 616 /// of the producerIndexMap w.r.t the parallel loops. The actual fusable loops 617 /// are the dimensions of the consumerLoopToProducerLoop map that correspond to 618 /// parallel loops and appear in the result of the map 619 /// 620 /// Example 1: 621 /// linalg.fill(%c, %cst) 622 /// linalg.matmul ins(%a, %b) outs(%c) 623 /// Number of parallel loops : 2 624 /// producerIndexMap = affine_map<(i, j) ->(i , j)> 625 /// consumerIndexMap = affine_map<(i, j, k) -> (i, j)> 626 /// consumerLoopToProducerLoop = affine_map<(i, j, k) -> (i, j)> 627 /// Fused dimensions : i, j 628 /// 629 /// Example 2: 630 /// linalg.matmul ins(%a, %b) outs(%c) 631 /// linalg.generic {indexing_maps = [affine_map<(i, j) -> (j, i)>, ... 632 /// iterator_types = ["parallel", "parallel"]} 633 /// ins(%c) ... 634 /// 635 /// Number of parallel loops = 2: 636 /// producerIndexMap (projected to parallel loops) = 637 /// affine_map<(i, j) -> (i, j)> 638 /// consumerLoopToProducerLoop2 = affine_map<(i, j) -> (j, i)> 639 /// Fused dimensions : i, j 640 /// 641 /// Example 3: 642 /// linalg.copy(%s, %b) 643 /// linalg.matmul ins(%a, %b) outs(%c) 644 /// 645 /// Number of parallel loops = 2 646 /// produceIndexMap : affine_map<(i, j) -> (i, j)> 647 /// consumerLoopToProduceLoops = affine_map<(i, j, k) -> (k, j)> 648 /// submap with only parallel loops = affine_map<(i, j) -> (j)> 649 /// Fused dimensions : j 650 static std::set<unsigned> 651 collectFusableLoops(ArrayRef<LinalgOp> ops, 652 const FusableOpDependencesTy &fusableDependences) { 653 assert(!ops.empty()); 654 auto getNumOuterParallelLoops = [](LinalgOp linalgOp) { 655 return linalgOp.iterator_types() 656 .getValue() 657 .take_while([](Attribute attr) -> bool { 658 return attr.cast<StringAttr>().getValue() == 659 getParallelIteratorTypeName(); 660 }) 661 .size(); 662 }; 663 664 size_t numOuterParallelLoops = getNumOuterParallelLoops(ops.back()); 665 for (auto op : ops.drop_back()) { 666 numOuterParallelLoops = 667 std::min(numOuterParallelLoops, getNumOuterParallelLoops(op)); 668 } 669 670 std::set<unsigned> fusableLoops; 671 auto range = llvm::seq<unsigned>(0, numOuterParallelLoops); 672 fusableLoops.insert(range.begin(), range.end()); 673 674 for (auto op : reverse(ops)) { 675 for (auto dependence : fusableDependences.lookup(op)) { 676 LLVM_DEBUG({ 677 llvm::dbgs() << "\t fusable :"; 678 for (unsigned i : fusableLoops) 679 llvm::dbgs() << " " << i; 680 llvm::dbgs() << "\n"; 681 }); 682 683 Optional<AffineMap> consumerLoopToProducerLoop = 684 getConsumerLoopToProducerLoopMap(dependence); 685 if (!consumerLoopToProducerLoop) { 686 op.emitRemark("failed to get map from consumer loop to producer loop"); 687 return {}; 688 } 689 // todo: This condition is only an implementation limitation. When fusing 690 // the operation, if the accesses in the producer/consumer are transposes 691 // of each other, the loop bounds for the tiled producer can be 692 // manipulated accordingly. This requires some additional bookkeeping in 693 // the implementation of tile+fuse that is deferred to later. 694 if (doesTransposeAccess(*consumerLoopToProducerLoop, fusableLoops)) { 695 op.emitRemark("unhandled fusion when fusion requires permutation"); 696 return {}; 697 } 698 699 std::set<unsigned> candidates; 700 for (AffineExpr expr : consumerLoopToProducerLoop->getResults()) { 701 unsigned position = expr.cast<AffineDimExpr>().getPosition(); 702 if (fusableLoops.count(position)) 703 candidates.insert(position); 704 } 705 LLVM_DEBUG({ 706 llvm::dbgs() << "\t candidates :"; 707 for (unsigned i : candidates) 708 llvm::dbgs() << " " << i; 709 llvm::dbgs() << "\n"; 710 }); 711 if (candidates.empty()) 712 return {}; 713 std::swap(candidates, fusableLoops); 714 } 715 } 716 717 return fusableLoops; 718 } 719 720 /// Find all dependences that are fusable. 721 FusableOpDependencesTy mlir::linalg::findAllFusableDependences( 722 ArrayRef<LinalgOp> ops, const LinalgDependenceGraph &dependenceGraph) { 723 FusableOpDependencesTy fusableDependences; 724 DenseMap<Operation *, SmallVector<AffineMap, 1>> fusedProducerIndexingMap; 725 for (LinalgOp op : reverse(ops)) { 726 for (OpOperand &opOperand : op.getShapedOpOperands()) { 727 Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> 728 fusableDependence = findFusableProducer(opOperand, dependenceGraph); 729 if (!fusableDependence) 730 continue; 731 LinalgOp producerOp = 732 dyn_cast<LinalgOp>(fusableDependence->getDependentOp()); 733 if (!producerOp) 734 continue; 735 // Do not fuse dependences that are to operations not in the same basic 736 // block. This avoid moving fused operations across loops that might 737 // themselves carry dependency making the fusion illegal. 738 if (producerOp->getBlock() != op->getBlock()) 739 continue; 740 741 // Make sure that the indexing map of the view used for fusion in the 742 // producer is a projected permutation. 743 Optional<AffineMap> producerMap = 744 fusableDependence->getDependentOpViewIndexingMap(); 745 Optional<AffineMap> consumerMap = 746 fusableDependence->getIndexingOpViewIndexingMap(); 747 assert( 748 consumerMap && 749 "unable to find indexing map of operand/result of indexing OpView"); 750 fusedProducerIndexingMap[producerOp.getOperation()].push_back( 751 *consumerMap); 752 if (!producerMap || !producerMap->isProjectedPermutation() || 753 !consumerMap->isProjectedPermutation()) 754 continue; 755 756 fusableDependences[producerOp.getOperation()].push_back( 757 *fusableDependence); 758 } 759 } 760 // TODO: Currently fusion would not be legal if the fusable dependence is to 761 // the same producer but different indexing map in the consumer. Fix this, but 762 // in the meanwhile disallow such a fusion. 763 for (auto useIndexingMapsList : fusedProducerIndexingMap) { 764 AffineMap map1 = useIndexingMapsList.second.front(); 765 for (AffineMap map2 : 766 ArrayRef<AffineMap>(useIndexingMapsList.second).drop_front()) { 767 if (map1 != map2) { 768 fusableDependences.erase(useIndexingMapsList.first); 769 break; 770 } 771 } 772 } 773 return fusableDependences; 774 } 775 776 /// Tile the fused loops in the root operation, by setting the tile sizes for 777 /// all other loops to zero (those will be tiled later). 778 static Optional<TiledLinalgOp> tileRootOperation( 779 OpBuilder &builder, LinalgOp op, ArrayRef<Value> tileSizeVector, 780 const LinalgTilingOptions &options, const std::set<unsigned> &fusedLoops) { 781 SmallVector<Value, 4> tileSizes(tileSizeVector.begin(), tileSizeVector.end()); 782 auto zero = std_constant_index(0); 783 for (unsigned i = 0, e = tileSizes.size(); i != e; ++i) 784 if (!fusedLoops.count(i)) 785 tileSizes[i] = zero; 786 LinalgTilingOptions tileFusedLoopsOptions = options; 787 tileFusedLoopsOptions.setTileSizes(tileSizes); 788 return tileLinalgOp(builder, op, tileFusedLoopsOptions); 789 } 790 791 /// Fuse the operations in `fusionCandidates` with `tiledOp`. Latter is expected 792 /// to be a tiled operation such that it is valid to fuse all operations in 793 /// `fusionCandidates`, i.e. move the operation within the inter-tile loops of 794 /// `tiledOp`. 795 static SmallVector<LinalgOp, 1> 796 fuseOperations(OpBuilder &builder, LinalgOp rootOp, TiledLinalgOp tiledLinalgOp, 797 ArrayRef<LinalgOp> fusionCandidates, 798 const FusableOpDependencesTy &fusableDependences, 799 const std::set<unsigned> &fusedLoops) { 800 LinalgOp tiledOp = tiledLinalgOp.op; 801 OpBuilder::InsertionGuard guard(builder); 802 builder.setInsertionPoint(tiledOp); 803 804 DenseMap<unsigned, Range> fusedLoopsAndRanges; 805 for (unsigned loop : fusedLoops) { 806 ShapeDimension shapeDim = getShapeDefiningLoopRange(tiledOp, loop, true); 807 fusedLoopsAndRanges[loop] = getRangeFromOperandShape( 808 builder, tiledOp.getLoc(), shapeDim.shape, shapeDim.dimension); 809 } 810 811 SmallVector<LinalgOp, 1> fusedOps(fusionCandidates.size()); 812 DenseMap<Operation *, LinalgOp> origOpToFusedOp; 813 origOpToFusedOp[rootOp.getOperation()] = tiledOp; 814 for (auto candidate : enumerate(llvm::reverse(fusionCandidates))) { 815 LinalgOp origOp = candidate.value(); 816 LinalgOp fusedOp = fuse(builder, origOp, fusedLoopsAndRanges); 817 origOpToFusedOp[origOp.getOperation()] = fusedOp; 818 fusedOps[fusionCandidates.size() - candidate.index() - 1] = fusedOp; 819 820 // Prepare the builder for the next insertion point. 821 auto guard = 822 llvm::make_scope_exit([&]() { builder.setInsertionPoint(fusedOp); }); 823 if (!origOp.hasTensorSemantics()) 824 continue; 825 826 // If the producer consumer operations are linalg operations on tensors, the 827 // dependence is due to value produced (as a return tensor) by the producer 828 // and used in the consumer. The returned value of the fused op needs to be 829 // made the operand of the tiled/fused consumer operation. By construction 830 // the value returned by the producer is the value used by the consumer. 831 for (auto &dependence : fusableDependences.lookup(origOp.getOperation())) { 832 if (dependence.dependenceType != 833 LinalgDependenceGraph::DependenceType::RAW) 834 continue; 835 836 unsigned resultIndex = 837 dependence.getDependentOpViewResultNum().getValue(); 838 LinalgOp consumer = origOpToFusedOp.lookup(dependence.getIndexingOp()); 839 if (!consumer) 840 continue; 841 842 Value replacementValue = fusedOp.getOperation()->getResult(resultIndex); 843 consumer.getOperation()->setOperand( 844 dependence.getIndexingOpViewOperandNum().getValue(), 845 replacementValue); 846 } 847 848 // At this point, all Linalg uses of the tensors produced by `origOp` have 849 // been replaced. However, there may still be "output tensor"-like uses 850 // coming from WAW dependencies. 851 // All these uses are iter_args of the outermost loop (TODO: add a check). 852 // Such iter_args uses serve 2 purposes: 853 // 1. give a shape to the output 854 // 2. encode destructive updates that may be inplaceable by bufferization. 855 // To keep the second type of information while letting the unfused op die 856 // unused, we need to forward the producer output operand. 857 for (auto &operand : 858 cast<scf::ForOp>(tiledLinalgOp.loops.front()).getIterOpOperands()) 859 if (auto opResult = operand.get().dyn_cast<OpResult>()) 860 if (opResult.getOwner() == origOp) 861 operand.set(origOp.getOutputTensors()[opResult.getResultNumber()]); 862 } 863 return fusedOps; 864 } 865 866 template <typename LoopType> 867 static Optional<TiledAndFusedLinalgOps> 868 tileAndFuseLinalgOpsImpl(OpBuilder &builder, ArrayRef<LinalgOp> ops, 869 const LinalgDependenceGraph &dependenceGraph, 870 const LinalgTilingOptions &tilingOptions) { 871 if (ops.size() < 2) 872 return llvm::None; 873 LinalgOp rootOp = ops.back(); 874 if (!llvm::all_of( 875 ops, 876 [](LinalgOp linalgOp) { return linalgOp.hasBufferSemantics(); }) && 877 !llvm::all_of(ops, [](LinalgOp linalgOp) { 878 return linalgOp.hasTensorSemantics(); 879 })) { 880 rootOp.emitError( 881 "unable to fuse operations that have tensor semantics with operations " 882 "that have buffer semantics and viceversa."); 883 return llvm::None; 884 } 885 // TODO: Support interchange with tile + fuse. This might actually help do 886 // better fusion. 887 if (!tilingOptions.interchangeVector.empty()) { 888 rootOp.emitRemark("unable to handle tile and fuse with interchange"); 889 return llvm::None; 890 } 891 892 OpBuilder::InsertionGuard guard(builder); 893 builder.setInsertionPoint(rootOp); 894 ScopedContext scope(builder, rootOp.getLoc()); 895 896 // Find all the producers. 897 LLVM_DEBUG(llvm::dbgs() << "findAllFusableDependences\n"); 898 FusableOpDependencesTy fusableDependences = 899 findAllFusableDependences(ops, dependenceGraph); 900 if (fusableDependences.empty()) { 901 LLVM_DEBUG(llvm::dbgs() << "no fusable dependencies found\n"); 902 return llvm::None; 903 } 904 905 TiledAndFusedLinalgOps ret; 906 // Find the loops that can be tiled and fused. 907 LLVM_DEBUG(llvm::dbgs() << "collectFusableLoops\n"); 908 ret.fusedLoopDims = collectFusableLoops(ops, fusableDependences); 909 910 // If there are no fusable dependences or there are no tile+fusable loops, 911 // just return. 912 if (ret.fusedLoopDims.empty()) { 913 LLVM_DEBUG(llvm::dbgs() << "no fusable loops found\n"); 914 return llvm::None; 915 } 916 917 // Tile the fused loops in the last operation in the list. 918 SmallVector<Value, 4> tileSizeVector = 919 tilingOptions.tileSizeComputationFunction(builder, rootOp); 920 Optional<TiledLinalgOp> tiledRootOp = tileRootOperation( 921 builder, rootOp, tileSizeVector, tilingOptions, ret.fusedLoopDims); 922 if (!tiledRootOp) { 923 rootOp.emitRemark("failed to tile the fused loops"); 924 return llvm::None; 925 } 926 ret.op = tiledRootOp->op; 927 ret.fusedLoops.assign(tiledRootOp->loops.begin(), tiledRootOp->loops.end()); 928 929 // Fuse the other operations into the fused inter-tile loops produced above. 930 ret.fusedProducers = 931 fuseOperations(builder, rootOp, *tiledRootOp, ops.drop_back(), 932 fusableDependences, ret.fusedLoopDims); 933 934 return ret; 935 } 936 937 Optional<TiledAndFusedLinalgOps> 938 mlir::linalg::tileAndFuseLinalgOps(OpBuilder &builder, ArrayRef<LinalgOp> ops, 939 const LinalgDependenceGraph &dependenceGraph, 940 const LinalgTilingOptions &tilingOptions) { 941 switch (tilingOptions.loopType) { 942 case LinalgTilingLoopType::Loops: 943 return tileAndFuseLinalgOpsImpl<scf::ForOp>(builder, ops, dependenceGraph, 944 tilingOptions); 945 case LinalgTilingLoopType::ParallelLoops: 946 return tileAndFuseLinalgOpsImpl<scf::ParallelOp>( 947 builder, ops, dependenceGraph, tilingOptions); 948 default:; 949 } 950 return llvm::None; 951 } 952