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