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