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