1 //===- ElementwiseOpFusion.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 <utility>
13 
14 #include "PassDetail.h"
15 #include "mlir/Dialect/Affine/IR/AffineOps.h"
16 #include "mlir/Dialect/Linalg/IR/Linalg.h"
17 #include "mlir/Dialect/Linalg/Passes.h"
18 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
19 #include "mlir/Dialect/Linalg/Utils/Utils.h"
20 #include "mlir/IR/AffineExpr.h"
21 #include "mlir/IR/AffineMap.h"
22 #include "mlir/IR/Matchers.h"
23 #include "mlir/IR/PatternMatch.h"
24 #include "mlir/Support/LLVM.h"
25 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
26 
27 using namespace mlir;
28 using namespace mlir::linalg;
29 
30 /// Append to `fusedOpIndexingMapAttrs` the indexing maps for the operands of
31 /// the `producer` to use in the fused operation given the indexing map of the
32 /// result of the producer in the consumer.
33 static AffineMap getIndexingMapOfProducerOperandsInCoordinatesOfFusedOp(
34     OpOperand *producerOpOperand, AffineMap producerResultIndexMap,
35     AffineMap fusedConsumerArgIndexMap) {
36   // The indexing map in the consumer op (fusedConsumerArgIndexMap) is a map
37   // from consumer loop -> consumer arg tensor index/producer result tensor
38   // index. The fused loop is same as the consumer loop. For each producer arg
39   // the indexing map to be computed is a map from consumer loop -> producer
40   // arg tensor index.
41   // producerResultIndexMap is a map from producer loop -> tensor index.
42   // Compute the inverse to get map from tensor index -> producer loop.
43   // The inverse is a map from producer result tensor index -> producer loop.
44   AffineMap invProducerResultIndexMap =
45       inversePermutation(producerResultIndexMap);
46   assert(invProducerResultIndexMap &&
47          "expected producer result indexig map to be invertible");
48 
49   LinalgOp producer = cast<LinalgOp>(producerOpOperand->getOwner());
50   // argMap is a map from producer loop -> producer arg tensor index.
51   AffineMap argMap = producer.getTiedIndexingMap(producerOpOperand);
52 
53   // Compose argMap with invProducerResultIndexMap to get a map from
54   // producer result tensor index -> producer arg tensor index.
55   AffineMap t1 = argMap.compose(invProducerResultIndexMap);
56 
57   // Compose t1 with fusedConsumerArgIndexMap gives an indexing map from
58   // consumer loop/ fused loop -> producer arg tensor index.
59   return t1.compose(fusedConsumerArgIndexMap);
60 }
61 
62 /// Conditions for elementwise fusion of generic operations.
63 static bool areElementwiseOpsFusable(GenericOp producer, GenericOp consumer,
64                                      OpOperand *consumerOpOperand) {
65   // Producer and consumer must have tensor semantics.
66   if (!producer.hasTensorSemantics() || !consumer.hasTensorSemantics())
67     return false;
68 
69   // Verify that
70   // - the producer has all "parallel" iterator type.
71   if (producer.getNumParallelLoops() != producer.getNumLoops())
72     return false;
73 
74   // Only allow fusing the producer of an input operand for now.
75   // TODO: allow fusing the producer of an output operand.
76   if (!consumer.isInputTensor(consumerOpOperand))
77     return false;
78 
79   // Get the consumer index map. The number of results of the consumer index
80   // map must match the number of loops of the producer.
81   AffineMap consumerIndexMap = consumer.getTiedIndexingMap(consumerOpOperand);
82   if (consumerIndexMap.getNumResults() != producer.getNumLoops())
83     return false;
84 
85   // Currently support only operations with single result.
86   if (producer.getNumOutputs() != 1)
87     return false;
88 
89   // Finally the index_map for the result must be invertible. For now just
90   // verify it is a permutation.
91   AffineMap producerResultIndexMap =
92       producer.getTiedIndexingMap(producer.getOutputOperand(0));
93   if (!producerResultIndexMap.isPermutation())
94     return false;
95 
96   // Ensure that the fusion does not remove size information required to
97   // get the loop bounds. For non-reduction generics, this is trivially the
98   // case due to the output operand. For reductions, we need to check that after
99   // the fusion, each loop dimension has at least one input that defines it.
100   if ((consumer.getNumReductionLoops())) {
101     llvm::BitVector coveredDims(consumer.getNumLoops(), false);
102 
103     auto addToCoveredDims = [&](AffineMap map) {
104       for (auto result : map.getResults())
105         if (auto dimExpr = result.dyn_cast<AffineDimExpr>())
106           coveredDims[dimExpr.getPosition()] = true;
107     };
108 
109     for (auto pair :
110          llvm::zip(consumer->getOperands(), consumer.getIndexingMaps())) {
111       Value operand = std::get<0>(pair);
112       if (operand == consumerOpOperand->get())
113         continue;
114       AffineMap operandMap = std::get<1>(pair);
115       addToCoveredDims(operandMap);
116     }
117 
118     for (OpOperand *operand : producer.getInputOperands()) {
119       AffineMap newIndexingMap =
120           getIndexingMapOfProducerOperandsInCoordinatesOfFusedOp(
121               operand, producerResultIndexMap, consumerIndexMap);
122       addToCoveredDims(newIndexingMap);
123     }
124     if (!coveredDims.all())
125       return false;
126   }
127 
128   return true;
129 }
130 
131 /// Generate the region of the fused tensor operation. The region of the fused
132 /// op must be empty.
133 static void
134 generateFusedElementwiseOpRegion(PatternRewriter &rewriter, GenericOp fusedOp,
135                                  AffineMap consumerToProducerLoopsMap,
136                                  OpOperand *consumerOpOperand,
137                                  unsigned nloops) {
138   auto producer = cast<GenericOp>(consumerOpOperand->get().getDefiningOp());
139   auto consumer = cast<GenericOp>(consumerOpOperand->getOwner());
140   // Build the region of the fused op.
141   Block &producerBlock = producer->getRegion(0).front();
142   Block &consumerBlock = consumer->getRegion(0).front();
143   Block *fusedBlock = new Block();
144   fusedOp.region().push_back(fusedBlock);
145   BlockAndValueMapping mapper;
146   OpBuilder::InsertionGuard guard(rewriter);
147   rewriter.setInsertionPointToStart(fusedBlock);
148 
149   // 2. Add an index operation for every fused loop dimension and use the
150   // `consumerToProducerLoopsMap` to map the producer indices.
151   if (producer.hasIndexSemantics()) {
152     // Add an index operation for every fused loop dimension.
153     unsigned numFusedOpLoops =
154         std::max(producer.getNumLoops(), consumer.getNumLoops());
155     SmallVector<Value> fusedIndices;
156     fusedIndices.reserve(numFusedOpLoops);
157     llvm::transform(llvm::seq<uint64_t>(0, numFusedOpLoops),
158                     std::back_inserter(fusedIndices), [&](uint64_t dim) {
159                       return rewriter.create<IndexOp>(producer.getLoc(), dim);
160                     });
161     for (IndexOp indexOp :
162          llvm::make_early_inc_range(producerBlock.getOps<IndexOp>())) {
163       Value newIndex = rewriter.create<mlir::AffineApplyOp>(
164           producer.getLoc(),
165           consumerToProducerLoopsMap.getSubMap(indexOp.dim()), fusedIndices);
166       mapper.map(indexOp.getResult(), newIndex);
167     }
168   }
169   // TODO: allow fusing the producer of an output operand.
170   assert(consumer.isInputTensor(consumerOpOperand) &&
171          "expected producer of input operand");
172   // 3. Consumer input operands up to consumerIdx (exclusive).
173   for (BlockArgument bbArg : consumerBlock.getArguments().take_front(
174            consumerOpOperand->getOperandNumber())) // input assumption.
175     mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType()));
176 
177   // Replacing consumerIdx requires getting the cloned, yielded, value from
178   // the (cloned) producer block. This happens in step 9.
179 
180   // 4. Splice in producer's input operands.
181   for (BlockArgument bbArg :
182        producerBlock.getArguments().take_front(producer.getNumInputs()))
183     mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType()));
184 
185   // 4.b. Producer output operand/map that is fused needs to be mapped to the
186   // producer bbArg if it is an "initTensor" (i.e. its value is actually read).
187   assert(producer->getNumResults() == 1 && "expected single result producer");
188   if (producer.isInitTensor(producer.getOutputOperand(0))) {
189     BlockArgument bbArg = producerBlock.getArguments()
190                               .drop_front(producer.getNumInputs())
191                               // TODO: bbArg index of
192                               .front();
193     mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType()));
194   }
195   // 5. Remaining consumer's input operands (drop past index `consumerIdx`).
196   for (BlockArgument bbArg :
197        consumerBlock.getArguments()
198            .take_front(consumer.getNumInputs())
199            .drop_front(consumerOpOperand->getOperandNumber() + 1))
200     mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType()));
201   // 6. All of consumer's output operands.
202   for (BlockArgument bbArg :
203        consumerBlock.getArguments().take_back(consumer.getNumOutputs()))
204     mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType()));
205   // 7. All of producer's output operands except the one fused.
206   // TODO: allow fusion of multi-result producers.
207   assert(producer->getNumResults() == 1 && "expected single result producer");
208 
209   // 8. Clone all producer operations except for the yield and index operations
210   // to the fused operation.
211   for (auto &op : producerBlock.without_terminator()) {
212     if (!isa<IndexOp>(op))
213       rewriter.clone(op, mapper);
214   }
215   // 9. Now we can map the consumerBlock's `consumerIdx` block argument. Just
216   // forward the yield operand.
217   auto yieldOp = cast<linalg::YieldOp>(producerBlock.getTerminator());
218   // TODO: allow fusion of multi-result producers.
219   assert(producer->getNumResults() == 1 && "expected single result producer");
220   unsigned producerResultNumber = 0;
221   Value replacement =
222       mapper.lookupOrDefault(yieldOp.getOperand(producerResultNumber));
223   // Sanity checks, if replacement is not already in the mapper then it must be
224   // produced outside.
225   if (replacement == yieldOp.getOperand(producerResultNumber)) {
226     if (auto bb = replacement.dyn_cast<BlockArgument>())
227       assert(bb.getOwner() != &producerBlock &&
228              "yielded block argument must have been mapped");
229     else
230       assert(!producer->isAncestor(replacement.getDefiningOp()) &&
231              "yielded value must have been mapped");
232   }
233   mapper.map(consumerBlock.getArgument(consumerOpOperand->getOperandNumber()),
234              replacement);
235   // 10. Clone operations from the consumer to the fused op.
236   for (auto &op : consumerBlock.getOperations())
237     rewriter.clone(op, mapper);
238 
239   // Sanity checks.
240   assert(fusedBlock->getNumArguments() == fusedOp.getNumOperands() &&
241          "Ill-formed GenericOp region");
242 }
243 
244 static Optional<SmallVector<Value>>
245 fuseElementwiseOpsImpl(GenericOp producer, OpOperand *consumerOpOperand,
246                        const ControlElementwiseOpsFusionFn &controlFn,
247                        PatternRewriter &rewriter) {
248   auto consumer = cast<GenericOp>(consumerOpOperand->getOwner());
249   if (!areElementwiseOpsFusable(producer, consumer, consumerOpOperand) ||
250       !controlFn(producer->getResult(0), *consumerOpOperand))
251     return llvm::None;
252 
253   // TODO: allow fusing the producer of an output operand.
254   assert(consumer.isInputTensor(consumerOpOperand) &&
255          "expected producer of input operand");
256 
257   // Compute the fused operands list and indexing maps.
258   SmallVector<Value> fusedOperands;
259   SmallVector<AffineMap> fusedIndexMaps;
260   fusedOperands.reserve(producer->getNumOperands() +
261                         consumer->getNumOperands());
262   fusedIndexMaps.reserve(producer->getNumOperands() +
263                          consumer->getNumOperands());
264   // In the following, numbering matches that of `generateFusedTensorOpRegion`.
265   // 3. Consumer input operands/maps up to consumerIdx (exclusive).
266   SmallVector<OpOperand *> consumerInputs = consumer.getInputOperands();
267   SmallVector<OpOperand *>::iterator it =
268       llvm::find(consumerInputs, consumerOpOperand);
269   assert(it != consumerInputs.end() && "expected to find the consumer operand");
270   for (OpOperand *opOperand : llvm::make_range(consumerInputs.begin(), it)) {
271     fusedOperands.push_back(opOperand->get());
272     fusedIndexMaps.push_back(consumer.getTiedIndexingMap(opOperand));
273   }
274   // 4. Splice in producer's input operands/maps.
275   assert(producer->getNumResults() == 1 && "expected single result producer");
276   AffineMap producerResultIndexMap =
277       producer.getTiedIndexingMap(producer.getOutputOperand(0));
278   for (OpOperand *opOperand : producer.getInputOperands()) {
279     fusedOperands.push_back(opOperand->get());
280     // Compute indexing maps for the producer args in the fused operation.
281     AffineMap map = getIndexingMapOfProducerOperandsInCoordinatesOfFusedOp(
282         opOperand, producerResultIndexMap,
283         consumer.getTiedIndexingMap(consumerOpOperand));
284     fusedIndexMaps.push_back(map);
285   }
286   // 4.b. Producer output operand/map that is fused needs to be passed if it is
287   // an "initTensor" (i.e. its value is actually read).
288   assert(producer->getNumResults() == 1 && "expected single result producer");
289   if (producer.isInitTensor(producer.getOutputOperand(0))) {
290     fusedOperands.push_back(producer.getOutputOperand(0)->get());
291     // Compute indexing maps for the producer args in the fused operation.
292     AffineMap map = getIndexingMapOfProducerOperandsInCoordinatesOfFusedOp(
293         producer.getOutputOperand(0), producerResultIndexMap,
294         consumer.getTiedIndexingMap(consumerOpOperand));
295     fusedIndexMaps.push_back(map);
296   }
297   // 5. Remaining consumer's input operands/maps (drop past index
298   // `consumerIdx`).
299   for (OpOperand *opOperand :
300        llvm::make_range(std::next(it), consumerInputs.end())) {
301     fusedOperands.push_back(opOperand->get());
302     fusedIndexMaps.push_back(consumer.getTiedIndexingMap(opOperand));
303   }
304   // 6. All of consumer's output operands (skip operands: added by the builder).
305   for (OpOperand *opOperand : consumer.getOutputOperands())
306     fusedIndexMaps.push_back(consumer.getTiedIndexingMap(opOperand));
307   // 7. All of producer's output operands/maps except the one fused.
308   // TODO: allow fusion of multi-result producers.
309   assert(producer->getNumResults() == 1 && "expected single result producer");
310 
311   // Generate the fused op.
312   SmallVector<Value> consumerOutputs = consumer.getOutputOperands();
313   auto fusedOp = rewriter.create<GenericOp>(
314       consumer.getLoc(), consumer->getResultTypes(),
315       /*inputs=*/fusedOperands,
316       // TODO: handle outputs.
317       consumerOutputs, rewriter.getAffineMapArrayAttr(fusedIndexMaps),
318       consumer.iterator_types(),
319       /*doc=*/nullptr,
320       /*library_call=*/nullptr);
321 
322   // Construct an AffineMap from consumer loops to producer loops.
323   // consumer loop -> tensor index
324   AffineMap consumerResultIndexMap =
325       consumer.getTiedIndexingMap(consumerOpOperand);
326   // tensor index -> producer loop
327   AffineMap invProducerResultIndexMap =
328       inversePermutation(producerResultIndexMap);
329   assert(invProducerResultIndexMap &&
330          "expected producer result indexig map to be invertible");
331   // consumer loop -> producer loop
332   AffineMap consumerToProducerLoopsMap =
333       invProducerResultIndexMap.compose(consumerResultIndexMap);
334 
335   generateFusedElementwiseOpRegion(rewriter, fusedOp,
336                                    consumerToProducerLoopsMap,
337                                    consumerOpOperand, consumer.getNumLoops());
338   return SmallVector<Value>(fusedOp->getResults());
339 }
340 
341 /// Linearize the expressions in `sourceMap` based on the `reassociationMaps`
342 /// provided, given the shape of the source tensor that corresponds to the
343 /// `sourceMap`. Note that this implicitly assumes that the tensors dimensions
344 /// are "row-major" ordered logically.
345 ///
346 /// For example:
347 ///
348 /// %0 = op ... : tensor<?x?x4x5xf32>
349 /// with output index_map `affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>`
350 ///
351 /// and reshape:
352 /// %1 = tensor.collapse_shape %0 [[0], [0, 1, 2]] :
353 ///        tensor<?x?x4x5xf32> into tensor<?x?xf32>
354 ///
355 /// would be rewritten into:
356 /// %0 = op ... : tensor<?x?x4x5xf32>
357 /// with output index_map
358 ///   `affine_map<(d0, d1, d2, d3) -> (d0, d1 * 20 + d2 * 5 + d3)>`
359 template <typename TensorReshapeOp>
360 static AffineMap linearizeCollapsedDims(AffineMap sourceMap,
361                                         TensorReshapeOp reshapeOp) {
362   constexpr bool isExpanding =
363       std::is_same<TensorReshapeOp, tensor::ExpandShapeOp>::value;
364   ArrayRef<int64_t> sourceShape =
365       (isExpanding ? reshapeOp.getResultType().getShape()
366                    : reshapeOp.getSrcType().getShape());
367   SmallVector<AffineExpr> resultExprs;
368   ArrayRef<AffineExpr> sourceExprs = sourceMap.getResults();
369   MLIRContext *context = sourceMap.getContext();
370 
371   // Compute the result exprs based on the reassociation maps.
372   for (auto &indices : reshapeOp.getReassociationIndices()) {
373     // Assume that they are in-order and contiguous (already checked in
374     // verifier).
375     assert(!indices.empty());
376     SmallVector<int64_t> sizes;
377     SmallVector<AffineExpr> dimExprs;
378     for (auto en : llvm::zip(sourceShape.slice(indices[0], indices.size()),
379                              sourceExprs.slice(indices[0], indices.size()))) {
380       if (std::get<0>(en) == 1)
381         continue;
382       sizes.push_back(std::get<0>(en));
383       dimExprs.push_back(std::get<1>(en));
384     }
385     AffineExpr linearizedExpr =
386         makeCanonicalStridedLayoutExpr(sizes, dimExprs, context);
387     resultExprs.push_back(linearizedExpr);
388   }
389   // The new affine map cannot drop unused dimension but some new symbols may
390   // have been added. Create a map with at least as many dimensions/symbols as
391   // the original affine map.
392   int64_t maxDim = -1;
393   int64_t maxSym = -1;
394   getMaxDimAndSymbol<SmallVector<AffineExpr>>({resultExprs}, maxDim, maxSym);
395   unsigned numDims = std::max(unsigned(maxDim + 1), sourceMap.getNumDims());
396   unsigned numSyms = std::max(unsigned(maxSym + 1), sourceMap.getNumSymbols());
397   return AffineMap::get(numDims, numSyms, resultExprs, context);
398 }
399 
400 // tensor::ExpandShapeOp is fusable with its consumer (i.e. reshape as a
401 // producer). Fusing when operand has higher rank will require use of mods and
402 // divs in the indexing maps of the fused op which would make it non-invertible.
403 static bool isTensorReshapeOpFoldableByLinearization(
404     tensor::ExpandShapeOp expandOp, AffineMap useIndexMap, bool asProducer) {
405   if (!asProducer)
406     return false;
407   return useIndexMap.isPermutation();
408 }
409 
410 // tensor::CollapseShapeOp is fusable with its producer (i.e. reshape as a
411 // consumer).
412 static bool
413 isTensorReshapeOpFoldableByLinearization(tensor::CollapseShapeOp collapseOp,
414                                          AffineMap useIndexMap,
415                                          bool asProducer) {
416   if (asProducer)
417     return false;
418   return useIndexMap.isPermutation();
419 }
420 
421 /// Check if the reshape operation is only expansion into/collapsing of
422 /// unit-dimension.
423 template <typename TensorReshapeOp>
424 static bool isUnitDimExpansionOnly(TensorReshapeOp reshapeOp) {
425   constexpr bool isExpanding =
426       std::is_same<TensorReshapeOp, tensor::ExpandShapeOp>::value;
427   ArrayRef<int64_t> expandedShape =
428       (isExpanding ? reshapeOp.getResultType().getShape()
429                    : reshapeOp.getSrcType().getShape());
430   for (auto &indices : reshapeOp.getReassociationIndices()) {
431     unsigned numUnitDims = 0;
432     for (int64_t position : indices)
433       if (expandedShape[position] == 1)
434         numUnitDims++;
435     if (numUnitDims != indices.size() - 1)
436       return false;
437   }
438   return true;
439 }
440 
441 /// Conditions for folding a generic operation with a reshape op by expanding
442 /// the iteration space dimensionality for tensor operations. These are
443 /// preconditions assumed by `foldReshapeByDimExpansion` which implements the
444 /// following fusion pattern.
445 ///
446 ///  Consider
447 ///
448 ///  %c = linalg.generic ins(%a, %b : memref<?x?x?xf32>, memref<?x?xf32>)
449 ///         indexing_maps = [affine_map<(d0, d1, d2) -> (d1, d0, d2)>,
450 ///                          affine_map<(d0, d1, d2) -> (d1, d2)>,
451 ///                          affine_map<(d0, d1, d2) -> (d0, d2, d1)>]
452 ///  %d = tensor.expand_shape %c [[0, 1], [2], [3, 4, 5]]
453 ///       : tensor<?x?x?xf32> into tensor<?x?x?x?x?x?xf32>
454 ///
455 ///  The reshape can be folded into the `genericOp` if its loop dimensionality
456 ///  is increased to match the result (operand) of the tensor_expand_shape.
457 ///  The indexing_map of the fused tensor in the `genericOp` and the
458 ///  reassociation map helps compute the indexing maps of the modified op.
459 ///  For the above example, based on the reassociation map it
460 ///  can be concluded that
461 ///
462 ///  - The loop used to access the first dimension of the fused tensor is split
463 ///    into two.
464 ///  - The loop used to access the second dimension of the fused tensor is kept
465 ///    as is.
466 ///  - The loop used to access the third dimension of the fused tensor is split
467 ///    into three.
468 ///
469 ///  i.e. (e0, e1, e2, e3, e4) is the domain of the indexing map of the modified
470 ///  op, then
471 ///
472 ///   d0 -> e0, e1
473 ///   d1 -> e2, e3, e4
474 ///   d2 -> e5
475 ///
476 ///  substituting this, the generic op can be rewritten as
477 ///
478 ///  %d = linalg.generic ins(%0, %1 : )
479 ///        indexing_maps =
480 ///         [affine_map<(e0, e1, e2, e3, e4, e5) -> (e2, e3, e4, e0, e1, e5)>,
481 ///          affine_map<(e0, e1, e2, e3, e4, e5) -> (e2, e3, e4, e5)>,
482 ///          affine_map<(e0, e1, e2, e3, e4, e5) -> (e0, e1, e5, e2, e3, e4)>]
483 ///
484 ///  Since operands to the linalg generic are now 5D, reshapes can be introduced
485 ///  to make it consistent
486 ///
487 ///  %0 = tensor.expand_shape %a [[0, 1, 2], [3, 4], [5]]
488 ///       : tensor<?x?x?xf32> into tensor<?x?x?x?x?x?xf32>
489 ///  %1 = tensor.expand_shape %b [[0, 1, 2], [3]]
490 ///       : tensor<?x?x?xf32> into tensor<?x?x?x?xf32>
491 ///
492 ///  The added reshapes are again expanding patterns, so they will get fused
493 ///  with its producers if possible.
494 static bool isFusableWithReshapeByDimExpansion(GenericOp genericOp,
495                                                OpOperand *fusableOpOperand) {
496   // Is fusable only if:
497   // - All the indexing maps for operands and results are projected
498   //   permutations.
499   // - The fused tensor is not a scalar.
500   // - All the loops are parallel loops.
501   return genericOp.hasTensorSemantics() &&
502          llvm::all_of(genericOp.indexing_maps().getValue(),
503                       [](Attribute attr) {
504                         return attr.cast<AffineMapAttr>()
505                             .getValue()
506                             .isProjectedPermutation();
507                       }) &&
508          genericOp.getTiedIndexingMap(fusableOpOperand).getNumResults() > 0 &&
509          llvm::all_of(genericOp.iterator_types(), [](Attribute attr) {
510            return attr.cast<StringAttr>().getValue() ==
511                   getParallelIteratorTypeName();
512          });
513 }
514 
515 namespace {
516 /// Information needed to expand a generic operation to fold the reshape with
517 /// it.
518 class ExpansionInfo {
519 public:
520   // Computes the mapping from original dimensions of the op to the dimensions
521   // of the expanded op given the `indexingMap` of the fused operand/result of
522   // the generic op, the `reassocationMaps` of the reshape op and the shape of
523   // the expanded op.
524   LogicalResult compute(LinalgOp linalgOp, OpOperand *fusableOpOperand,
525                         ArrayRef<AffineMap> reassociationMaps,
526                         ArrayRef<int64_t> expandedShape,
527                         PatternRewriter &rewriter);
528   unsigned getOrigOpNumDims() const { return reassociation.size(); }
529   unsigned getExpandedOpNumDims() const { return expandedOpNumDims; }
530   ReassociationIndicesRef getExpandedDims(unsigned i) const {
531     return reassociation[i];
532   }
533   ArrayRef<int64_t> getExpandedShapeOfDim(unsigned i) const {
534     return expandedShapeMap[i];
535   }
536 
537 private:
538   /// Reassociation from the dimensions in the original operation to the
539   /// dimension of the expanded operation.
540   SmallVector<ReassociationIndices> reassociation;
541   /// Mapping from extent of loops in the original operation, to the extent of
542   /// loops in the expanded operation.
543   SmallVector<SmallVector<int64_t>> expandedShapeMap;
544   unsigned expandedOpNumDims;
545 };
546 } // namespace
547 
548 LogicalResult ExpansionInfo::compute(LinalgOp linalgOp,
549                                      OpOperand *fusableOpOperand,
550                                      ArrayRef<AffineMap> reassociationMaps,
551                                      ArrayRef<int64_t> expandedShape,
552                                      PatternRewriter &rewriter) {
553   if (reassociationMaps.empty())
554     return failure();
555   AffineMap fusedIndexMap = linalgOp.getTiedIndexingMap(fusableOpOperand);
556 
557   Optional<SmallVector<int64_t, 4>> originalLoopRange =
558       linalgOp.getStaticLoopRanges();
559   if (!originalLoopRange)
560     return rewriter.notifyMatchFailure(linalgOp, "unable to find loop range");
561 
562   reassociation.clear();
563   expandedShapeMap.clear();
564   // Compute the number of dimension in the expanded op that correspond to each
565   // dimension of the original op.
566   SmallVector<unsigned> numExpandedDims(fusedIndexMap.getNumDims(), 1);
567   expandedShapeMap.resize(fusedIndexMap.getNumDims());
568   for (const auto &resultExpr : llvm::enumerate(fusedIndexMap.getResults())) {
569     unsigned pos = resultExpr.value().cast<AffineDimExpr>().getPosition();
570     AffineMap foldedDims = reassociationMaps[resultExpr.index()];
571     numExpandedDims[pos] = foldedDims.getNumResults();
572     ArrayRef<int64_t> shape =
573         expandedShape.slice(foldedDims.getDimPosition(0), numExpandedDims[pos]);
574     expandedShapeMap[pos].assign(shape.begin(), shape.end());
575   }
576   // The remaining dimensions remain the same.
577   for (unsigned i : llvm::seq<unsigned>(0, fusedIndexMap.getNumDims()))
578     if (expandedShapeMap[i].empty())
579       expandedShapeMap[i] = {(*originalLoopRange)[i]};
580 
581   // Compute reassociation map from the original op to the expanded op.
582   unsigned sum = 0;
583   reassociation.reserve(fusedIndexMap.getNumDims());
584   for (const auto &numFoldedDim : llvm::enumerate(numExpandedDims)) {
585     auto seq = llvm::seq<int64_t>(sum, sum + numFoldedDim.value());
586     reassociation.emplace_back(seq.begin(), seq.end());
587     sum += numFoldedDim.value();
588   }
589   expandedOpNumDims = sum;
590   return success();
591 }
592 
593 /// Epanding the body of a linalg operation requires adaptations of the accessed
594 /// loop indices. Specifically, access of indices in the original operation need
595 /// to be replaced with linearizations of indices in the expanded op. That
596 /// requires the shape of the expanded dimensions to be static (at least all but
597 /// the most significant). For now check that these are all statically sized.
598 /// Note that this could be extended to handle dynamic case, but the
599 /// implementation below uses `affine.apply` which seems to have issues when the
600 /// shapes are not static.
601 LogicalResult isGenericOpExpandable(GenericOp genericOp,
602                                     const ExpansionInfo &expansionInfo,
603                                     PatternRewriter &rewriter) {
604   if (!genericOp.hasIndexSemantics())
605     return success();
606   for (unsigned i : llvm::seq<unsigned>(0, expansionInfo.getOrigOpNumDims())) {
607     ArrayRef<int64_t> expandedShape = expansionInfo.getExpandedShapeOfDim(i);
608     if (expandedShape.size() == 1)
609       continue;
610     for (int64_t shape : expandedShape.drop_front()) {
611       if (ShapedType::isDynamic(shape)) {
612         return rewriter.notifyMatchFailure(
613             genericOp, "cannot expand due to index semantics and dynamic dims");
614       }
615     }
616   }
617   return success();
618 }
619 
620 /// Return the indexing map to use in the expanded op for a given the
621 /// `indexingMap` of the original operation.
622 static AffineMap
623 getIndexingMapInExpandedOp(OpBuilder &builder, AffineMap indexingMap,
624                            const ExpansionInfo &expansionInfo) {
625   SmallVector<AffineExpr> newExprs;
626   for (AffineExpr expr : indexingMap.getResults()) {
627     unsigned pos = expr.cast<AffineDimExpr>().getPosition();
628     SmallVector<AffineExpr, 4> expandedExprs = llvm::to_vector<4>(
629         llvm::map_range(expansionInfo.getExpandedDims(pos), [&](int64_t v) {
630           return builder.getAffineDimExpr(static_cast<unsigned>(v));
631         }));
632     newExprs.append(expandedExprs.begin(), expandedExprs.end());
633   }
634   return AffineMap::get(expansionInfo.getExpandedOpNumDims(),
635                         indexingMap.getNumSymbols(), newExprs,
636                         builder.getContext());
637 }
638 
639 /// Return the type of the operand/result to use in the expanded op given the
640 /// type in the original op.
641 static RankedTensorType getExpandedType(RankedTensorType originalType,
642                                         AffineMap indexingMap,
643                                         const ExpansionInfo &expansionInfo) {
644   SmallVector<int64_t> expandedShape;
645   for (AffineExpr expr : indexingMap.getResults()) {
646     unsigned dim = expr.cast<AffineDimExpr>().getPosition();
647     auto dimExpansion = expansionInfo.getExpandedShapeOfDim(dim);
648     expandedShape.append(dimExpansion.begin(), dimExpansion.end());
649   }
650   return RankedTensorType::get(expandedShape, originalType.getElementType());
651 }
652 
653 /// Returns the reassociation maps to use in the `tensor.expand_shape`
654 /// operation to convert the operands of the original operation to operands of
655 /// the expanded operation. The same method is used to compute the
656 /// `tensor.collapse_shape` used to collapse the result of the expanded
657 /// op to get the value that can replace all uses of the results of the original
658 /// op.
659 static SmallVector<ReassociationIndices>
660 getReassociationForExpansion(AffineMap indexingMap,
661                              const ExpansionInfo &expansionInfo) {
662   SmallVector<ReassociationIndices> reassociation;
663   unsigned numReshapeDims = 0;
664   for (AffineExpr expr : indexingMap.getResults()) {
665     unsigned dim = expr.cast<AffineDimExpr>().getPosition();
666     auto numExpandedDims = expansionInfo.getExpandedDims(dim).size();
667     SmallVector<int64_t, 2> indices = llvm::to_vector<2>(
668         llvm::seq<int64_t>(numReshapeDims, numReshapeDims + numExpandedDims));
669     reassociation.emplace_back(std::move(indices));
670     numReshapeDims += numExpandedDims;
671   }
672   return reassociation;
673 }
674 
675 /// Update the body of an expanded linalg operation having index semantics. The
676 /// indices of the original operation need to be recovered by linearizing the
677 /// indices of the correspoding dimensions of the expanded operation. For now it
678 /// is assumed that the shapes of the expanded operation needed for
679 /// linearization are static.
680 static void updateExpandedGenericOpRegion(PatternRewriter &rewriter,
681                                           Location loc, Region &fusedRegion,
682                                           const ExpansionInfo &expansionInfo) {
683   // Replace the original indices by the linearization of the expanded indices.
684   for (IndexOp indexOp :
685        llvm::make_early_inc_range(fusedRegion.front().getOps<IndexOp>())) {
686     ArrayRef<int64_t> expandedDims =
687         expansionInfo.getExpandedDims(indexOp.dim());
688     assert(!expandedDims.empty() && "expected valid expansion info");
689 
690     // Skip index operations that are not affected by the expansion.
691     if (expandedDims.size() == 1 &&
692         expandedDims.front() == (int64_t)indexOp.dim())
693       continue;
694 
695     // Linearize the expanded indices of the original index dimension.
696     OpBuilder::InsertionGuard guard(rewriter);
697     rewriter.setInsertionPointAfter(indexOp);
698     ArrayRef<int64_t> expandedDimsShape =
699         expansionInfo.getExpandedShapeOfDim(indexOp.dim()).drop_front();
700     SmallVector<Value> expandedIndices;
701     expandedIndices.reserve(expandedDims.size() - 1);
702     llvm::transform(
703         expandedDims.drop_front(), std::back_inserter(expandedIndices),
704         [&](int64_t dim) { return rewriter.create<IndexOp>(loc, dim); });
705     Value newIndex = rewriter.create<IndexOp>(loc, expandedDims.front());
706     for (auto it : llvm::zip(expandedDimsShape, expandedIndices)) {
707       assert(!ShapedType::isDynamic(std::get<0>(it)));
708       AffineExpr idx, acc;
709       bindDims(rewriter.getContext(), idx, acc);
710       newIndex = rewriter.create<AffineApplyOp>(
711           indexOp.getLoc(), idx + acc * std::get<0>(it),
712           ValueRange{std::get<1>(it), newIndex});
713     }
714     rewriter.replaceOp(indexOp, newIndex);
715   }
716 }
717 
718 /// Implements the fusion of a tensor_collapse_shape or a tensor_expand_shape op
719 /// and a generic op as explained in `isFusableWithReshapeByExpansion`. Assumes
720 /// that those conditions have been satisfied.
721 static Optional<SmallVector<Value>>
722 fuseWithReshapeByExpansion(GenericOp genericOp, Operation *reshapeOp,
723                            OpOperand *fusableOpOperand,
724                            PatternRewriter &rewriter) {
725   assert(isFusableWithReshapeByDimExpansion(genericOp, fusableOpOperand) &&
726          "preconditions for fuse operation failed");
727   // Check if reshape is expanding or collapsing.
728   auto expandingReshapeOp = dyn_cast<tensor::ExpandShapeOp>(*reshapeOp);
729   auto collapsingReshapeOp = dyn_cast<tensor::CollapseShapeOp>(*reshapeOp);
730   bool isExpanding = (expandingReshapeOp != nullptr);
731   RankedTensorType expandedType = isExpanding
732                                       ? expandingReshapeOp.getResultType()
733                                       : collapsingReshapeOp.getSrcType();
734 
735   ExpansionInfo expansionInfo;
736   if (failed(expansionInfo.compute(
737           genericOp, fusableOpOperand,
738           isExpanding ? expandingReshapeOp.getReassociationMaps()
739                       : collapsingReshapeOp.getReassociationMaps(),
740           expandedType.getShape(), rewriter)))
741     return llvm::None;
742 
743   if (failed(isGenericOpExpandable(genericOp, expansionInfo, rewriter)))
744     return llvm::None;
745 
746   SmallVector<AffineMap, 4> expandedOpIndexingMaps = llvm::to_vector<4>(
747       llvm::map_range(genericOp.getIndexingMaps(), [&](AffineMap m) {
748         return getIndexingMapInExpandedOp(rewriter, m, expansionInfo);
749       }));
750 
751   SmallVector<Value> expandedOpOperands;
752   expandedOpOperands.reserve(genericOp.getNumInputs());
753   for (OpOperand *opOperand : genericOp.getInputOperands()) {
754     if (opOperand == fusableOpOperand) {
755       expandedOpOperands.push_back(isExpanding ? expandingReshapeOp.src()
756                                                : collapsingReshapeOp.src());
757       continue;
758     }
759     if (genericOp.isInputTensor(opOperand)) {
760       AffineMap indexingMap = genericOp.getTiedIndexingMap(opOperand);
761       RankedTensorType expandedOperandType =
762           getExpandedType(opOperand->get().getType().cast<RankedTensorType>(),
763                           indexingMap, expansionInfo);
764       if (expandedOperandType != opOperand->get().getType()) {
765         // Reshape the operand to get the right type.
766         SmallVector<ReassociationIndices> reassociation =
767             getReassociationForExpansion(indexingMap, expansionInfo);
768         expandedOpOperands.push_back(rewriter.create<tensor::ExpandShapeOp>(
769             genericOp.getLoc(), expandedOperandType, opOperand->get(),
770             reassociation));
771         continue;
772       }
773     }
774     expandedOpOperands.push_back(opOperand->get());
775   }
776 
777   Location loc = genericOp.getLoc();
778   SmallVector<Value> outputs;
779   for (OpOperand *opOperand : genericOp.getOutputOperands()) {
780     AffineMap indexingMap = genericOp.getTiedIndexingMap(opOperand);
781     RankedTensorType expandedOutputType =
782         getExpandedType(opOperand->get().getType().cast<RankedTensorType>(),
783                         indexingMap, expansionInfo);
784     if (expandedOutputType != opOperand->get().getType()) {
785       SmallVector<ReassociationIndices> reassociation =
786           getReassociationForExpansion(indexingMap, expansionInfo);
787       outputs.push_back(rewriter.create<tensor::ExpandShapeOp>(
788           genericOp.getLoc(), expandedOutputType, opOperand->get(),
789           reassociation));
790     }
791   }
792 
793   // The iterator types of the expanded op are all parallel.
794   SmallVector<StringRef> iteratorTypes(expansionInfo.getExpandedOpNumDims(),
795                                        getParallelIteratorTypeName());
796 
797   TypeRange resultTypes = ValueRange(outputs).getTypes();
798   auto fusedOp =
799       rewriter.create<GenericOp>(genericOp.getLoc(), resultTypes,
800                                  /*inputs=*/expandedOpOperands, outputs,
801                                  expandedOpIndexingMaps, iteratorTypes);
802   Region &fusedRegion = fusedOp->getRegion(0);
803   Region &originalRegion = genericOp->getRegion(0);
804   rewriter.cloneRegionBefore(originalRegion, fusedRegion, fusedRegion.begin());
805 
806   // Update the index accesses after the expansion.
807   updateExpandedGenericOpRegion(rewriter, loc, fusedRegion, expansionInfo);
808 
809   // Reshape the result values to their original shape if this is a collapsing
810   // reshape folded into its consumer.
811   SmallVector<Value> resultVals;
812   for (OpResult opResult : genericOp->getOpResults()) {
813     int64_t resultNumber = opResult.getResultNumber();
814     if (!isExpanding && resultTypes[resultNumber] != opResult.getType()) {
815       SmallVector<ReassociationIndices> reassociation =
816           getReassociationForExpansion(
817               genericOp.getTiedIndexingMap(
818                   genericOp.getOutputOperand(resultNumber)),
819               expansionInfo);
820       resultVals.push_back(rewriter.create<tensor::CollapseShapeOp>(
821           genericOp.getLoc(), opResult.getType(),
822           fusedOp->getResult(resultNumber), reassociation));
823     } else {
824       resultVals.push_back(fusedOp->getResult(resultNumber));
825     }
826   }
827   // Assuming a single result.
828   return resultVals;
829 }
830 
831 namespace {
832 
833 /// Pattern to fold tensor_expand_shape op with its consumer by using the source
834 /// of the reshape op as the operand in the consumer (instead of the result of
835 /// the tensor_collapse_shape). The corresponding index map in the consumer
836 /// needs to be modified to linearize the folded dimension.
837 ///
838 /// For example,
839 ///
840 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
841 /// %0 = tensor.expand_shape %arg0 [[0], [1, 2], [3]]
842 ///      tensor<?x?x?xf32> into tensor<?x?x4x?xf32>
843 /// %1 = linalg.generic { indexing_maps = [#map0, #map0, #map0], ... }
844 ///        ins(%0, %arg1 : tensor<?x?x4x?xf32>, tensor<?x?x4x?xf32>) ...
845 ///        -> tensor<?x?x4x?xf32>
846 ///
847 /// can be folded into
848 ///
849 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1 * 4 + d2, d3)>
850 /// #map1 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
851 /// %0 = linalg.generic { indexing_maps = [#map0, #map1, #map1] ... }
852 ///        ins(%arg0, %arg1 : tensor<?x?x?xf32>, tensor<?x?x4x?xf32>) ...
853 ///        -> tensor<?x?x4x?xf32>
854 template <bool foldUnitDimReshapesOnly, typename TensorReshapeOp>
855 struct FoldProducerReshapeOpByLinearization
856     : public OpRewritePattern<GenericOp> {
857   using OpRewritePattern<GenericOp>::OpRewritePattern;
858 
859   LogicalResult matchAndRewrite(GenericOp genericOp,
860                                 PatternRewriter &rewriter) const override {
861     if (!genericOp.hasTensorSemantics())
862       return failure();
863     SmallVector<OpOperand *> inputOperands = genericOp.getInputOperands();
864     for (const auto &en : llvm::enumerate(inputOperands)) {
865       auto reshapeOp = en.value()->get().getDefiningOp<TensorReshapeOp>();
866       if (!reshapeOp)
867         continue;
868 
869       if (!isTensorReshapeOpFoldableByLinearization(
870               reshapeOp, genericOp.getTiedIndexingMap(en.value()),
871               /*asProducer =*/true) ||
872           (foldUnitDimReshapesOnly && !isUnitDimExpansionOnly(reshapeOp)))
873         continue;
874 
875       // Compute the fused operands list,
876       SmallVector<Value> fusedOperands = genericOp.getInputOperands();
877       fusedOperands[en.index()] = reshapeOp.src();
878       SmallVector<Value> outputOperands = genericOp.getOutputOperands();
879       llvm::append_range(fusedOperands, outputOperands);
880 
881       // Compute indexing_maps for the fused operation. The indexing_maps for
882       // the operands of the consumers that arent fused are the same.
883       SmallVector<AffineMap> fusedIndexMaps = genericOp.getIndexingMaps();
884 
885       // Accepted consumer maps are either identity or permutation.
886       auto invMap = inversePermutation(fusedIndexMaps[en.index()]);
887 
888       // Compute the indexing map to use for the result of the producer.
889       AffineMap modifiedMap = linearizeCollapsedDims(invMap, reshapeOp);
890       // The modified map cannot have symbols.
891       if (modifiedMap.getNumSymbols())
892         return failure();
893       for (AffineExpr expr : modifiedMap.getResults()) {
894         if (!expr.isPureAffine())
895           return failure();
896       }
897       fusedIndexMaps[en.index()] = modifiedMap;
898 
899       // Further check that the resulting index maps can be fused and
900       // inverted. Without this the resultant op is not legal.
901       if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) {
902         return rewriter.notifyMatchFailure(
903             genericOp, "fused op loop bound computation failed");
904       }
905 
906       rewriter.startRootUpdate(genericOp);
907       genericOp->setOperands(fusedOperands);
908       genericOp.indexing_mapsAttr(
909           rewriter.getAffineMapArrayAttr(fusedIndexMaps));
910       rewriter.finalizeRootUpdate(genericOp);
911       return success();
912     }
913     return failure();
914   }
915 };
916 
917 static SmallVector<ReassociationIndices>
918 getReassociationIndices(ArrayRef<AffineMap> maps) {
919   SmallVector<ReassociationIndices> reassociation;
920   for (AffineMap map : maps) {
921     ReassociationIndices indices;
922     for (unsigned i = 0, e = map.getNumResults(); i < e; i++) {
923       unsigned pos = map.getResult(i).cast<AffineDimExpr>().getPosition();
924       indices.push_back(pos);
925     }
926     reassociation.push_back(indices);
927   }
928   return reassociation;
929 }
930 
931 /// Pattern to move rank reducing reshape after an elementwise linalg generic
932 /// op. This is useful to expose more fusion opportunities between named ops and
933 /// generic ops. This can only be done if there is no broadcast or permuation
934 /// within the dimensions we need to merge.
935 ///
936 /// For example,
937 ///
938 ///  %0 = tensor.expand_shape %A [[0, 1], [2]]
939 ///      : tensor<12544x16xf32> into tensor<112x112x16xf32>
940 ///  %2 = linalg.generic {indexing_maps = [
941 ///    affine_map<(d0, d1, d2) -> (d0, d1, d2)>,
942 ///    affine_map<(d0, d1, d2) -> (d2)>,
943 ///    affine_map<(d0, d1, d2) -> (d0, d1, d2)>], iterator_types =
944 ///    ["parallel", "parallel", "parallel"]} {
945 ///  } -> tensor<112x112x16xf32>
946 ///
947 ///  into
948 ///
949 ///  %2 = linalg.generic {indexing_maps = [
950 ///    affine_map<(d0, d1) -> (d0, d1)>,
951 ///    affine_map<(d0, d1) -> (d1)>,
952 ///    affine_map<(d0, d1) -> (d0, d1)>],
953 ///    iterator_types = ["parallel", "parallel"]} ins(%arg0, %arg1
954 ///    : tensor<12544x16xf32>, tensor<16xf32>) outs(%1 : tensor<12544x16xf32>) {
955 ///  } -> tensor<12544x16xf32>
956 ///  %3 = tensor.expand_shape %2 [[0, 1], [2]]
957 ///    : tensor<12544x16xf32> into tensor<112x112x16xf32>
958 struct PushExpandingReshape : public OpRewritePattern<GenericOp> {
959   using OpRewritePattern<GenericOp>::OpRewritePattern;
960 
961   LogicalResult matchAndRewrite(GenericOp genericOp,
962                                 PatternRewriter &rewriter) const override {
963     // Only apply to elementwise linalg on tensor.
964     if (!genericOp.hasTensorSemantics() ||
965         genericOp.getNumParallelLoops() != genericOp.getNumLoops())
966       return failure();
967     // Only support identity output maps. It could be extended to permuations if
968     // needed.
969     if (llvm::any_of(genericOp.getOutputOperands(), [&](OpOperand *opOperand) {
970           return !genericOp.getTiedIndexingMap(opOperand).isIdentity();
971         }))
972       return failure();
973     int64_t destRank = genericOp.getNumParallelLoops();
974     SmallVector<Value> newOperands = genericOp.getInputOperands();
975     tensor::ExpandShapeOp reshapeFound;
976     // 1. Look for tensor_expand_shape operands and figure out save the
977     // dimensions merged.
978     SmallVector<OpOperand *> inputOperands = genericOp.getInputOperands();
979     for (const auto &en : llvm::enumerate(inputOperands)) {
980       auto reshapeOp =
981           en.value()->get().template getDefiningOp<tensor::ExpandShapeOp>();
982       if (!reshapeOp)
983         continue;
984       // TODO: We could support non-identity map as long as the merged
985       // dimensions are still contiguous.
986       if (!genericOp.getTiedIndexingMap(en.value()).isIdentity())
987         continue;
988       if (reshapeFound) {
989         // Only support a second reshape op if it has the same reassociate maps.
990         if (reshapeFound.getReassociationMaps() ==
991             reshapeOp.getReassociationMaps())
992           newOperands[en.index()] = reshapeOp.src();
993         continue;
994       }
995       reshapeFound = reshapeOp;
996       newOperands[en.index()] = reshapeOp.src();
997     }
998     if (!reshapeFound)
999       return failure();
1000 
1001     // Calculate the reassociation indices and rassociated reverse map.
1002     SmallVector<ReassociationIndices> reassociation =
1003         getReassociationIndices(reshapeFound.getReassociationMaps());
1004     SmallVector<unsigned> remap(destRank);
1005     for (auto &indices : llvm::enumerate(reassociation)) {
1006       for (int64_t index : indices.value()) {
1007         remap[index] = indices.index();
1008       }
1009     }
1010     // 2. Verify that we can merge the dimensions in the linalg and that we
1011     // don't need to create new reshapes operands. Inserting new reshape
1012     // operands would defeat the purpose of the transformation.
1013     for (const auto &en : llvm::enumerate(inputOperands)) {
1014       if (en.value()->get() == newOperands[en.index()]) {
1015         AffineMap map = genericOp.getTiedIndexingMap(en.value());
1016         for (unsigned i : llvm::seq(unsigned(0), map.getNumResults())) {
1017           if (reassociation[remap[map.getDimPosition(i)]].size() > 1)
1018             return failure();
1019         }
1020       }
1021     }
1022 
1023     // 3. Calculate the affine map remapping and the reassociation to apply to
1024     // output tensors.
1025     SmallVector<AffineMap> newMaps;
1026     unsigned newRank = reassociation.size();
1027     for (auto map : genericOp.getIndexingMaps()) {
1028       SmallVector<AffineExpr> newExprs;
1029       for (auto expr : map.getResults()) {
1030         unsigned position = expr.template cast<AffineDimExpr>().getPosition();
1031         // Skip dimension merged except for the last of the group.
1032         if (reassociation[remap[position]].back() == position) {
1033           newExprs.push_back(
1034               getAffineDimExpr(remap[position], genericOp.getContext()));
1035         }
1036       }
1037       newMaps.push_back(
1038           AffineMap::get(newRank, 0, newExprs, genericOp.getContext()));
1039     }
1040 
1041     // 4. Reshape the output tensors.
1042     SmallVector<Value> newOutputs;
1043     SmallVector<Type> newOutputTypes;
1044     for (auto output : genericOp.outputs()) {
1045       auto newOutputType = RankedTensorType::get(
1046           reshapeFound.getSrcType().getShape(),
1047           output.getType().template cast<RankedTensorType>().getElementType());
1048       Value newOutput = rewriter.create<tensor::CollapseShapeOp>(
1049           genericOp->getLoc(), newOutputType, output, reassociation);
1050       newOutputTypes.push_back(newOutputType);
1051       newOutputs.push_back(newOutput);
1052     }
1053     // 5. Create a new generic op with lowerer rank.
1054     SmallVector<StringRef> iteratorTypes(newRank,
1055                                          getParallelIteratorTypeName());
1056     auto newOp = rewriter.create<GenericOp>(genericOp->getLoc(), newOutputTypes,
1057                                             newOperands, newOutputs, newMaps,
1058                                             iteratorTypes);
1059     rewriter.inlineRegionBefore(genericOp.region(), newOp.region(),
1060                                 newOp.region().begin());
1061     // 6. Reshape the so that the type matches the uses.
1062     SmallVector<Value> newResults;
1063     for (const auto &result : llvm::enumerate(newOp->getResults())) {
1064       newResults.push_back(rewriter.create<tensor::ExpandShapeOp>(
1065           genericOp->getLoc(), genericOp.getOutputTensorTypes()[result.index()],
1066           result.value(), reassociation));
1067     }
1068     rewriter.replaceOp(genericOp, newResults);
1069     return success();
1070   }
1071 };
1072 
1073 /// Pattern to fuse a tensor_collapse_shape op with its consumer generic op,
1074 /// when the reshape op is collapsing dimensions. The dimensionality of the loop
1075 /// in the consumer is expanded.
1076 class FoldWithProducerReshapeOpByExpansion
1077     : public OpRewritePattern<GenericOp> {
1078 public:
1079   FoldWithProducerReshapeOpByExpansion(
1080       MLIRContext *context, ControlElementwiseOpsFusionFn foldReshapes,
1081       PatternBenefit benefit = 1)
1082       : OpRewritePattern<GenericOp>(context, benefit),
1083         controlFoldingReshapes(std::move(foldReshapes)) {}
1084 
1085   LogicalResult matchAndRewrite(GenericOp genericOp,
1086                                 PatternRewriter &rewriter) const override {
1087     for (OpOperand *opOperand : genericOp.getInputTensorOperands()) {
1088       tensor::CollapseShapeOp reshapeOp =
1089           opOperand->get().getDefiningOp<tensor::CollapseShapeOp>();
1090       if (!reshapeOp)
1091         continue;
1092       // Fold only if
1093       // - The tensor reshape op is folding.
1094       // - All constraints of fusing with reshape by expansion are met.
1095       if (!isFusableWithReshapeByDimExpansion(genericOp, opOperand) ||
1096           (!controlFoldingReshapes(reshapeOp->getResult(0), *opOperand)))
1097         continue;
1098 
1099       Optional<SmallVector<Value>> replacementValues =
1100           fuseWithReshapeByExpansion(genericOp, reshapeOp, opOperand, rewriter);
1101       if (!replacementValues)
1102         return failure();
1103       rewriter.replaceOp(genericOp, replacementValues.getValue());
1104       return success();
1105     }
1106     return failure();
1107   }
1108 
1109 private:
1110   ControlElementwiseOpsFusionFn controlFoldingReshapes;
1111 };
1112 
1113 /// Pattern to fold tensor_collapse_shape or tensor_expand_shape op with its
1114 /// producer. The corresponding index map in the consumer needs to be modified
1115 /// to linearize the folded dimension.
1116 template <bool foldUnitDimReshapesOnly, typename TensorReshapeOp>
1117 struct FoldConsumerReshapeOpByLinearization
1118     : public OpRewritePattern<TensorReshapeOp> {
1119   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
1120 
1121   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
1122                                 PatternRewriter &rewriter) const override {
1123     GenericOp producer = reshapeOp.src().template getDefiningOp<GenericOp>();
1124     if (!producer || !producer.hasTensorSemantics() ||
1125         producer.getNumOutputs() != 1 ||
1126         !isTensorReshapeOpFoldableByLinearization(
1127             reshapeOp,
1128             producer.getTiedIndexingMap(producer.getOutputOperand(0)),
1129             /*asProducer =*/false) ||
1130         (foldUnitDimReshapesOnly && !isUnitDimExpansionOnly(reshapeOp)))
1131       return failure();
1132     // The indexing_maps for the operands of the fused operation are same as
1133     // those for the operands of the producer.
1134     SmallVector<AffineMap> fusedIndexMaps = producer.getIndexingMaps();
1135 
1136     auto invMap = inversePermutation(
1137         producer.getTiedIndexingMap(producer.getOutputOperand(0)));
1138 
1139     // Compute the indexing map to use for the operand of the producer.
1140     AffineMap modifiedMap = linearizeCollapsedDims(invMap, reshapeOp);
1141     for (AffineExpr expr : modifiedMap.getResults()) {
1142       if (!expr.isPureAffine()) {
1143         return rewriter.notifyMatchFailure(
1144             producer, "fused op indexing map is not affine");
1145       }
1146     }
1147     fusedIndexMaps.back() = modifiedMap;
1148 
1149     // Further check that the resulting index maps can be fused and
1150     // inverted. Without this the resultant op is not legal.
1151     if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) {
1152       return rewriter.notifyMatchFailure(
1153           producer, "fused op loop bound computation failed");
1154     }
1155 
1156     Location loc = producer.getLoc();
1157     SmallVector<Value> inputOperands = producer.getInputOperands();
1158     Value output = rewriter.create<TensorReshapeOp>(
1159         loc, producer.getOutputOperand(0)->get(),
1160         reshapeOp.getReassociationExprs());
1161     auto fusedOp = rewriter.create<GenericOp>(
1162         loc, reshapeOp.getResultType(),
1163         /*inputs=*/inputOperands,
1164         // TODO: handle outputs.
1165         /*outputs=*/output, rewriter.getAffineMapArrayAttr(fusedIndexMaps),
1166         producer.iterator_types(),
1167         /*doc=*/nullptr,
1168         /*library_call=*/nullptr);
1169     auto &fusedRegion = fusedOp->getRegion(0);
1170     rewriter.cloneRegionBefore(producer->getRegion(0), fusedRegion,
1171                                fusedRegion.begin());
1172     rewriter.replaceOp(reshapeOp, fusedOp->getResults());
1173     return success();
1174   }
1175 };
1176 
1177 /// Pattern to fold a tensor_expand_shape op with its producer generic op
1178 /// by expanding the dimensionality of the loop in the producer op.
1179 struct FoldReshapeWithGenericOpByExpansion
1180     : public OpRewritePattern<tensor::ExpandShapeOp> {
1181 
1182   FoldReshapeWithGenericOpByExpansion(
1183       MLIRContext *context, ControlElementwiseOpsFusionFn foldReshapes,
1184       PatternBenefit benefit = 1)
1185       : OpRewritePattern<tensor::ExpandShapeOp>(context, benefit),
1186         controlFoldingReshapes(std::move(foldReshapes)) {}
1187 
1188   LogicalResult matchAndRewrite(tensor::ExpandShapeOp reshapeOp,
1189                                 PatternRewriter &rewriter) const override {
1190     // Fold only if all constraints of fusing with reshape by expansion are met.
1191     GenericOp producer = reshapeOp.src().getDefiningOp<GenericOp>();
1192     if (!producer || producer.getNumOutputs() != 1 ||
1193         !isFusableWithReshapeByDimExpansion(producer,
1194                                             producer.getOutputOperand(0)) ||
1195         !controlFoldingReshapes(producer->getResult(0),
1196                                 reshapeOp->getOpOperand(0)))
1197       return failure();
1198     Optional<SmallVector<Value>> replacementValues = fuseWithReshapeByExpansion(
1199         producer, reshapeOp, producer.getOutputOperand(0), rewriter);
1200     if (!replacementValues)
1201       return failure();
1202     rewriter.replaceOp(reshapeOp, replacementValues.getValue());
1203     return success();
1204   }
1205 
1206 private:
1207   ControlElementwiseOpsFusionFn controlFoldingReshapes;
1208 };
1209 
1210 /// Pattern to fold a generic op with a splat constant/scalar constant. Does not
1211 /// handle cases where the constant is not single-valued.
1212 class FoldScalarOrSplatConstant : public OpRewritePattern<GenericOp> {
1213 public:
1214   FoldScalarOrSplatConstant(MLIRContext *context,
1215                             ControlElementwiseOpsFusionFn &fun,
1216                             PatternBenefit benefit = 1)
1217       : OpRewritePattern<GenericOp>(context, benefit), controlFn(fun) {}
1218 
1219   LogicalResult matchAndRewrite(GenericOp genericOp,
1220                                 PatternRewriter &rewriter) const override {
1221     if (!genericOp.hasTensorSemantics())
1222       return failure();
1223     for (OpOperand *opOperand : genericOp.getInputOperands()) {
1224       Operation *def = opOperand->get().getDefiningOp();
1225       Attribute constantAttr;
1226       auto isScalarOrSplatConstantOp = [&constantAttr](Operation *def) -> bool {
1227         {
1228           DenseElementsAttr splatAttr;
1229           if (matchPattern(def, m_Constant<DenseElementsAttr>(&splatAttr)) &&
1230               splatAttr.isSplat() &&
1231               splatAttr.getType().getElementType().isIntOrFloat()) {
1232             constantAttr = splatAttr.getSplatValue<Attribute>();
1233             return true;
1234           }
1235         }
1236         {
1237           IntegerAttr intAttr;
1238           if (matchPattern(def, m_Constant<IntegerAttr>(&intAttr))) {
1239             constantAttr = intAttr;
1240             return true;
1241           }
1242         }
1243         {
1244           FloatAttr floatAttr;
1245           if (matchPattern(def, m_Constant<FloatAttr>(&floatAttr))) {
1246             constantAttr = floatAttr;
1247             return true;
1248           }
1249         }
1250         return false;
1251       };
1252 
1253       auto resultValue = opOperand->get().dyn_cast<OpResult>();
1254       if (!def || !resultValue || !isScalarOrSplatConstantOp(def) ||
1255           !controlFn(resultValue, *opOperand))
1256         continue;
1257 
1258       // The operands and the indexing_maps of the fused operation the same as
1259       // the operands and indexing_maps of the generic operations with the
1260       // values at the constant index dropped.
1261       SmallVector<AffineMap> fusedIndexMaps;
1262       SmallVector<Value> fusedOperands;
1263       SmallVector<Location> fusedLocs{genericOp.getLoc()};
1264       fusedIndexMaps.reserve(genericOp.getNumInputsAndOutputs());
1265       fusedOperands.reserve(genericOp.getNumInputs());
1266       fusedLocs.reserve(fusedLocs.size() + genericOp.getNumInputs());
1267       for (OpOperand *inputOperand : genericOp.getInputOperands()) {
1268         if (inputOperand == opOperand)
1269           continue;
1270         Value inputValue = inputOperand->get();
1271         fusedIndexMaps.push_back(genericOp.getTiedIndexingMap(inputOperand));
1272         fusedOperands.push_back(inputValue);
1273         fusedLocs.push_back(inputValue.getLoc());
1274       }
1275       for (OpOperand *outputOperand : genericOp.getOutputOperands())
1276         fusedIndexMaps.push_back(genericOp.getTiedIndexingMap(outputOperand));
1277 
1278       // Check if the operation shapes to loops map is computable.
1279       if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) {
1280         return rewriter.notifyMatchFailure(
1281             genericOp, "fused op loop bound computation failed");
1282       }
1283 
1284       // Create a constant scalar value from the splat constant.
1285       Value scalarConstant = rewriter.create<arith::ConstantOp>(
1286           def->getLoc(), constantAttr, constantAttr.getType());
1287 
1288       SmallVector<Value> outputOperands = genericOp.getOutputOperands();
1289       auto fusedOp = rewriter.create<GenericOp>(
1290           rewriter.getFusedLoc(fusedLocs), genericOp->getResultTypes(),
1291           /*inputs=*/fusedOperands,
1292           /*outputs=*/outputOperands,
1293           rewriter.getAffineMapArrayAttr(fusedIndexMaps),
1294           genericOp.iterator_types(),
1295           /*doc=*/nullptr,
1296           /*library_call=*/nullptr);
1297 
1298       // Map the block argument corresponding to the replaced argument with the
1299       // scalar constant.
1300       Region &region = genericOp->getRegion(0);
1301       Block &entryBlock = *region.begin();
1302       BlockAndValueMapping mapping;
1303       mapping.map(entryBlock.getArgument(opOperand->getOperandNumber()),
1304                   scalarConstant);
1305       Region &fusedRegion = fusedOp->getRegion(0);
1306       rewriter.cloneRegionBefore(region, fusedRegion, fusedRegion.begin(),
1307                                  mapping);
1308       rewriter.replaceOp(genericOp, fusedOp->getResults());
1309       return success();
1310     }
1311     return failure();
1312   }
1313 
1314 private:
1315   ControlElementwiseOpsFusionFn controlFn;
1316 };
1317 
1318 /// Base class for constant folding linalg.generic ops with N inputs, 1 output,
1319 /// and permutation indexing maps.
1320 ///
1321 /// `ConcreteType` should provide methods with signatures
1322 ///
1323 /// ```c++
1324 ///   bool matchIndexingMaps(GenericOp genericOp) const;
1325 ///   RegionComputationFn getRegionComputeFn(GenericOp) const;
1326 /// ```
1327 ///
1328 /// The latter inspects the region and returns the computation inside as a
1329 /// functor. The functor will be invoked with constant elements for all inputs
1330 /// and should return the corresponding computea constant element for output.
1331 template <typename ConcreteType>
1332 class FoldConstantBase : public OpRewritePattern<GenericOp> {
1333 public:
1334   struct APIntOrFloat {
1335     Optional<APInt> apInt;
1336     Optional<APFloat> apFloat;
1337   };
1338   struct APIntOrFloatArray {
1339     SmallVector<APInt> apInts;
1340     SmallVector<APFloat> apFloats;
1341   };
1342   using RegionComputationFn =
1343       std::function<APIntOrFloat(const APIntOrFloatArray &)>;
1344 
1345   FoldConstantBase(MLIRContext *context,
1346                    const ControlElementwiseOpsFusionFn &controlFn,
1347                    PatternBenefit benefit = 1)
1348       : OpRewritePattern<GenericOp>(context, benefit), controlFn(controlFn) {}
1349 
1350   LogicalResult matchAndRewrite(GenericOp genericOp,
1351                                 PatternRewriter &rewriter) const override {
1352     if (genericOp.hasBufferSemantics())
1353       return failure();
1354 
1355     // Only support ops generating one output for now.
1356     if (genericOp.getNumOutputs() != 1)
1357       return failure();
1358 
1359     auto outputType = genericOp.getResultTypes().front().dyn_cast<ShapedType>();
1360     // Require the output types to be static give we are generating constants.
1361     if (!outputType || !outputType.hasStaticShape())
1362       return failure();
1363 
1364     if (!llvm::all_of(genericOp.getInputOperands(), [](OpOperand *operand) {
1365           return operand->get().getType().isa<ShapedType>();
1366         }))
1367       return failure();
1368 
1369     // Make sure all element types are the same.
1370     auto getOperandElementType = [](OpOperand *operand) {
1371       return operand->get().getType().cast<ShapedType>().getElementType();
1372     };
1373     if (!llvm::is_splat(llvm::map_range(genericOp.getInputAndOutputOperands(),
1374                                         getOperandElementType)))
1375       return failure();
1376 
1377     // We can only handle the case where we have int/float elements.
1378     auto elementType = outputType.getElementType();
1379     if (!elementType.isIntOrFloat())
1380       return failure();
1381 
1382     // Require all indexing maps to be permutations for now. This is common and
1383     // it simplifies input/output access greatly: we can do the data shuffling
1384     // entirely in the compiler, without needing to turn all indices into
1385     // Values, and then do affine apply on them, and then match back the
1386     // constant again.
1387     if (!llvm::all_of(genericOp.getIndexingMaps(),
1388                       [](AffineMap map) { return map.isPermutation(); }))
1389       return failure();
1390 
1391     for (OpOperand *operand : genericOp.getOutputOperands()) {
1392       if (genericOp.payloadUsesValueFromOperand(operand))
1393         return failure();
1394     }
1395 
1396     // Further check the indexing maps are okay for the ConcreteType.
1397     if (!static_cast<const ConcreteType *>(this)->matchIndexingMaps(genericOp))
1398       return failure();
1399 
1400     // Defer to the concrete type to check the region and discover the
1401     // computation inside.
1402     RegionComputationFn computeFn =
1403         static_cast<const ConcreteType *>(this)->getRegionComputeFn(genericOp);
1404     if (!computeFn)
1405       return failure();
1406 
1407     // All inputs should be constants.
1408     int numInputs = genericOp.getNumInputs();
1409     SmallVector<DenseIntOrFPElementsAttr> inputValues(numInputs);
1410     for (const auto &operand : llvm::enumerate(genericOp.getInputOperands())) {
1411       if (!matchPattern(operand.value()->get(),
1412                         m_Constant(&inputValues[operand.index()])))
1413         return failure();
1414     }
1415 
1416     // Identified this as a potential candidate for folding. Now check the
1417     // policy to see whether we are allowed to proceed.
1418     for (int i = 0; i < numInputs; ++i) {
1419       OpOperand *consumer = genericOp.getInputOperand(i);
1420       OpResult producer = consumer->get().cast<OpResult>();
1421       if (!controlFn(producer, *consumer))
1422         return failure();
1423     }
1424 
1425     auto linalgOp = cast<LinalgOp>(genericOp.getOperation());
1426     SmallVector<int64_t, 4> loopBounds = linalgOp.computeStaticLoopSizes();
1427     int64_t numElements = outputType.getNumElements();
1428 
1429     // Use APInt/APFloat instead of Attribute here for constructing the output.
1430     // This helps to avoid blowing up compiler memory usage: Attributes would
1431     // unify the following cases but they have lifetime as the MLIRContext.
1432     SmallVector<APInt> intOutputValues;
1433     SmallVector<APFloat> fpOutputValues;
1434     if (elementType.template isa<FloatType>())
1435       fpOutputValues.resize(numElements, APFloat(0.f));
1436     else
1437       intOutputValues.resize(numElements);
1438 
1439     // Return the constant dim positions from the given permutation map.
1440     auto getDimPositions = [](AffineMap map) {
1441       SmallVector<unsigned> dims;
1442       dims.reserve(map.getNumResults());
1443       for (AffineExpr result : map.getResults()) {
1444         dims.push_back(result.cast<AffineDimExpr>().getPosition());
1445       }
1446       return dims;
1447     };
1448 
1449     SmallVector<SmallVector<unsigned>> inputDims;
1450     for (int i = 0; i < numInputs; ++i)
1451       inputDims.push_back(getDimPositions(genericOp.getIndexingMaps()[i]));
1452     auto outputDims = getDimPositions(genericOp.getIndexingMaps().back());
1453     auto outputShape = outputType.getShape();
1454 
1455     // Allocate small vectors for index delinearization. Initial values do not
1456     // matter here as they will be overwritten later.
1457     SmallVector<uint64_t> indices(loopBounds.size(), 0);
1458     SmallVector<uint64_t> dstIndices(loopBounds.size(), 0);
1459     SmallVector<SmallVector<uint64_t>> srcIndices(
1460         numInputs, SmallVector<uint64_t>(loopBounds.size(), 0));
1461     SmallVector<uint64_t> srcLinearIndices(numInputs, 0);
1462     uint64_t dstLinearIndex = 0;
1463 
1464     // Allocate spaces for compute function inputs. Initial values do not matter
1465     // here as they will be overwritten later.
1466     APIntOrFloatArray computeFnInputs;
1467 
1468     auto inputShapes = llvm::to_vector<4>(
1469         llvm::map_range(genericOp.getInputOperands(), [](OpOperand *operand) {
1470           return operand->get().getType().cast<ShapedType>().getShape();
1471         }));
1472 
1473     // Given a `linearIndex`, remap it to a linear index to access linalg op
1474     // inputs/ouputs. This mutates `indices`, `srcIndices`, `dstIndices`,
1475     // `srcLinearIndices`, `dstLinearIndex` in place.
1476     auto computeRemappedLinearIndex = [&](int linearIndex) {
1477       int totalCount = linearIndex;
1478       for (int dim = loopBounds.size() - 1; dim >= 0; --dim) {
1479         indices[dim] = totalCount % loopBounds[dim];
1480         totalCount /= loopBounds[dim];
1481       }
1482 
1483       for (int dim = loopBounds.size() - 1; dim >= 0; --dim) {
1484         for (int i = 0; i < numInputs; ++i)
1485           srcIndices[i][dim] = indices[inputDims[i][dim]];
1486         dstIndices[dim] = indices[outputDims[dim]];
1487       }
1488 
1489       dstLinearIndex = dstIndices.front();
1490       for (int i = 0; i < numInputs; ++i)
1491         srcLinearIndices[i] = srcIndices[i].front();
1492 
1493       for (int dim = 1; dim < outputType.getRank(); ++dim) {
1494         dstLinearIndex = dstLinearIndex * outputShape[dim] + dstIndices[dim];
1495         for (int i = 0; i < numInputs; ++i)
1496           srcLinearIndices[i] =
1497               srcLinearIndices[i] * inputShapes[i][dim] + srcIndices[i][dim];
1498       }
1499     };
1500 
1501     bool isFloat = elementType.isa<FloatType>();
1502     if (isFloat) {
1503       SmallVector<DenseElementsAttr::iterator_range<APFloat>> inFpRanges;
1504       for (int i = 0; i < numInputs; ++i)
1505         inFpRanges.push_back(inputValues[i].getValues<APFloat>());
1506 
1507       computeFnInputs.apFloats.resize(numInputs, APFloat(0.f));
1508 
1509       // Transpose the input constant. Because we don't know its rank in
1510       // advance, we need to loop over the range [0, element count) and
1511       // delinearize the index.
1512       for (int linearIndex = 0; linearIndex < numElements; ++linearIndex) {
1513         computeRemappedLinearIndex(linearIndex);
1514 
1515         // Collect constant elements for all inputs at this loop iteration.
1516         for (int i = 0; i < numInputs; ++i)
1517           computeFnInputs.apFloats[i] = inFpRanges[i][srcLinearIndices[i]];
1518 
1519         // Invoke the computation to get the corresponding constant output
1520         // element.
1521         fpOutputValues[dstLinearIndex] = *computeFn(computeFnInputs).apFloat;
1522       }
1523     } else {
1524       SmallVector<DenseElementsAttr::iterator_range<APInt>> inIntRanges;
1525       for (int i = 0; i < numInputs; ++i)
1526         inIntRanges.push_back(inputValues[i].getValues<APInt>());
1527 
1528       computeFnInputs.apInts.resize(numInputs);
1529 
1530       // Transpose the input constant. Because we don't know its rank in
1531       // advance, we need to loop over the range [0, element count) and
1532       // delinearize the index.
1533       for (int linearIndex = 0; linearIndex < numElements; ++linearIndex) {
1534         computeRemappedLinearIndex(linearIndex);
1535 
1536         // Collect constant elements for all inputs at this loop iteration.
1537         for (int i = 0; i < numInputs; ++i)
1538           computeFnInputs.apInts[i] = inIntRanges[i][srcLinearIndices[i]];
1539 
1540         // Invoke the computation to get the corresponding constant output
1541         // element.
1542         intOutputValues[dstLinearIndex] = *computeFn(computeFnInputs).apInt;
1543       }
1544     }
1545 
1546     DenseElementsAttr outputAttr =
1547         isFloat ? DenseElementsAttr::get(outputType, fpOutputValues)
1548                 : DenseElementsAttr::get(outputType, intOutputValues);
1549 
1550     rewriter.replaceOpWithNewOp<ConstantOp>(genericOp, outputAttr);
1551     return success();
1552   }
1553 
1554 private:
1555   ControlElementwiseOpsFusionFn controlFn;
1556 };
1557 
1558 // Folds linalg.generic ops that are actually transposes on constant values.
1559 struct FoldConstantTranspose : public FoldConstantBase<FoldConstantTranspose> {
1560   using FoldConstantBase::FoldConstantBase;
1561 
1562   bool matchIndexingMaps(GenericOp genericOp) const {
1563     // We should have one input and one output.
1564     return genericOp.getIndexingMaps().size() == 2;
1565   }
1566 
1567   RegionComputationFn getRegionComputeFn(GenericOp genericOp) const {
1568     // Make sure the region only contains a yield op.
1569     Block &body = genericOp.region().front();
1570     if (!llvm::hasSingleElement(body))
1571       return nullptr;
1572     auto yieldOp = dyn_cast<linalg::YieldOp>(body.getTerminator());
1573     if (!yieldOp)
1574       return nullptr;
1575 
1576     // The yield op should return the block argument corresponds to the input.
1577     for (Value yieldVal : yieldOp.values()) {
1578       auto yieldArg = yieldVal.dyn_cast<BlockArgument>();
1579       if (!yieldArg || yieldArg.getOwner() != &body)
1580         return nullptr;
1581       if (yieldArg.getArgNumber() != 0)
1582         return nullptr;
1583     }
1584 
1585     // No computation; just return the orginal value.
1586     return [](const APIntOrFloatArray &inputs) {
1587       if (inputs.apFloats.empty())
1588         return APIntOrFloat{inputs.apInts.front(), llvm::None};
1589       return APIntOrFloat{llvm::None, inputs.apFloats.front()};
1590     };
1591   }
1592 
1593   ControlElementwiseOpsFusionFn controlFn;
1594 };
1595 
1596 } // namespace
1597 
1598 static Optional<SmallVector<Value>>
1599 fuseElementwiseOps(PatternRewriter &rewriter, OpOperand *consumerOpOperand,
1600                    GenericOp producer,
1601                    const ControlElementwiseOpsFusionFn &controlFn) {
1602   if (producer->getNumResults() != 1)
1603     return llvm::None;
1604 
1605   return fuseElementwiseOpsImpl(producer, consumerOpOperand, controlFn,
1606                                 rewriter);
1607 }
1608 
1609 bool mlir::linalg::skipUnitDimReshape(const OpResult &producer,
1610                                       OpOperand &consumer) {
1611   if (auto producerCollapseOp =
1612           dyn_cast<tensor::CollapseShapeOp>(producer.getOwner())) {
1613     return !isUnitDimExpansionOnly(producerCollapseOp);
1614   }
1615   if (auto consumerExpandOp =
1616           dyn_cast<tensor::ExpandShapeOp>(consumer.getOwner())) {
1617     return !isUnitDimExpansionOnly(consumerExpandOp);
1618   }
1619   return true;
1620 }
1621 
1622 namespace {
1623 /// Patterns to fuse a generic op, with the producer of its operands.
1624 class FuseElementwiseOps : public OpRewritePattern<GenericOp> {
1625 public:
1626   FuseElementwiseOps(MLIRContext *context, ControlElementwiseOpsFusionFn &fun,
1627                      PatternBenefit benefit = 1)
1628       : OpRewritePattern<GenericOp>(context, benefit), controlFn(fun) {}
1629 
1630   LogicalResult matchAndRewrite(GenericOp genericOp,
1631                                 PatternRewriter &rewriter) const override {
1632     // Find the first operand that is defined by another generic op on tensors.
1633     for (OpOperand *opOperand : genericOp.getInputAndOutputOperands()) {
1634       auto producer =
1635           dyn_cast_or_null<GenericOp>(opOperand->get().getDefiningOp());
1636       if (!producer || !producer.hasTensorSemantics())
1637         continue;
1638       Optional<SmallVector<Value>> fusedOpResults =
1639           fuseElementwiseOps(rewriter, opOperand, producer, controlFn);
1640       if (fusedOpResults) {
1641         rewriter.replaceOp(genericOp, *fusedOpResults);
1642         return success();
1643       }
1644     }
1645     return failure();
1646   }
1647 
1648 private:
1649   ControlElementwiseOpsFusionFn controlFn;
1650 };
1651 
1652 /// Pass that fuses generic ops on tensors. Used only for testing.
1653 struct LinalgElementwiseOpFusionPass
1654     : public LinalgElementwiseOpFusionBase<LinalgElementwiseOpFusionPass> {
1655   void runOnOperation() override {
1656     Operation *op = getOperation();
1657     RewritePatternSet patterns(op->getContext());
1658     ControlElementwiseOpsFusionFn allowFoldingFn =
1659         [](const OpResult &producer, const OpOperand &consumer) {
1660           return true;
1661         };
1662     populateElementwiseOpsFusionPatterns(
1663         patterns,
1664         LinalgElementwiseFusionOptions().setControlFoldingReshapes(
1665             allowFoldingUnitDimReshapes ? allowFoldingFn : skipUnitDimReshape));
1666 
1667     // Use TopDownTraversal for compile time reasons
1668     GreedyRewriteConfig grc;
1669     grc.useTopDownTraversal = true;
1670     (void)applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns),
1671                                        grc);
1672   }
1673 };
1674 
1675 /// Pass to test folding of reshape ops with generic ops by linearization.
1676 struct FoldReshapeOpsByLinearizationPass
1677     : public LinalgFoldReshapeOpsByLinearizationBase<
1678           FoldReshapeOpsByLinearizationPass> {
1679   void runOnOperation() override {
1680     Operation *op = getOperation();
1681     RewritePatternSet patterns(op->getContext());
1682     populateFoldReshapeOpsByLinearizationPatterns(patterns);
1683     if (allowFoldingUnitDimReshapes) {
1684       populateFoldUnitDimsReshapeOpsByLinearizationPatterns(patterns);
1685     }
1686     (void)applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns));
1687   }
1688 };
1689 
1690 /// Forces `outs` operands of linalg operations to use `linalg.init_tensor` if
1691 /// the value of the `outs` operand is not used within the op.  This is only
1692 /// implemented for `linalg.generic` operations for now, but should hold for all
1693 /// linalg structured ops.
1694 struct RemoveOutsDependency : public OpRewritePattern<GenericOp> {
1695   using OpRewritePattern<GenericOp>::OpRewritePattern;
1696 
1697   LogicalResult matchAndRewrite(GenericOp op,
1698                                 PatternRewriter &rewriter) const override {
1699     rewriter.startRootUpdate(op);
1700     bool modifiedOutput = false;
1701     Location loc = op.getLoc();
1702     for (OpOperand *opOperand : op.getOutputOperands()) {
1703       if (!op.payloadUsesValueFromOperand(opOperand)) {
1704         Value operandVal = opOperand->get();
1705         auto operandType = operandVal.getType().dyn_cast<RankedTensorType>();
1706         if (!operandType)
1707           continue;
1708 
1709         // If outs is already an `init_tensor` operation, nothing to do.
1710         auto definingOp = operandVal.getDefiningOp<InitTensorOp>();
1711         if (definingOp)
1712           continue;
1713         modifiedOutput = true;
1714         SmallVector<Value> dynamicDims;
1715         for (const auto &dim : llvm::enumerate(operandType.getShape())) {
1716           if (dim.value() != ShapedType::kDynamicSize)
1717             continue;
1718           dynamicDims.push_back(rewriter.createOrFold<tensor::DimOp>(
1719               loc, operandVal, dim.index()));
1720         }
1721         Value initTensor = rewriter.create<InitTensorOp>(
1722             loc, dynamicDims, operandType.getShape(),
1723             operandType.getElementType());
1724         op->setOperand(opOperand->getOperandNumber(), initTensor);
1725       }
1726     }
1727     if (!modifiedOutput) {
1728       rewriter.cancelRootUpdate(op);
1729       return failure();
1730     }
1731     rewriter.finalizeRootUpdate(op);
1732     return success();
1733   }
1734 };
1735 
1736 } // namespace
1737 
1738 void mlir::linalg::populateFoldReshapeOpsByLinearizationPatterns(
1739     RewritePatternSet &patterns) {
1740   patterns
1741       .add<FoldProducerReshapeOpByLinearization<false, tensor::CollapseShapeOp>,
1742            FoldProducerReshapeOpByLinearization<false, tensor::ExpandShapeOp>,
1743            FoldConsumerReshapeOpByLinearization<false, tensor::CollapseShapeOp>,
1744            FoldConsumerReshapeOpByLinearization<false, tensor::ExpandShapeOp>>(
1745           patterns.getContext());
1746 }
1747 
1748 void mlir::linalg::populateFoldUnitDimsReshapeOpsByLinearizationPatterns(
1749     RewritePatternSet &patterns) {
1750   patterns
1751       .add<FoldProducerReshapeOpByLinearization<true, tensor::CollapseShapeOp>,
1752            FoldProducerReshapeOpByLinearization<true, tensor::ExpandShapeOp>,
1753            FoldConsumerReshapeOpByLinearization<true, tensor::CollapseShapeOp>,
1754            FoldConsumerReshapeOpByLinearization<true, tensor::ExpandShapeOp>>(
1755           patterns.getContext());
1756 }
1757 
1758 void mlir::linalg::populateFoldReshapeOpsByExpansionPatterns(
1759     RewritePatternSet &patterns,
1760     const ControlElementwiseOpsFusionFn &controlFoldingReshapes) {
1761   patterns.add<FoldReshapeWithGenericOpByExpansion>(patterns.getContext(),
1762                                                     controlFoldingReshapes);
1763   patterns.add<FoldWithProducerReshapeOpByExpansion>(patterns.getContext(),
1764                                                      controlFoldingReshapes);
1765 }
1766 
1767 void mlir::linalg::populateElementwiseOpsFusionPatterns(
1768     RewritePatternSet &patterns, LinalgElementwiseFusionOptions options) {
1769   auto *context = patterns.getContext();
1770   patterns.add<FuseElementwiseOps, FoldScalarOrSplatConstant,
1771                FoldConstantTranspose>(context,
1772                                       options.controlElementwiseOpsFusionFn);
1773   patterns.add<RemoveOutsDependency>(context);
1774   populateFoldReshapeOpsByExpansionPatterns(patterns,
1775                                             options.controlFoldingReshapesFn);
1776   AffineApplyOp::getCanonicalizationPatterns(patterns, context);
1777   GenericOp::getCanonicalizationPatterns(patterns, context);
1778   tensor::ExpandShapeOp::getCanonicalizationPatterns(patterns, context);
1779   tensor::CollapseShapeOp::getCanonicalizationPatterns(patterns, context);
1780   context->getLoadedDialect<LinalgDialect>()->getCanonicalizationPatterns(
1781       patterns);
1782 }
1783 
1784 void mlir::linalg::populatePushReshapeOpsPatterns(RewritePatternSet &patterns) {
1785   auto *context = patterns.getContext();
1786   patterns.add<PushExpandingReshape>(context);
1787 }
1788 
1789 std::unique_ptr<Pass> mlir::createLinalgElementwiseOpFusionPass() {
1790   return std::make_unique<LinalgElementwiseOpFusionPass>();
1791 }
1792 
1793 std::unique_ptr<Pass> mlir::createFoldReshapeOpsByLinearizationPass() {
1794   return std::make_unique<FoldReshapeOpsByLinearizationPass>();
1795 }
1796