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