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 on tensors operations pass.
10 //
11 //===----------------------------------------------------------------------===//
12 #include "PassDetail.h"
13 #include "mlir/Dialect/Affine/IR/AffineOps.h"
14 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
15 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
16 #include "mlir/Dialect/Linalg/Passes.h"
17 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
18 #include "mlir/Dialect/Linalg/Utils/Utils.h"
19 #include "mlir/IR/AffineExpr.h"
20 #include "mlir/IR/AffineMap.h"
21 #include "mlir/IR/PatternMatch.h"
22 #include "mlir/Support/LLVM.h"
23 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
24 
25 using namespace mlir;
26 using namespace mlir::linalg;
27 
28 /// Implementation of fusion of generic ops and indexed_generic ops.
29 // struct FuseGenericOpsOnTensors {
30 static bool areTensorOpsFusable(LinalgOp producer, LinalgOp consumer,
31                                 unsigned consumerIdx) {
32   // Producer and consumer must have tensor semantics.
33   if (!producer.hasTensorSemantics() || !consumer.hasTensorSemantics())
34     return false;
35 
36   // Verify that
37   // - the producer has all "parallel" iterator type.
38   if (producer.getNumParallelLoops() != producer.getNumLoops())
39     return false;
40 
41   // Get the consumer index map. The number of results of the consumer index
42   // map must match the number of loops of the producer.
43   AffineMap consumerIndexMap = consumer.getIndexingMap(consumerIdx);
44   if (consumerIndexMap.getNumResults() != producer.getNumLoops())
45     return false;
46 
47   // Finally the index_map for the result must be invertible. For now just
48   // verify it is a permutation.
49   AffineMap producerResultIndexMap = producer.getOutputIndexingMap(0);
50   return producerResultIndexMap.isPermutation();
51 }
52 
53 /// Append to `fusedOpIndexingMapAttrs` the indexing maps for the operands of
54 /// the `producer` to use in the fused operation given the indexing map of the
55 /// result of the producer in the consumer.
56 static void getIndexingMapOfProducerOperandsInFusedOp(
57     LinalgOp producer, AffineMap fusedConsumerArgIndexMap,
58     SmallVectorImpl<Attribute> &fusedOpIndexingMapAttrs) {
59   // The indexing map in the consumer op (fusedConsumerArgIndexMap) is a map
60   // from consumer loop -> consumer arg tensor index/producer result tensor
61   // index. The fused loop is same as the consumer loop. For each producer arg
62   // the indexing map to be computed is a map from consumer loop -> producer
63   // arg tensor index.
64 
65   AffineMap producerResultIndexMap = producer.getOutputIndexingMap(0);
66   // producerResultIndexMap is a map from producer loop -> tensor index.
67   // Compute the inverse to get map from tensor index -> producer loop.
68   // The inverse is a map from producer result tensor index -> producer loop.
69   AffineMap invProducerResultIndexMap =
70       inversePermutation(producerResultIndexMap);
71   assert(invProducerResultIndexMap &&
72          "expected producer result indexig map to be invertible");
73   for (unsigned argNum : llvm::seq<unsigned>(0, producer.getNumInputs())) {
74     // argMap is a map from producer loop -> producer arg tensor index.
75     AffineMap argMap = producer.getInputIndexingMap(argNum);
76 
77     // Compose argMap with invProducerResultIndexMap to get a map from
78     // producer result tensor index -> producer arg tensor index.
79     AffineMap t1 = argMap.compose(invProducerResultIndexMap);
80 
81     // Compose t1 with fusedConsumerArgIndexMap gives an indexing map from
82     // consumer loop/ fused loop -> producer arg tensor index.
83     AffineMap indexingMap = t1.compose(fusedConsumerArgIndexMap);
84     fusedOpIndexingMapAttrs.push_back(AffineMapAttr::get(indexingMap));
85   }
86 }
87 
88 /// Generate the region of the fused tensor operation. The region of the fused
89 /// op must be empty.
90 static void generateFusedTensorOpRegion(PatternRewriter &rewriter,
91                                         Operation *fusedOp, LinalgOp producer,
92                                         LinalgOp consumer,
93                                         AffineMap consumerToProducerLoopsMap,
94                                         unsigned consumerIdx, unsigned nloops) {
95   // Build the region of the fused op.
96   Block &producerBlock = producer.getOperation()->getRegion(0).front();
97   Block &consumerBlock = consumer.getOperation()->getRegion(0).front();
98   Block *fusedBlock = new Block();
99   fusedOp->getRegion(0).push_back(fusedBlock);
100   BlockAndValueMapping mapper;
101   OpBuilder::InsertionGuard guard(rewriter);
102   rewriter.setInsertionPointToStart(fusedBlock);
103 
104   // The block arguments are
105   // [index_0, index_1, ... ,
106   //   consumer_operand_0, ... , consumer_operand_(`consumerIdx`-1),
107   //   producer_operand_0, ... , producer_operand_(n-1)],
108   //   consumer_operand_(`consumerIdx`), .. consumer_operand_(m-1)]
109   // , where n is the number of producer's operand and m is the number
110   // consumer's operand.
111   // If both `numProducerIndices` and `numConsumerIndices` are zero, this is a
112   // generic op. In this case, there are no indices in block arguments.
113   unsigned numProducerIndices = isa<IndexedGenericOp>(producer.getOperation())
114                                     ? producer.getNumLoops()
115                                     : 0;
116   unsigned numConsumerIndices = isa<IndexedGenericOp>(consumer.getOperation())
117                                     ? consumer.getNumLoops()
118                                     : 0;
119   unsigned numFusedOpIndices =
120       (isa<IndexedGenericOp>(producer.getOperation()) ||
121        isa<IndexedGenericOp>(consumer.getOperation()))
122           ? std::max(producer.getNumLoops(), consumer.getNumLoops())
123           : 0;
124   // Firstly, add all the indices to the block arguments.
125   for (unsigned i = 0, e = numFusedOpIndices; i < e; ++i)
126     fusedBlock->addArgument(rewriter.getIndexType());
127   // Map the arguments for the unmodified args from the consumer.
128   for (auto consumerArg : llvm::enumerate(consumerBlock.getArguments())) {
129     if (consumerArg.index() == consumerIdx + numConsumerIndices) {
130       // Map the arguments for the args from the producer.
131       for (auto producerArg : llvm::enumerate(producerBlock.getArguments())) {
132         // If producer is an indexed_generic op, map the indices from consumer
133         // loop to producer loop (because the fusedOp is built based on
134         // consumer's perspective).
135         if (producerArg.index() < numProducerIndices) {
136           auto newIndex = rewriter.create<mlir::AffineApplyOp>(
137               producer.getLoc(),
138               consumerToProducerLoopsMap.getSubMap(producerArg.index()),
139               fusedBlock->getArguments().take_front(numFusedOpIndices));
140           mapper.map(producerArg.value(), newIndex);
141         } else {
142           mapper.map(producerArg.value(),
143                      fusedBlock->addArgument(producerArg.value().getType()));
144         }
145       }
146       continue;
147     }
148 
149     // If consumer is an indexed_generic op, map the indices to the block
150     // arguments directly. Otherwise, add the same type of argument and map to
151     // it.
152     if (consumerArg.index() < numConsumerIndices) {
153       mapper.map(consumerArg.value(),
154                  fusedBlock->getArgument(consumerArg.index()));
155     } else {
156       mapper.map(consumerArg.value(),
157                  fusedBlock->addArgument(consumerArg.value().getType()));
158     }
159   }
160 
161   // Add operations from producer (except the yield operation) to the fused
162   // op.
163   for (auto &op : producerBlock.getOperations()) {
164     if (auto yieldOp = dyn_cast<linalg::YieldOp>(op)) {
165       // Lookup the value the yield operation is mapped to.
166       Value yieldVal = yieldOp.getOperand(0);
167       if (Value clonedVal = mapper.lookupOrNull(yieldVal))
168         mapper.map(consumerBlock.getArgument(consumerIdx + numConsumerIndices),
169                    clonedVal);
170       continue;
171     }
172     rewriter.clone(op, mapper);
173   }
174   for (auto &op : consumerBlock.getOperations())
175     rewriter.clone(op, mapper);
176 }
177 
178 static Optional<SmallVector<Value, 1>>
179 fuseTensorOpsImpl(LinalgOp producer, LinalgOp consumer, unsigned consumerIdx,
180                   PatternRewriter &rewriter) {
181   if (!areTensorOpsFusable(producer, consumer, consumerIdx))
182     return llvm::None;
183 
184   unsigned numFusedOperands =
185       producer.getNumInputs() + consumer.getNumInputs() - 1;
186 
187   // Compute the fused operands list,
188   SmallVector<Value, 2> fusedOperands;
189   fusedOperands.reserve(numFusedOperands);
190   auto consumerOperands = consumer.getInputs();
191   auto producerOperands = producer.getInputs();
192   fusedOperands.assign(consumerOperands.begin(),
193                        std::next(consumerOperands.begin(), consumerIdx));
194   fusedOperands.append(producerOperands.begin(), producerOperands.end());
195   fusedOperands.append(std::next(consumerOperands.begin(), consumerIdx + 1),
196                        consumerOperands.end());
197 
198   // Compute indexing_maps for the fused operation. The indexing_maps for the
199   // operands of the consumers that arent fused are the same. The
200   // indexing_maps for the producers need to be computed based on the
201   // indexing_map of the operand at consumerIdx in the consumer.
202   SmallVector<Attribute, 4> fusedIndexMaps;
203   auto consumerIndexMaps = consumer.indexing_maps();
204   fusedIndexMaps.reserve(fusedOperands.size() + consumer.getNumOutputs());
205   fusedIndexMaps.assign(consumerIndexMaps.begin(),
206                         std::next(consumerIndexMaps.begin(), consumerIdx));
207   // Compute indexing maps for the producer args in the fused operation.
208   getIndexingMapOfProducerOperandsInFusedOp(
209       producer, consumer.getInputIndexingMap(consumerIdx), fusedIndexMaps);
210 
211   // Append the indexing maps for the remaining consumer operands.
212   fusedIndexMaps.append(std::next(consumerIndexMaps.begin(), consumerIdx + 1),
213                         consumerIndexMaps.end());
214 
215   // Generate the fused op.
216   // Tensor-level fusion is only on ops without initTensors and outputBuffers.
217   LinalgOp fusedOp;
218   if (isa<GenericOp>(producer.getOperation()) &&
219       isa<GenericOp>(consumer.getOperation())) {
220     fusedOp = rewriter
221                   .create<GenericOp>(consumer.getLoc(),
222                                      consumer.getOperation()->getResultTypes(),
223                                      /*inputs=*/fusedOperands,
224                                      /*outputBuffers=*/ValueRange{},
225                                      /*initTensors=*/ValueRange{},
226                                      rewriter.getArrayAttr(fusedIndexMaps),
227                                      consumer.iterator_types(),
228                                      /*doc=*/nullptr,
229                                      /*library_call=*/nullptr,
230                                      /*sparse=*/nullptr)
231                   .getOperation();
232   } else {
233     fusedOp =
234         rewriter
235             .create<IndexedGenericOp>(consumer.getLoc(),
236                                       consumer.getOperation()->getResultTypes(),
237                                       /*inputs=*/fusedOperands,
238                                       /*outputBuffers=*/ValueRange{},
239                                       /*initTensors=*/ValueRange{},
240                                       rewriter.getArrayAttr(fusedIndexMaps),
241                                       consumer.iterator_types(),
242                                       /*doc=*/nullptr,
243                                       /*library_call=*/nullptr,
244                                       /*sparse=*/nullptr)
245             .getOperation();
246   }
247 
248   // Construct an AffineMap from consumer loops to producer loops.
249   // consumer loop -> tensor index
250   AffineMap consumerResultIndexMap = consumer.getInputIndexingMap(consumerIdx);
251   // producer loop -> tensor index
252   AffineMap producerResultIndexMap = producer.getOutputIndexingMap(0);
253   // tensor index -> producer loop
254   AffineMap invProducerResultIndexMap =
255       inversePermutation(producerResultIndexMap);
256   assert(invProducerResultIndexMap &&
257          "expected producer result indexig map to be invertible");
258   // consumer loop -> producer loop
259   AffineMap consumerToProducerLoopsMap =
260       invProducerResultIndexMap.compose(consumerResultIndexMap);
261 
262   generateFusedTensorOpRegion(rewriter, fusedOp.getOperation(), producer,
263                               consumer, consumerToProducerLoopsMap, consumerIdx,
264                               consumer.getNumLoops());
265   return SmallVector<Value, 1>(fusedOp.getOperation()->getResults());
266 }
267 
268 /// Linearize the expressions in `sourceMap` based on the `reassociationMaps`
269 /// provided, given the shape of the source tensor that corresponds to the
270 /// `sourceMap`. Note that this implicitly assumes that the tensors dimensions
271 /// are "row-major" ordered logically.
272 ///
273 /// For example:
274 ///
275 /// %0 = op ... : tensor<?x?x4x5xf32>
276 /// with output index_map `affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>`
277 ///
278 /// and reshape:
279 /// %1 = linalg.tensor_reshape %0 [affine_map<(i, j, k, l) -> (i)>,
280 ///                                affine_map<(i, j, k, l) -> (j, k, l)>] :
281 ///        tensor<?x?x4x5xf32> into tensor<?x?xf32>
282 ///
283 /// would be rewritten into:
284 /// %0 = op ... : tensor<?x?x4x5xf32>
285 /// with output index_map
286 ///   `affine_map<(d0, d1, d2, d3) -> (d0, d1 * 20 + d2 * 5 + d3)>`
287 static AffineMap linearizeCollapsedDims(AffineMap sourceMap,
288                                         ArrayRef<int64_t> sourceShape,
289                                         ArrayRef<AffineMap> reassociationMaps) {
290   SmallVector<AffineExpr, 4> resultExprs;
291   resultExprs.reserve(reassociationMaps.size());
292   ArrayRef<AffineExpr> sourceExprs = sourceMap.getResults();
293   MLIRContext *context = sourceMap.getContext();
294 
295   // Compute the result exprs based on the reassociation maps.
296   for (AffineMap map : reassociationMaps) {
297     ArrayRef<AffineExpr> collapsedDims = map.getResults();
298     // Assume that they are in-order and contiguous (already checked in
299     // verifier).
300     assert(!collapsedDims.empty());
301     unsigned startDim =
302         collapsedDims.front().cast<AffineDimExpr>().getPosition();
303     AffineExpr linearizedExpr = makeCanonicalStridedLayoutExpr(
304         sourceShape.slice(startDim, collapsedDims.size()),
305         sourceExprs.slice(startDim, collapsedDims.size()), context);
306     resultExprs.push_back(linearizedExpr);
307   }
308   return AffineMap::get(sourceMap.getNumDims(), sourceMap.getNumSymbols(),
309                         resultExprs, context);
310 }
311 
312 /// Checks if the `reshapeOp` can be fused with it consumer (if `asProducer` is
313 /// true) or its producer (if `asProducer` is false) given the indexing map at
314 /// its use.
315 static bool isTensorReshapeOpFoldableByLinearization(TensorReshapeOp reshapeOp,
316                                                      AffineMap useIndexMap,
317                                                      bool asProducer) {
318   RankedTensorType returnType = reshapeOp.getResultType();
319   RankedTensorType operandType = reshapeOp.getSrcType();
320   // Reshape is fusable with its consumer (i.e. reshape as a producer) when its
321   // operand is of lesser rank than the result. Fusing when operand has higher
322   // rank will require use of mods and divs in the indexing maps of the fused op
323   // which would make it non-invertible. Similarly reshape is fused with its
324   // producer (i.e. reshape as consumer) only if the return type has lesser
325   // rank.
326   if ((asProducer && reshapeOp.getSrcType().hasStaticShape() &&
327        returnType.getRank() < operandType.getRank()) ||
328       (!asProducer && reshapeOp.getResultType().hasStaticShape() &&
329        operandType.getRank() < returnType.getRank()))
330     return false;
331   return useIndexMap.isPermutation();
332 }
333 
334 /// Based on the type of `op` create a linalg op of the same type, i.e. if `op`
335 /// is a linalg.generic operation, the create a `linalg.generic` operation with
336 /// the given `args`. Expects `op` to be `linalg.generic` or
337 /// `linalg.indexed_generic`.
338 template <typename... Args>
339 static LinalgOp createLinalgOpOfSameType(LinalgOp op, PatternRewriter &rewriter,
340                                          Args... args) {
341   if (isa<GenericOp>(op.getOperation()))
342     return rewriter.create<GenericOp>(args...);
343   if (isa<IndexedGenericOp>(op.getOperation()))
344     return rewriter.create<IndexedGenericOp>(args...);
345   llvm_unreachable(
346       "expected only linalg.generic or linalg.indexed_generic ops");
347   return nullptr;
348 }
349 
350 /// Conditions for folding a generic/indexed-generic operation with a reshape op
351 /// by expanding the iteration space dimensionality for tensor operations. These
352 /// are preconditions assumed by `foldReshapeByDimExpansion` which implements
353 /// the following fusion pattern.
354 ///
355 ///  Consider
356 ///
357 ///  %c = linalg.generic ins(%a, %b : memref<?x?x?xf32>, memref<?x?xf32>)
358 ///         indexing_maps = [affine_map<(d0, d1, d2) -> (d1, d0, d2)>,
359 ///                          affine_map<(d0, d1, d2) -> (d1, d2)>,
360 ///                          affine_map<(d0, d1, d2) -> (d0, d2, d1)>]
361 ///  %d = linalg.tensor_reshape %c
362 ///         [affine_map<(d0, d1, d2, d3, d4, d5) -> (d0, d1)>,
363 ///          affine_map<(d0, d1, d2, d3, d4, d5) -> (d2)>,
364 ///          affine_map<(d0, d1, d2, d3, d4, d5) -> (d3, d4, d5)>]
365 ///       : tensor<?x?x?xf32> into tensor<?x?x?x?x?x?xf32>
366 ///
367 ///  The reshape can be folded into the `linalgOp` if the
368 ///  generic/indexed-generic op loop dimensionality is increased to match the
369 ///  result (operand) of the tensor_reshape when the reshape is expanding
370 ///  (folding). The indexing_map of the fused tensor in the `linalgOp` and the
371 ///  reassociation map helps compute the indexing maps of the modified op. For
372 ///  the above example, based on the reassociation map it can be concluded that
373 ///
374 ///  - The loop used to access the first dimension of the fused tensor is split
375 ///    into two.
376 ///  - The loop used to access the second dimension of the fused tensor is kept
377 ///    as is.
378 ///  - The loop used to access the third dimension of the fused tensor is split
379 ///    into three.
380 ///
381 ///  i.e. (e0, e1, e2, e3, e4) is the domain of the indexing map of the modified
382 ///  op, then
383 ///
384 ///   d0 -> e0, e1
385 ///   d1 -> e2, e3, e4
386 ///   d2 -> e5
387 ///
388 ///  substituting this, the generic op can be rewritten as
389 ///
390 ///  %d = linalg.generic ins(%0, %1 : )
391 ///        indexing_maps =
392 ///         [affine_map<(e0, e1, e2, e3, e4, e5) -> (e2, e3, e4, e0, e1, e5)>,
393 ///          affine_map<(e0, e1, e2, e3, e4, e5) -> (e2, e3, e4, e5)>,
394 ///          affine_map<(e0, e1, e2, e3, e4, e5) -> (e0, e1, e5, e2, e3, e4)>]
395 ///
396 ///  Since operands to the linalg generic are now 5D, reshapes can be introduced
397 ///  to make it consistent
398 ///
399 ///  %0 = linalg.tensor_reshape %a
400 ///         [affine_map<(e0, e1, e2, e3, e4, e5) -> (e0, e1, e2),
401 ///          affine_map<(e0, e1, e2, e3, e4, e5) -> (e3, e4),
402 ///          affine_map<(e0, e1, e2, e3, e4, e5) -> (e5)]
403 ///       : tensor<?x?x?xf32> into tensor<?x?x?x?x?x?xf32>
404 ///  %1 = linalg.tensor_reshape %b
405 ///         [affine_map<(e0, e1, e2, e3) -> (e0, e1, e2),
406 ///          affine_map<(e0, e1, e2, e3) -> (e3)]
407 ///       : tensor<?x?x?xf32> into tensor<?x?x?x?xf32>
408 ///
409 ///  The added reshapes are again expanding patterns, so they will get fused
410 ///  with its producers if possible.
411 static bool isFusableWithReshapeByDimExpansion(LinalgOp linalgOp,
412                                                unsigned fusedTensorIndex) {
413   // Is fusable only if:
414   // - The linalgOp is a generic op, or an indexed_generic.
415   // - All the indexing maps for operands in linalgOp are projected
416   //   permutations.
417   // - The indexing map at the position representing the fused tensor is a
418   //   permutation.
419   // - All the loops in linalgOp are parallel loops.
420   return isa<GenericOp, IndexedGenericOp>(linalgOp.getOperation()) &&
421          linalgOp.hasTensorSemantics() &&
422          llvm::all_of(linalgOp.indexing_maps().getValue().take_front(
423                           linalgOp.getNumInputs()),
424                       [](Attribute attr) {
425                         return attr.cast<AffineMapAttr>()
426                             .getValue()
427                             .isProjectedPermutation();
428                       }) &&
429          linalgOp.getIndexingMap(fusedTensorIndex).isPermutation() &&
430          llvm::all_of(linalgOp.iterator_types(), [](Attribute attr) {
431            return attr.cast<StringAttr>().getValue() ==
432                   getParallelIteratorTypeName();
433          });
434 }
435 
436 /// Implements the fusion of a tensor_reshape op and a generic/indexed_generic
437 /// op as explained in `isFusableWithReshapeByExpansion`. Assumes that those
438 /// conditions have been satisfied.
439 static Optional<SmallVector<Value, 1>>
440 fuseWithReshapeByExpansion(LinalgOp linalgOp, TensorReshapeOp reshapeOp,
441                            unsigned fusedTensorIndex,
442                            PatternRewriter &rewriter) {
443   assert(isFusableWithReshapeByDimExpansion(linalgOp, fusedTensorIndex) &&
444          "preconditions for fuse operation failed");
445   // Check if reshape is expanding or collapsing.
446   bool isExpanding =
447       reshapeOp.getSrcType().getRank() < reshapeOp.getResultType().getRank();
448   RankedTensorType expandedType =
449       isExpanding ? reshapeOp.getResultType() : reshapeOp.getSrcType();
450   RankedTensorType foldedType =
451       isExpanding ? reshapeOp.getSrcType() : reshapeOp.getResultType();
452   AffineMap fusedIndexMap = linalgOp.getIndexingMap(fusedTensorIndex);
453 
454   // The reshape is folding/expanding consecutive dimensions. Given the indexing
455   // map of the fused tensor find the number of dimensions each of the loops of
456   // the original op is expanded into. Also record the shape of the expanded
457   // dimensions.
458   ArrayRef<int64_t> expandedShape = expandedType.getShape();
459   SmallVector<unsigned, 4> numFoldedDims(foldedType.getRank(), 0);
460   SmallVector<SmallVector<int64_t, 4>, 4> expandedDimsShape(
461       foldedType.getRank());
462   auto reassociationMaps = reshapeOp.getReassociationMaps();
463   for (auto resultExpr : llvm::enumerate(fusedIndexMap.getResults())) {
464     unsigned pos = resultExpr.value().cast<AffineDimExpr>().getPosition();
465     AffineMap foldedDims = reassociationMaps[resultExpr.index()];
466     numFoldedDims[pos] = foldedDims.getNumResults();
467     ArrayRef<int64_t> shape =
468         expandedShape.slice(foldedDims.getDimPosition(0), numFoldedDims[pos]);
469     expandedDimsShape[pos].assign(shape.begin(), shape.end());
470   }
471 
472   if (isa<IndexedGenericOp>(linalgOp.getOperation())) {
473     // For indexed generic op, the region contains arguments that represent the
474     // induction variable value of the loops. In the fused op these values are
475     // obtained by linearizing the expanded dimensions. For now just check that
476     // the extents used in the linearization (all the expanded dims except the
477     // front) are statically know. For dynamic case, we would need shape
478     // information on these dimensions to get these.
479     for (auto &expandedShape : expandedDimsShape) {
480       for (int64_t expandedDimShape : llvm::make_range(
481                std::next(expandedShape.begin()), expandedShape.end())) {
482         if (ShapedType::isDynamic(expandedDimShape)) {
483           linalgOp.emitError(
484               "unable to fuse indexed generic op where the expanded dim is "
485               "dynamic");
486           return llvm::None;
487         }
488       }
489     }
490   }
491 
492   // The remapping of the indices is then the prefix sum (inclusive) of the
493   // numFoldedDims.
494   SmallVector<unsigned, 4> remapping(numFoldedDims.size() + 1, 0);
495   unsigned sum = 0;
496   for (auto numFoldedDim : llvm::enumerate(numFoldedDims)) {
497     sum += numFoldedDim.value();
498     remapping[numFoldedDim.index() + 1] = sum;
499   }
500 
501   SmallVector<AffineMap, 4> expandedOpIndexingMaps;
502   // Compute the modified indexing maps by replacing every loop (AffineDimExpr)
503   // in the original indexing map with the sequence of loops that it is expanded
504   // to.
505   for (AffineMap indexingMap : linalgOp.getIndexingMaps()) {
506     SmallVector<AffineExpr, 4> newExprs;
507     for (AffineExpr expr : indexingMap.getResults()) {
508       unsigned pos = expr.cast<AffineDimExpr>().getPosition();
509       for (unsigned newPos :
510            llvm::seq<unsigned>(remapping[pos], remapping[pos + 1])) {
511         newExprs.push_back(rewriter.getAffineDimExpr(newPos));
512       }
513     }
514     expandedOpIndexingMaps.push_back(
515         AffineMap::get(remapping.back(), indexingMap.getNumSymbols(), newExprs,
516                        rewriter.getContext()));
517   }
518 
519   // The operands of the expanded op are computed by reshaping the original
520   // operands. The reshape depends on the ordering of the loop used to access
521   // the tensor in the original operation, and are expanded into as many
522   // dimensions as the loop is expanded into (as computed by `remapping`).
523   auto getReshapeInfo =
524       [&](AffineMap operandIndexingMap,
525           SmallVectorImpl<ReassociationIndices> &reassociation,
526           SmallVectorImpl<int64_t> &expandedOpOperandShape) {
527         unsigned reshapeDims = 0;
528         for (AffineExpr expr : operandIndexingMap.getResults()) {
529           unsigned origDim = expr.cast<AffineDimExpr>().getPosition();
530           auto foldedDims = llvm::seq<int64_t>(
531               reshapeDims, reshapeDims + numFoldedDims[origDim]);
532           reassociation.emplace_back(foldedDims.begin(), foldedDims.end());
533           expandedOpOperandShape.append(expandedDimsShape[origDim].begin(),
534                                         expandedDimsShape[origDim].end());
535           reshapeDims += numFoldedDims[origDim];
536         }
537       };
538   SmallVector<Value, 4> expandedOpOperands;
539   for (auto operand : llvm::enumerate(linalgOp.getInputs())) {
540     if (operand.index() == fusedTensorIndex) {
541       expandedOpOperands.push_back(reshapeOp.src());
542       continue;
543     }
544     AffineMap indexingMap = linalgOp.getIndexingMap(operand.index());
545     SmallVector<ReassociationIndices, 4> reassociation;
546     SmallVector<int64_t, 4> expandedOperandShape;
547     getReshapeInfo(indexingMap, reassociation, expandedOperandShape);
548     Type expandedOperandType = RankedTensorType::get(
549         expandedOperandShape,
550         operand.value().getType().cast<ShapedType>().getElementType());
551     if (expandedOperandType != operand.value().getType()) {
552       expandedOpOperands.push_back(rewriter.create<TensorReshapeOp>(
553           linalgOp.getLoc(), expandedOperandType, operand.value(),
554           reassociation));
555     } else {
556       expandedOpOperands.push_back(operand.value());
557     }
558   }
559   SmallVector<Type, 1> resultTypes;
560   SmallVector<SmallVector<ReassociationIndices, 4>, 1> resultReassociation;
561   for (auto result : llvm::enumerate(linalgOp.getOperation()->getResults())) {
562     AffineMap indexingMap =
563         linalgOp.getIndexingMap(linalgOp.getNumInputs() + result.index());
564     SmallVector<ReassociationIndices, 4> reassociation;
565     SmallVector<int64_t, 4> expandedResultShape;
566     getReshapeInfo(indexingMap, reassociation, expandedResultShape);
567     resultTypes.push_back(RankedTensorType::get(
568         expandedResultShape,
569         result.value().getType().cast<ShapedType>().getElementType()));
570     resultReassociation.emplace_back(std::move(reassociation));
571   }
572 
573   // The iterator types of the expanded op are all parallel.
574   SmallVector<StringRef, 4> iteratorTypes(remapping.back(),
575                                           getParallelIteratorTypeName());
576 
577   LinalgOp fusedOp = createLinalgOpOfSameType(
578       linalgOp, rewriter, linalgOp.getLoc(), resultTypes,
579       /*inputs=*/expandedOpOperands,
580       /*outputBuffers=*/ValueRange{},
581       /*initTensors=*/ValueRange{}, expandedOpIndexingMaps, iteratorTypes);
582   Region &fusedRegion = fusedOp.getOperation()->getRegion(0);
583   Region &originalRegion = linalgOp.getOperation()->getRegion(0);
584 
585   if (isa<GenericOp>(linalgOp.getOperation())) {
586     rewriter.cloneRegionBefore(originalRegion, fusedRegion,
587                                fusedRegion.begin());
588   } else {
589     assert(isa<IndexedGenericOp>(linalgOp.getOperation()));
590     // Create an entry block in the fused Region with same number of arguments
591     // as the fused op
592     Block *fusedEntryBlock = new Block;
593     fusedRegion.push_back(fusedEntryBlock);
594     rewriter.cloneRegionBefore(originalRegion, fusedRegion, fusedRegion.end());
595 
596     // Merge the entry block of the fused op with the cloned blocks. For this
597     // compute the value for arguments of the region in the original operation
598     // in terms of the arguments of the fused op. Since the original operation
599     // is expanded, the expanded dimensions need to be folded back to get the
600     // replacement value for the arguments corresponding to interation index.
601     // For now this expects that all the loop ranges are constants, which is
602     // true if the shapes are all static. This has already been checked in the
603     // precondition.
604     using namespace edsc::op;
605     using namespace edsc::intrinsics;
606     OpBuilder::InsertionGuard guard(rewriter);
607     SmallVector<Value, 4> argReplacements(originalRegion.getNumArguments());
608     rewriter.setInsertionPointToStart(fusedEntryBlock);
609     edsc::ScopedContext scopedContext(rewriter, fusedOp.getLoc());
610     IndexType indexType = rewriter.getIndexType();
611     for (unsigned i : llvm::seq<unsigned>(0, numFoldedDims.size())) {
612       Value linearizedIndex = fusedEntryBlock->addArgument(indexType);
613       for (unsigned foldedDim = remapping[i] + 1; foldedDim != remapping[i + 1];
614            foldedDim++) {
615         int64_t expandedDimExtent =
616             expandedDimsShape[i][foldedDim - remapping[i]];
617         assert(!ShapedType::isDynamic(expandedDimExtent));
618         linearizedIndex =
619             linearizedIndex * std_constant_index(expandedDimExtent);
620         linearizedIndex =
621             linearizedIndex + fusedEntryBlock->addArgument(indexType);
622       }
623       argReplacements[i] = linearizedIndex;
624     }
625     for (unsigned i :
626          llvm::seq<unsigned>(numFoldedDims.size(), argReplacements.size())) {
627       argReplacements[i] =
628           fusedEntryBlock->addArgument(originalRegion.getArgument(i).getType());
629     }
630     rewriter.mergeBlocks(fusedEntryBlock->getNextNode(), fusedEntryBlock,
631                          argReplacements);
632   }
633 
634   // Reshape the result values to their original shape if this is a collapsing
635   // reshape folded into its consumer.
636   SmallVector<Value, 1> resultVals;
637   for (auto result : llvm::enumerate(linalgOp.getOperation()->getResults())) {
638     if (!isExpanding &&
639         resultTypes[result.index()] != result.value().getType()) {
640       resultVals.push_back(rewriter.create<TensorReshapeOp>(
641           linalgOp.getLoc(), result.value().getType(),
642           fusedOp.getOperation()->getResult(result.index()),
643           resultReassociation[result.index()]));
644     } else {
645       resultVals.push_back(fusedOp.getOperation()->getResult(result.index()));
646     }
647   }
648   // Assuming a single result.
649   return resultVals;
650 }
651 
652 namespace {
653 
654 /// Pattern to fold tensor_reshape op with its consumer by using the source of
655 /// the reshape op as the operand in the consumer (instead of the result of the
656 /// tensor_reshapeop) when the tensor_reshape op is collapsing. The
657 /// corresponding index map in the consumer needs to be modified to linearize
658 /// the folded dimension.
659 ///
660 /// For example,
661 ///
662 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
663 /// %0 = linalg.tensor_reshape %arg0
664 ///        [affine_map<(i, j, k, l) -> (i)>, affine_map<(i, j, k, l) -> (j, k)>,
665 ///         affine_map<(i, j, k, l) -> (l)>]
666 ///      tensor<?x?x?xf32> into tensor<?x?x4x?xf32>
667 /// %1 = linalg.generic { indexing_maps = [#map0, #map0, #map0], ... }
668 ///        ins(%0, %arg1 : tensor<?x?x4x?xf32>, tensor<?x?x4x?xf32>) ...
669 ///        -> tensor<?x?x4x?xf32>
670 ///
671 /// can be folded into
672 ///
673 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1 * 4 + d2, d3)>
674 /// #map1 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
675 /// %0 = linalg.generic { indexing_maps = [#map0, #map1, #map1] ... }
676 ///        ins(%arg0, %arg1 : tensor<?x?x?xf32>, tensor<?x?x4x?xf32>) ...
677 ///        -> tensor<?x?x4x?xf32>
678 template <typename LinalgOpTy>
679 struct FoldProducerReshapeOpByLinearization
680     : public OpRewritePattern<LinalgOpTy> {
681   using OpRewritePattern<LinalgOpTy>::OpRewritePattern;
682 
683   LogicalResult matchAndRewrite(LinalgOpTy op,
684                                 PatternRewriter &rewriter) const override {
685     if (!op.hasTensorSemantics())
686       return failure();
687     LinalgOp linalgOp = cast<LinalgOp>(op.getOperation());
688     for (auto operand : llvm::enumerate(linalgOp.getInputs())) {
689       TensorReshapeOp reshapeOp =
690           operand.value().getDefiningOp<TensorReshapeOp>();
691       if (!reshapeOp ||
692           !isTensorReshapeOpFoldableByLinearization(
693               reshapeOp, linalgOp.getInputIndexingMap(operand.index()),
694               /*asProducer =*/true))
695         continue;
696 
697       // Compute the fused operands list,
698       SmallVector<Value, 2> fusedOperands(linalgOp.getInputs());
699       fusedOperands[operand.index()] = reshapeOp.src();
700 
701       // Compute indexing_maps for the fused operation. The indexing_maps for
702       // the operands of the consumers that arent fused are the same.
703       SmallVector<AffineMap, 4> fusedIndexMaps = llvm::to_vector<4>(
704           op.indexing_maps().template getAsValueRange<AffineMapAttr>());
705 
706       // Accepted consumer maps are either identity or permutation.
707       auto invMap = inversePermutation(fusedIndexMaps[operand.index()]);
708 
709       // Compute the indexing map to use for the result of the producer.
710       AffineMap modifiedMap =
711           linearizeCollapsedDims(invMap, reshapeOp.getResultType().getShape(),
712                                  reshapeOp.getReassociationMaps());
713       for (AffineExpr expr : modifiedMap.getResults()) {
714         if (!expr.isPureAffine())
715           return failure();
716       }
717       fusedIndexMaps[operand.index()] = modifiedMap;
718 
719       // Further check that the resulting index maps can be fused and
720       // inverted. Without this the resultant op is not legal.
721       if (!inversePermutation(concatAffineMaps(fusedIndexMaps)))
722         return op.emitRemark("fused op loop bound computation failed");
723 
724       rewriter.startRootUpdate(op);
725       op.getOperation()->setOperands(fusedOperands);
726       op.indexing_mapsAttr(rewriter.getAffineMapArrayAttr(fusedIndexMaps));
727       rewriter.finalizeRootUpdate(op);
728       if (reshapeOp.use_empty())
729         rewriter.eraseOp(reshapeOp);
730       return success();
731     }
732     return op.emitRemark("no fusion candidates found");
733   }
734 };
735 
736 /// Pattern to fuse a tensor_reshape op with its consumer
737 /// generic/indexed_generic op, when the reshape op is collapsing
738 /// dimensions. The dimensionality of the loop in the consumer is expanded.
739 template <typename GenericOpTy>
740 struct FoldWithProducerReshapeOpByExpansion
741     : public OpRewritePattern<GenericOpTy> {
742   using OpRewritePattern<GenericOpTy>::OpRewritePattern;
743 
744   LogicalResult matchAndRewrite(GenericOpTy genericOp,
745                                 PatternRewriter &rewriter) const override {
746     LinalgOp linalgOp = cast<LinalgOp>(genericOp.getOperation());
747     for (auto operand : llvm::enumerate(linalgOp.getInputs())) {
748       TensorReshapeOp reshapeOp =
749           operand.value().getDefiningOp<TensorReshapeOp>();
750       if (!reshapeOp)
751         continue;
752 
753       // Fold only if
754       // - The tensor reshape op is folding.
755       // - All constraints of fusing with reshape by expansion are met.
756       if (reshapeOp.getSrcType().getRank() <
757               reshapeOp.getResultType().getRank() ||
758           !isFusableWithReshapeByDimExpansion(linalgOp, operand.index()))
759         continue;
760 
761       Optional<SmallVector<Value, 1>> replacementValues =
762           fuseWithReshapeByExpansion(linalgOp, reshapeOp, operand.index(),
763                                      rewriter);
764       if (!replacementValues)
765         return failure();
766       rewriter.replaceOp(genericOp, replacementValues.getValue());
767       if (reshapeOp.use_empty())
768         rewriter.eraseOp(reshapeOp);
769       return success();
770     }
771     return failure();
772   }
773 };
774 
775 /// Pattern to fold tensor_reshape op with its producer. The corresponding index
776 /// map in the consumer needs to be modified to linearize the folded dimension.
777 struct FoldConsumerReshapeOpByLinearization
778     : public OpRewritePattern<TensorReshapeOp> {
779   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
780 
781   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
782                                 PatternRewriter &rewriter) const override {
783     LinalgOp producer = reshapeOp.src().getDefiningOp<LinalgOp>();
784     if (!producer ||
785         !isa<GenericOp, IndexedGenericOp>(producer.getOperation()) ||
786         !producer.hasTensorSemantics() || producer.getNumOutputs() != 1 ||
787         !isTensorReshapeOpFoldableByLinearization(
788             reshapeOp, producer.getOutputIndexingMap(0), /*asProducer =*/false))
789       return failure();
790     // The indexing_maps for the operands of the fused operation are same as
791     // those for the operands of the producer.
792     SmallVector<AffineMap, 4> fusedIndexMaps = llvm::to_vector<4>(
793         producer.indexing_maps().getAsValueRange<AffineMapAttr>());
794 
795     auto invMap = inversePermutation(producer.getOutputIndexingMap(0));
796 
797     // Compute the indexing map to use for the operand of the producer.
798     AffineMap modifiedMap =
799         linearizeCollapsedDims(invMap, reshapeOp.getSrcType().getShape(),
800                                reshapeOp.getReassociationMaps());
801     for (AffineExpr expr : modifiedMap.getResults()) {
802       if (!expr.isPureAffine())
803         return reshapeOp.emitRemark("fused op indexing map is not affine");
804     }
805     fusedIndexMaps.back() = modifiedMap;
806 
807     // Further check that the resulting index maps can be fused and
808     // inverted. Without this the resultant op is not legal.
809     if (!inversePermutation(concatAffineMaps(fusedIndexMaps)))
810       return reshapeOp.emitRemark("fused op loop bound computation failed");
811 
812     LinalgOp fusedOp = createLinalgOpOfSameType(
813         producer, rewriter, rewriter.getUnknownLoc(), reshapeOp.getResultType(),
814         /*inputs=*/producer.getInputs(),
815         /*outputBuffers=*/ValueRange{},
816         /*initTensors=*/ValueRange{}, // no init tensors for now.
817         rewriter.getAffineMapArrayAttr(fusedIndexMaps),
818         producer.iterator_types(),
819         /*doc=*/nullptr,
820         /*library_call=*/nullptr,
821         /*sparse=*/nullptr);
822     auto &fusedRegion = fusedOp.getOperation()->getRegion(0);
823     rewriter.cloneRegionBefore(producer.getOperation()->getRegion(0),
824                                fusedRegion, fusedRegion.begin());
825     rewriter.replaceOp(reshapeOp, fusedOp.getOperation()->getResults());
826     if (producer.use_empty())
827       rewriter.eraseOp(producer);
828     return success();
829   }
830 };
831 
832 /// Pattern to fold a tensor_reshape op with its producer generic op if the
833 /// tensor_reshape op is expanding, by expanding the dimensionality of the loop
834 /// in the producer op.
835 struct FoldReshapeWithGenericOpByExpansion
836     : public OpRewritePattern<TensorReshapeOp> {
837   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
838   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
839                                 PatternRewriter &rewriter) const override {
840     // Fold only if
841     // - The tensor reshape op is a expanding case.
842     // - All constraints of fusing with reshape by expansion are met.
843     if (reshapeOp.getSrcType().getRank() > reshapeOp.getResultType().getRank())
844       return failure();
845     LinalgOp producer = reshapeOp.src().getDefiningOp<LinalgOp>();
846     if (!producer || producer.getNumOutputs() != 1 ||
847         !isFusableWithReshapeByDimExpansion(producer, producer.getNumInputs()))
848       return failure();
849     Optional<SmallVector<Value, 1>> replacementValues =
850         fuseWithReshapeByExpansion(producer, reshapeOp, producer.getNumInputs(),
851                                    rewriter);
852     if (!replacementValues)
853       return failure();
854     rewriter.replaceOp(reshapeOp, replacementValues.getValue());
855     if (producer.use_empty())
856       rewriter.eraseOp(producer);
857     return success();
858   }
859 };
860 
861 /// Pattern to fold a GenericOp/IndexedGenericOp with a splat constant.
862 template <typename LinalgOpTy>
863 struct FoldSplatConstants : public OpRewritePattern<LinalgOpTy> {
864   using OpRewritePattern<LinalgOpTy>::OpRewritePattern;
865 
866   LogicalResult matchAndRewrite(LinalgOpTy op,
867                                 PatternRewriter &rewriter) const override {
868     if (!op.hasTensorSemantics())
869       return failure();
870     LinalgOp linalgOp = cast<LinalgOp>(op.getOperation());
871     for (auto operand : llvm::enumerate(linalgOp.getInputs())) {
872       ConstantOp constantOp = operand.value().getDefiningOp<ConstantOp>();
873       if (!constantOp ||
874           !constantOp.value().cast<DenseElementsAttr>().isSplat())
875         continue;
876 
877       // The indexing_maps for the operands of the fused operation are same as
878       // those for the operands of the linalgOp without the indexing map at
879       // operand.index()
880       SmallVector<AffineMap, 4> fusedIndexMaps = llvm::to_vector<4>(
881           linalgOp.indexing_maps().getAsValueRange<AffineMapAttr>());
882       fusedIndexMaps.erase(std::next(fusedIndexMaps.begin(), operand.index()));
883 
884       // The operands list is same as the linalgOp with the argument for
885       // constant index dropped.
886       SmallVector<Value, 4> fusedOperands(linalgOp.getInputs());
887       fusedOperands.erase(std::next(fusedOperands.begin(), operand.index()));
888 
889       // Create a constant scalar value from the splat constant.
890       Value scalarConstant = rewriter.create<ConstantOp>(
891           constantOp.getLoc(),
892           constantOp.value().cast<DenseElementsAttr>().getSplatValue());
893 
894       LinalgOp fusedOp = createLinalgOpOfSameType(
895           linalgOp, rewriter, rewriter.getUnknownLoc(),
896           linalgOp.getOperation()->getResultTypes(),
897           /*inputs=*/fusedOperands,
898           /*outputBuffers=*/ValueRange{},
899           /*initTensors=*/ValueRange{}, // no init tensors for now.
900           rewriter.getAffineMapArrayAttr(fusedIndexMaps),
901           linalgOp.iterator_types(),
902           /*doc=*/nullptr,
903           /*library_call=*/nullptr,
904           /*sparse=*/nullptr);
905 
906       // Map the block argument corresponding to the replaced argument with the
907       // scalar constant.
908       Region &linalgOpRegion = linalgOp.getOperation()->getRegion(0);
909       Block &entryBlock = *linalgOpRegion.begin();
910       unsigned argIndex = entryBlock.getNumArguments() -
911                           linalgOp.getNumInputs() + operand.index();
912       BlockAndValueMapping mapping;
913       mapping.map(entryBlock.getArgument(argIndex), scalarConstant);
914       Region &fusedRegion = fusedOp.getOperation()->getRegion(0);
915       rewriter.cloneRegionBefore(linalgOpRegion, fusedRegion,
916                                  fusedRegion.begin(), mapping);
917       rewriter.replaceOp(linalgOp, fusedOp.getOperation()->getResults());
918       if (constantOp.use_empty())
919         rewriter.eraseOp(constantOp);
920       return success();
921     }
922     return failure();
923   }
924 };
925 } // namespace
926 
927 Optional<SmallVector<Value, 1>>
928 mlir::linalg::fuseTensorOps(PatternRewriter &rewriter, Operation *consumer,
929                             unsigned consumerIdx) {
930   if (consumerIdx >= consumer->getNumOperands())
931     return llvm::None;
932   Operation *producer = consumer->getOperand(consumerIdx).getDefiningOp();
933   if (!producer || producer->getNumResults() != 1)
934     return llvm::None;
935 
936   // Fuse when consumer is GenericOp or IndexedGenericOp.
937   if (!isa<GenericOp, IndexedGenericOp>(consumer) ||
938       !isa<GenericOp, IndexedGenericOp>(producer))
939     return llvm::None;
940 
941   return fuseTensorOpsImpl(cast<LinalgOp>(producer), cast<LinalgOp>(consumer),
942                            consumerIdx, rewriter);
943 }
944 
945 namespace {
946 /// Patterns to fuse a generic op, with the producer of its operands.
947 template <typename LinalgOpTy>
948 struct FuseTensorOps : public OpRewritePattern<LinalgOpTy> {
949   using OpRewritePattern<LinalgOpTy>::OpRewritePattern;
950 
951   LogicalResult matchAndRewrite(LinalgOpTy op,
952                                 PatternRewriter &rewriter) const override {
953     // Find the first operand that is defined by another generic op on tensors.
954     for (auto operandNum :
955          llvm::seq<unsigned>(0, op.getOperation()->getNumOperands())) {
956       Operation *producer =
957           op.getOperation()->getOperand(operandNum).getDefiningOp();
958       if (!producer)
959         continue;
960       Optional<SmallVector<Value, 1>> fusedOpResults =
961           fuseTensorOps(rewriter, op, operandNum);
962       if (fusedOpResults) {
963         rewriter.replaceOp(op, *fusedOpResults);
964         if (producer->use_empty())
965           rewriter.eraseOp(producer);
966         return success();
967       }
968     }
969     return failure();
970   }
971 };
972 
973 /// Pass that fuses generic ops on tensors. Used only for testing.
974 struct FusionOfTensorOpsPass
975     : public LinalgFusionOfTensorOpsBase<FusionOfTensorOpsPass> {
976   void runOnOperation() override {
977     OwningRewritePatternList patterns;
978     Operation *op = getOperation();
979     populateLinalgTensorOpsFusionPatterns(op->getContext(), patterns);
980     applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns));
981   }
982 };
983 
984 /// Pass to test folding of reshape op with generic/indexed_generic ops by
985 /// linearization.
986 struct FoldReshapeOpsByLinearizationPass
987     : public LinalgFoldReshapeOpsByLinearizationBase<
988           FoldReshapeOpsByLinearizationPass> {
989   void runOnOperation() override {
990     OwningRewritePatternList patterns;
991     Operation *op = getOperation();
992     populateFoldReshapeOpsByLinearizationPatterns(op->getContext(), patterns);
993     applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns));
994   }
995 };
996 
997 } // namespace
998 
999 void mlir::populateFoldReshapeOpsByLinearizationPatterns(
1000     MLIRContext *context, OwningRewritePatternList &patterns) {
1001   patterns.insert<FoldProducerReshapeOpByLinearization<GenericOp>,
1002                   FoldProducerReshapeOpByLinearization<IndexedGenericOp>,
1003                   FoldConsumerReshapeOpByLinearization>(context);
1004 }
1005 
1006 void mlir::populateFoldReshapeOpsByExpansionPatterns(
1007     MLIRContext *context, OwningRewritePatternList &patterns) {
1008   patterns.insert<FoldReshapeWithGenericOpByExpansion,
1009                   FoldWithProducerReshapeOpByExpansion<GenericOp>,
1010                   FoldWithProducerReshapeOpByExpansion<IndexedGenericOp>>(
1011       context);
1012 }
1013 
1014 void mlir::populateLinalgTensorOpsFusionPatterns(
1015     MLIRContext *context, OwningRewritePatternList &patterns) {
1016   patterns.insert<FuseTensorOps<GenericOp>, FuseTensorOps<IndexedGenericOp>,
1017                   FoldSplatConstants<GenericOp>,
1018                   FoldSplatConstants<IndexedGenericOp>>(context);
1019   populateFoldReshapeOpsByExpansionPatterns(context, patterns);
1020   GenericOp::getCanonicalizationPatterns(patterns, context);
1021   IndexedGenericOp::getCanonicalizationPatterns(patterns, context);
1022   TensorReshapeOp::getCanonicalizationPatterns(patterns, context);
1023 }
1024 
1025 std::unique_ptr<Pass> mlir::createLinalgFusionOfTensorOpsPass() {
1026   return std::make_unique<FusionOfTensorOpsPass>();
1027 }
1028 
1029 std::unique_ptr<Pass> mlir::createFoldReshapeOpsByLinearizationPass() {
1030   return std::make_unique<FoldReshapeOpsByLinearizationPass>();
1031 }
1032