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