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