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