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                         ArrayRef<int64_t> collapsedShape,
528                         PatternRewriter &rewriter);
529   unsigned getOrigOpNumDims() const { return reassociation.size(); }
530   unsigned getExpandedOpNumDims() const { return expandedOpNumDims; }
531   ReassociationIndicesRef getExpandedDims(unsigned i) const {
532     return reassociation[i];
533   }
534   ArrayRef<int64_t> getExpandedShapeOfDim(unsigned i) const {
535     return expandedShapeMap[i];
536   }
537   ArrayRef<int64_t> getOriginalShape() const { return originalLoopExtent; }
538 
539 private:
540   /// Reassociation from the dimensions in the original operation to the
541   /// dimension of the expanded operation.
542   SmallVector<ReassociationIndices> reassociation;
543   /// Mapping from extent of loops in the original operation, to the extent of
544   /// loops in the expanded operation.
545   SmallVector<SmallVector<int64_t>> expandedShapeMap;
546   /// Extent of the loop in the original operation.
547   SmallVector<int64_t> originalLoopExtent;
548   unsigned expandedOpNumDims;
549 };
550 } // namespace
551 
552 LogicalResult ExpansionInfo::compute(LinalgOp linalgOp,
553                                      OpOperand *fusableOpOperand,
554                                      ArrayRef<AffineMap> reassociationMaps,
555                                      ArrayRef<int64_t> expandedShape,
556                                      ArrayRef<int64_t> collapsedShape,
557                                      PatternRewriter &rewriter) {
558   if (reassociationMaps.empty())
559     return failure();
560   AffineMap fusedIndexMap = linalgOp.getTiedIndexingMap(fusableOpOperand);
561 
562   Optional<SmallVector<int64_t, 4>> originalLoopRange =
563       linalgOp.getStaticLoopRanges();
564   if (!originalLoopRange)
565     return rewriter.notifyMatchFailure(linalgOp, "unable to find loop range");
566   originalLoopExtent.assign(originalLoopRange->begin(),
567                             originalLoopRange->end());
568 
569   reassociation.clear();
570   expandedShapeMap.clear();
571   // Compute the number of dimension in the expanded op that correspond to each
572   // dimension of the original op.
573   SmallVector<unsigned> numExpandedDims(fusedIndexMap.getNumDims(), 1);
574   expandedShapeMap.resize(fusedIndexMap.getNumDims());
575   for (const auto &resultExpr : llvm::enumerate(fusedIndexMap.getResults())) {
576     unsigned pos = resultExpr.value().cast<AffineDimExpr>().getPosition();
577     AffineMap foldedDims = reassociationMaps[resultExpr.index()];
578     numExpandedDims[pos] = foldedDims.getNumResults();
579     ArrayRef<int64_t> shape =
580         expandedShape.slice(foldedDims.getDimPosition(0), numExpandedDims[pos]);
581     expandedShapeMap[pos].assign(shape.begin(), shape.end());
582   }
583   // The remaining dimensions remain the same.
584   for (unsigned i : llvm::seq<unsigned>(0, fusedIndexMap.getNumDims()))
585     if (expandedShapeMap[i].empty())
586       expandedShapeMap[i] = {originalLoopExtent[i]};
587 
588   // Compute reassociation map from the original op to the expanded op.
589   unsigned sum = 0;
590   reassociation.reserve(fusedIndexMap.getNumDims());
591   for (const auto &numFoldedDim : llvm::enumerate(numExpandedDims)) {
592     auto seq = llvm::seq<int64_t>(sum, sum + numFoldedDim.value());
593     reassociation.emplace_back(seq.begin(), seq.end());
594     sum += numFoldedDim.value();
595   }
596   expandedOpNumDims = sum;
597   return success();
598 }
599 
600 /// Epanding the body of a linalg operation requires adaptations of the accessed
601 /// loop indices. Specifically, access of indices in the original operation need
602 /// to be replaced with linearizations of indices in the expanded op. That
603 /// requires the shape of the expanded dimensions to be static (at least all but
604 /// the most significant). For now check that these are all statically sized.
605 /// Note that this could be extended to handle dynamic case, but the
606 /// implementation below uses `affine.apply` which seems to have issues when the
607 /// shapes are not static.
608 LogicalResult isGenericOpExpandable(GenericOp genericOp,
609                                     const ExpansionInfo &expansionInfo,
610                                     PatternRewriter &rewriter) {
611   // Current reshape only supports expansion of a dynamic dim when only one of
612   // the expanded dims are dynamic.
613   for (const auto &originalShape :
614        llvm::enumerate(expansionInfo.getOriginalShape()))
615     if (ShapedType::isDynamic(originalShape.value())) {
616       // All but one of the expanded dims must be static.
617       bool foundDynamicExpandedDim = false;
618       for (auto expandedShape :
619            expansionInfo.getExpandedShapeOfDim(originalShape.index())) {
620         if (ShapedType::isDynamic(expandedShape)) {
621           if (foundDynamicExpandedDim) {
622             return rewriter.notifyMatchFailure(
623                 genericOp,
624                 "cannot expanded dynamic dims into multiple dynamic dims");
625           }
626           foundDynamicExpandedDim = true;
627         }
628       }
629       if (!foundDynamicExpandedDim) {
630         return rewriter.notifyMatchFailure(
631             genericOp, "dynamic dim expansion needs at least one dynamic dim "
632                        "in result shape");
633       }
634     }
635 
636   if (!genericOp.hasIndexSemantics())
637     return success();
638   for (unsigned i : llvm::seq<unsigned>(0, expansionInfo.getOrigOpNumDims())) {
639     ArrayRef<int64_t> expandedShape = expansionInfo.getExpandedShapeOfDim(i);
640     if (expandedShape.size() == 1)
641       continue;
642     for (int64_t shape : expandedShape.drop_front()) {
643       if (ShapedType::isDynamic(shape)) {
644         return rewriter.notifyMatchFailure(
645             genericOp, "cannot expand due to index semantics and dynamic dims");
646       }
647     }
648   }
649   return success();
650 }
651 
652 /// Return the indexing map to use in the expanded op for a given the
653 /// `indexingMap` of the original operation.
654 static AffineMap
655 getIndexingMapInExpandedOp(OpBuilder &builder, AffineMap indexingMap,
656                            const ExpansionInfo &expansionInfo) {
657   SmallVector<AffineExpr> newExprs;
658   for (AffineExpr expr : indexingMap.getResults()) {
659     unsigned pos = expr.cast<AffineDimExpr>().getPosition();
660     SmallVector<AffineExpr, 4> expandedExprs = llvm::to_vector<4>(
661         llvm::map_range(expansionInfo.getExpandedDims(pos), [&](int64_t v) {
662           return builder.getAffineDimExpr(static_cast<unsigned>(v));
663         }));
664     newExprs.append(expandedExprs.begin(), expandedExprs.end());
665   }
666   return AffineMap::get(expansionInfo.getExpandedOpNumDims(),
667                         indexingMap.getNumSymbols(), newExprs,
668                         builder.getContext());
669 }
670 
671 /// Return the type of the operand/result to use in the expanded op given the
672 /// type in the original op.
673 static RankedTensorType getExpandedType(RankedTensorType originalType,
674                                         AffineMap indexingMap,
675                                         const ExpansionInfo &expansionInfo) {
676   SmallVector<int64_t> expandedShape;
677   for (AffineExpr expr : indexingMap.getResults()) {
678     unsigned dim = expr.cast<AffineDimExpr>().getPosition();
679     auto dimExpansion = expansionInfo.getExpandedShapeOfDim(dim);
680     expandedShape.append(dimExpansion.begin(), dimExpansion.end());
681   }
682   return RankedTensorType::get(expandedShape, originalType.getElementType());
683 }
684 
685 /// Returns the reassociation maps to use in the `tensor.expand_shape`
686 /// operation to convert the operands of the original operation to operands of
687 /// the expanded operation. The same method is used to compute the
688 /// `tensor.collapse_shape` used to collapse the result of the expanded
689 /// op to get the value that can replace all uses of the results of the original
690 /// op.
691 static SmallVector<ReassociationIndices>
692 getReassociationForExpansion(AffineMap indexingMap,
693                              const ExpansionInfo &expansionInfo) {
694   SmallVector<ReassociationIndices> reassociation;
695   unsigned numReshapeDims = 0;
696   for (AffineExpr expr : indexingMap.getResults()) {
697     unsigned dim = expr.cast<AffineDimExpr>().getPosition();
698     auto numExpandedDims = expansionInfo.getExpandedDims(dim).size();
699     SmallVector<int64_t, 2> indices = llvm::to_vector<2>(
700         llvm::seq<int64_t>(numReshapeDims, numReshapeDims + numExpandedDims));
701     reassociation.emplace_back(std::move(indices));
702     numReshapeDims += numExpandedDims;
703   }
704   return reassociation;
705 }
706 
707 /// Update the body of an expanded linalg operation having index semantics. The
708 /// indices of the original operation need to be recovered by linearizing the
709 /// indices of the correspoding dimensions of the expanded operation. For now it
710 /// is assumed that the shapes of the expanded operation needed for
711 /// linearization are static.
712 static void updateExpandedGenericOpRegion(PatternRewriter &rewriter,
713                                           Location loc, Region &fusedRegion,
714                                           const ExpansionInfo &expansionInfo) {
715   // Replace the original indices by the linearization of the expanded indices.
716   for (IndexOp indexOp :
717        llvm::make_early_inc_range(fusedRegion.front().getOps<IndexOp>())) {
718     ArrayRef<int64_t> expandedDims =
719         expansionInfo.getExpandedDims(indexOp.dim());
720     assert(!expandedDims.empty() && "expected valid expansion info");
721 
722     // Skip index operations that are not affected by the expansion.
723     if (expandedDims.size() == 1 &&
724         expandedDims.front() == (int64_t)indexOp.dim())
725       continue;
726 
727     // Linearize the expanded indices of the original index dimension.
728     OpBuilder::InsertionGuard guard(rewriter);
729     rewriter.setInsertionPointAfter(indexOp);
730     ArrayRef<int64_t> expandedDimsShape =
731         expansionInfo.getExpandedShapeOfDim(indexOp.dim()).drop_front();
732     SmallVector<Value> expandedIndices;
733     expandedIndices.reserve(expandedDims.size() - 1);
734     llvm::transform(
735         expandedDims.drop_front(), std::back_inserter(expandedIndices),
736         [&](int64_t dim) { return rewriter.create<IndexOp>(loc, dim); });
737     Value newIndex = rewriter.create<IndexOp>(loc, expandedDims.front());
738     for (auto it : llvm::zip(expandedDimsShape, expandedIndices)) {
739       assert(!ShapedType::isDynamic(std::get<0>(it)));
740       AffineExpr idx, acc;
741       bindDims(rewriter.getContext(), idx, acc);
742       newIndex = rewriter.create<AffineApplyOp>(
743           indexOp.getLoc(), idx + acc * std::get<0>(it),
744           ValueRange{std::get<1>(it), newIndex});
745     }
746     rewriter.replaceOp(indexOp, newIndex);
747   }
748 }
749 
750 /// Implements the fusion of a tensor_collapse_shape or a tensor_expand_shape op
751 /// and a generic op as explained in `isFusableWithReshapeByExpansion`. Assumes
752 /// that those conditions have been satisfied.
753 static Optional<SmallVector<Value>>
754 fuseWithReshapeByExpansion(GenericOp genericOp, Operation *reshapeOp,
755                            OpOperand *fusableOpOperand,
756                            PatternRewriter &rewriter) {
757   assert(isFusableWithReshapeByDimExpansion(genericOp, fusableOpOperand) &&
758          "preconditions for fuse operation failed");
759   // Check if reshape is expanding or collapsing.
760   auto expandingReshapeOp = dyn_cast<tensor::ExpandShapeOp>(*reshapeOp);
761   auto collapsingReshapeOp = dyn_cast<tensor::CollapseShapeOp>(*reshapeOp);
762   bool isExpanding = (expandingReshapeOp != nullptr);
763   RankedTensorType expandedType = isExpanding
764                                       ? expandingReshapeOp.getResultType()
765                                       : collapsingReshapeOp.getSrcType();
766   RankedTensorType collapsedType = isExpanding
767                                        ? expandingReshapeOp.getSrcType()
768                                        : collapsingReshapeOp.getResultType();
769 
770   ExpansionInfo expansionInfo;
771   if (failed(expansionInfo.compute(
772           genericOp, fusableOpOperand,
773           isExpanding ? expandingReshapeOp.getReassociationMaps()
774                       : collapsingReshapeOp.getReassociationMaps(),
775           expandedType.getShape(), collapsedType.getShape(), rewriter)))
776     return llvm::None;
777 
778   if (failed(isGenericOpExpandable(genericOp, expansionInfo, rewriter)))
779     return llvm::None;
780 
781   SmallVector<AffineMap, 4> expandedOpIndexingMaps = llvm::to_vector<4>(
782       llvm::map_range(genericOp.getIndexingMaps(), [&](AffineMap m) {
783         return getIndexingMapInExpandedOp(rewriter, m, expansionInfo);
784       }));
785 
786   SmallVector<Value> expandedOpOperands;
787   expandedOpOperands.reserve(genericOp.getNumInputs());
788   for (OpOperand *opOperand : genericOp.getInputOperands()) {
789     if (opOperand == fusableOpOperand) {
790       expandedOpOperands.push_back(isExpanding ? expandingReshapeOp.src()
791                                                : collapsingReshapeOp.src());
792       continue;
793     }
794     if (genericOp.isInputTensor(opOperand)) {
795       AffineMap indexingMap = genericOp.getTiedIndexingMap(opOperand);
796       RankedTensorType expandedOperandType =
797           getExpandedType(opOperand->get().getType().cast<RankedTensorType>(),
798                           indexingMap, expansionInfo);
799       if (expandedOperandType != opOperand->get().getType()) {
800         // Reshape the operand to get the right type.
801         SmallVector<ReassociationIndices> reassociation =
802             getReassociationForExpansion(indexingMap, expansionInfo);
803         expandedOpOperands.push_back(rewriter.create<tensor::ExpandShapeOp>(
804             genericOp.getLoc(), expandedOperandType, opOperand->get(),
805             reassociation));
806         continue;
807       }
808     }
809     expandedOpOperands.push_back(opOperand->get());
810   }
811 
812   Location loc = genericOp.getLoc();
813   SmallVector<Value> outputs;
814   for (OpOperand *opOperand : genericOp.getOutputOperands()) {
815     AffineMap indexingMap = genericOp.getTiedIndexingMap(opOperand);
816     RankedTensorType expandedOutputType =
817         getExpandedType(opOperand->get().getType().cast<RankedTensorType>(),
818                         indexingMap, expansionInfo);
819     if (expandedOutputType != opOperand->get().getType()) {
820       SmallVector<ReassociationIndices> reassociation =
821           getReassociationForExpansion(indexingMap, expansionInfo);
822       outputs.push_back(rewriter.create<tensor::ExpandShapeOp>(
823           genericOp.getLoc(), expandedOutputType, opOperand->get(),
824           reassociation));
825     }
826   }
827 
828   // The iterator types of the expanded op are all parallel.
829   SmallVector<StringRef> iteratorTypes(expansionInfo.getExpandedOpNumDims(),
830                                        getParallelIteratorTypeName());
831 
832   TypeRange resultTypes = ValueRange(outputs).getTypes();
833   auto fusedOp =
834       rewriter.create<GenericOp>(genericOp.getLoc(), resultTypes,
835                                  /*inputs=*/expandedOpOperands, outputs,
836                                  expandedOpIndexingMaps, iteratorTypes);
837   Region &fusedRegion = fusedOp->getRegion(0);
838   Region &originalRegion = genericOp->getRegion(0);
839   rewriter.cloneRegionBefore(originalRegion, fusedRegion, fusedRegion.begin());
840 
841   // Update the index accesses after the expansion.
842   updateExpandedGenericOpRegion(rewriter, loc, fusedRegion, expansionInfo);
843 
844   // Reshape the result values to their original shape if this is a collapsing
845   // reshape folded into its consumer.
846   SmallVector<Value> resultVals;
847   for (OpResult opResult : genericOp->getOpResults()) {
848     int64_t resultNumber = opResult.getResultNumber();
849     if (!isExpanding && resultTypes[resultNumber] != opResult.getType()) {
850       SmallVector<ReassociationIndices> reassociation =
851           getReassociationForExpansion(
852               genericOp.getTiedIndexingMap(
853                   genericOp.getOutputOperand(resultNumber)),
854               expansionInfo);
855       resultVals.push_back(rewriter.create<tensor::CollapseShapeOp>(
856           genericOp.getLoc(), opResult.getType(),
857           fusedOp->getResult(resultNumber), reassociation));
858     } else {
859       resultVals.push_back(fusedOp->getResult(resultNumber));
860     }
861   }
862   // Assuming a single result.
863   return resultVals;
864 }
865 
866 namespace {
867 
868 /// Pattern to fold tensor_expand_shape op with its consumer by using the source
869 /// of the reshape op as the operand in the consumer (instead of the result of
870 /// the tensor_collapse_shape). The corresponding index map in the consumer
871 /// needs to be modified to linearize the folded dimension.
872 ///
873 /// For example,
874 ///
875 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
876 /// %0 = tensor.expand_shape %arg0 [[0], [1, 2], [3]]
877 ///      tensor<?x?x?xf32> into tensor<?x?x4x?xf32>
878 /// %1 = linalg.generic { indexing_maps = [#map0, #map0, #map0], ... }
879 ///        ins(%0, %arg1 : tensor<?x?x4x?xf32>, tensor<?x?x4x?xf32>) ...
880 ///        -> tensor<?x?x4x?xf32>
881 ///
882 /// can be folded into
883 ///
884 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1 * 4 + d2, d3)>
885 /// #map1 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
886 /// %0 = linalg.generic { indexing_maps = [#map0, #map1, #map1] ... }
887 ///        ins(%arg0, %arg1 : tensor<?x?x?xf32>, tensor<?x?x4x?xf32>) ...
888 ///        -> tensor<?x?x4x?xf32>
889 template <bool foldUnitDimReshapesOnly, typename TensorReshapeOp>
890 struct FoldProducerReshapeOpByLinearization
891     : public OpRewritePattern<GenericOp> {
892   using OpRewritePattern<GenericOp>::OpRewritePattern;
893 
894   LogicalResult matchAndRewrite(GenericOp genericOp,
895                                 PatternRewriter &rewriter) const override {
896     if (!genericOp.hasTensorSemantics())
897       return failure();
898     SmallVector<OpOperand *> inputOperands = genericOp.getInputOperands();
899     for (const auto &en : llvm::enumerate(inputOperands)) {
900       auto reshapeOp = en.value()->get().getDefiningOp<TensorReshapeOp>();
901       if (!reshapeOp)
902         continue;
903 
904       if (!isTensorReshapeOpFoldableByLinearization(
905               reshapeOp, genericOp.getTiedIndexingMap(en.value()),
906               /*asProducer =*/true) ||
907           (foldUnitDimReshapesOnly && !isUnitDimExpansionOnly(reshapeOp)))
908         continue;
909 
910       // Compute the fused operands list,
911       SmallVector<Value> fusedOperands = genericOp.getInputOperands();
912       fusedOperands[en.index()] = reshapeOp.src();
913       SmallVector<Value> outputOperands = genericOp.getOutputOperands();
914       llvm::append_range(fusedOperands, outputOperands);
915 
916       // Compute indexing_maps for the fused operation. The indexing_maps for
917       // the operands of the consumers that arent fused are the same.
918       SmallVector<AffineMap> fusedIndexMaps = genericOp.getIndexingMaps();
919 
920       // Accepted consumer maps are either identity or permutation.
921       auto invMap = inversePermutation(fusedIndexMaps[en.index()]);
922 
923       // Compute the indexing map to use for the result of the producer.
924       AffineMap modifiedMap = linearizeCollapsedDims(invMap, reshapeOp);
925       // The modified map cannot have symbols.
926       if (modifiedMap.getNumSymbols())
927         return failure();
928       for (AffineExpr expr : modifiedMap.getResults()) {
929         if (!expr.isPureAffine())
930           return failure();
931       }
932       fusedIndexMaps[en.index()] = modifiedMap;
933 
934       // Further check that the resulting index maps can be fused and
935       // inverted. Without this the resultant op is not legal.
936       if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) {
937         return rewriter.notifyMatchFailure(
938             genericOp, "fused op loop bound computation failed");
939       }
940 
941       rewriter.startRootUpdate(genericOp);
942       genericOp->setOperands(fusedOperands);
943       genericOp.indexing_mapsAttr(
944           rewriter.getAffineMapArrayAttr(fusedIndexMaps));
945       rewriter.finalizeRootUpdate(genericOp);
946       return success();
947     }
948     return failure();
949   }
950 };
951 
952 static SmallVector<ReassociationIndices>
953 getReassociationIndices(ArrayRef<AffineMap> maps) {
954   SmallVector<ReassociationIndices> reassociation;
955   for (AffineMap map : maps) {
956     ReassociationIndices indices;
957     for (unsigned i = 0, e = map.getNumResults(); i < e; i++) {
958       unsigned pos = map.getResult(i).cast<AffineDimExpr>().getPosition();
959       indices.push_back(pos);
960     }
961     reassociation.push_back(indices);
962   }
963   return reassociation;
964 }
965 
966 /// Pattern to move rank reducing reshape after an elementwise linalg generic
967 /// op. This is useful to expose more fusion opportunities between named ops and
968 /// generic ops. This can only be done if there is no broadcast or permuation
969 /// within the dimensions we need to merge.
970 ///
971 /// For example,
972 ///
973 ///  %0 = tensor.expand_shape %A [[0, 1], [2]]
974 ///      : tensor<12544x16xf32> into tensor<112x112x16xf32>
975 ///  %2 = linalg.generic {indexing_maps = [
976 ///    affine_map<(d0, d1, d2) -> (d0, d1, d2)>,
977 ///    affine_map<(d0, d1, d2) -> (d2)>,
978 ///    affine_map<(d0, d1, d2) -> (d0, d1, d2)>], iterator_types =
979 ///    ["parallel", "parallel", "parallel"]} {
980 ///  } -> tensor<112x112x16xf32>
981 ///
982 ///  into
983 ///
984 ///  %2 = linalg.generic {indexing_maps = [
985 ///    affine_map<(d0, d1) -> (d0, d1)>,
986 ///    affine_map<(d0, d1) -> (d1)>,
987 ///    affine_map<(d0, d1) -> (d0, d1)>],
988 ///    iterator_types = ["parallel", "parallel"]} ins(%arg0, %arg1
989 ///    : tensor<12544x16xf32>, tensor<16xf32>) outs(%1 : tensor<12544x16xf32>) {
990 ///  } -> tensor<12544x16xf32>
991 ///  %3 = tensor.expand_shape %2 [[0, 1], [2]]
992 ///    : tensor<12544x16xf32> into tensor<112x112x16xf32>
993 struct PushExpandingReshape : public OpRewritePattern<GenericOp> {
994   using OpRewritePattern<GenericOp>::OpRewritePattern;
995 
996   LogicalResult matchAndRewrite(GenericOp genericOp,
997                                 PatternRewriter &rewriter) const override {
998     // Only apply to elementwise linalg on tensor.
999     if (!genericOp.hasTensorSemantics() ||
1000         genericOp.getNumParallelLoops() != genericOp.getNumLoops())
1001       return failure();
1002     // Only support identity output maps. It could be extended to permuations if
1003     // needed.
1004     if (llvm::any_of(genericOp.getOutputOperands(), [&](OpOperand *opOperand) {
1005           return !genericOp.getTiedIndexingMap(opOperand).isIdentity();
1006         }))
1007       return failure();
1008     int64_t destRank = genericOp.getNumParallelLoops();
1009     SmallVector<Value> newOperands = genericOp.getInputOperands();
1010     tensor::ExpandShapeOp reshapeFound;
1011     // 1. Look for tensor_expand_shape operands and figure out save the
1012     // dimensions merged.
1013     SmallVector<OpOperand *> inputOperands = genericOp.getInputOperands();
1014     for (const auto &en : llvm::enumerate(inputOperands)) {
1015       auto reshapeOp =
1016           en.value()->get().template getDefiningOp<tensor::ExpandShapeOp>();
1017       if (!reshapeOp)
1018         continue;
1019       // TODO: We could support non-identity map as long as the merged
1020       // dimensions are still contiguous.
1021       if (!genericOp.getTiedIndexingMap(en.value()).isIdentity())
1022         continue;
1023       if (reshapeFound) {
1024         // Only support a second reshape op if it has the same reassociate maps.
1025         if (reshapeFound.getReassociationMaps() ==
1026             reshapeOp.getReassociationMaps())
1027           newOperands[en.index()] = reshapeOp.src();
1028         continue;
1029       }
1030       reshapeFound = reshapeOp;
1031       newOperands[en.index()] = reshapeOp.src();
1032     }
1033     if (!reshapeFound)
1034       return failure();
1035 
1036     // Calculate the reassociation indices and rassociated reverse map.
1037     SmallVector<ReassociationIndices> reassociation =
1038         getReassociationIndices(reshapeFound.getReassociationMaps());
1039     SmallVector<unsigned> remap(destRank);
1040     for (auto &indices : llvm::enumerate(reassociation)) {
1041       for (int64_t index : indices.value()) {
1042         remap[index] = indices.index();
1043       }
1044     }
1045     // 2. Verify that we can merge the dimensions in the linalg and that we
1046     // don't need to create new reshapes operands. Inserting new reshape
1047     // operands would defeat the purpose of the transformation.
1048     for (const auto &en : llvm::enumerate(inputOperands)) {
1049       if (en.value()->get() == newOperands[en.index()]) {
1050         AffineMap map = genericOp.getTiedIndexingMap(en.value());
1051         for (unsigned i : llvm::seq(unsigned(0), map.getNumResults())) {
1052           if (reassociation[remap[map.getDimPosition(i)]].size() > 1)
1053             return failure();
1054         }
1055       }
1056     }
1057 
1058     // 3. Calculate the affine map remapping and the reassociation to apply to
1059     // output tensors.
1060     SmallVector<AffineMap> newMaps;
1061     unsigned newRank = reassociation.size();
1062     for (auto map : genericOp.getIndexingMaps()) {
1063       SmallVector<AffineExpr> newExprs;
1064       for (auto expr : map.getResults()) {
1065         unsigned position = expr.template cast<AffineDimExpr>().getPosition();
1066         // Skip dimension merged except for the last of the group.
1067         if (reassociation[remap[position]].back() == position) {
1068           newExprs.push_back(
1069               getAffineDimExpr(remap[position], genericOp.getContext()));
1070         }
1071       }
1072       newMaps.push_back(
1073           AffineMap::get(newRank, 0, newExprs, genericOp.getContext()));
1074     }
1075 
1076     // 4. Reshape the output tensors.
1077     SmallVector<Value> newOutputs;
1078     SmallVector<Type> newOutputTypes;
1079     for (auto output : genericOp.outputs()) {
1080       auto newOutputType = RankedTensorType::get(
1081           reshapeFound.getSrcType().getShape(),
1082           output.getType().template cast<RankedTensorType>().getElementType());
1083       Value newOutput = rewriter.create<tensor::CollapseShapeOp>(
1084           genericOp->getLoc(), newOutputType, output, reassociation);
1085       newOutputTypes.push_back(newOutputType);
1086       newOutputs.push_back(newOutput);
1087     }
1088     // 5. Create a new generic op with lowerer rank.
1089     SmallVector<StringRef> iteratorTypes(newRank,
1090                                          getParallelIteratorTypeName());
1091     auto newOp = rewriter.create<GenericOp>(genericOp->getLoc(), newOutputTypes,
1092                                             newOperands, newOutputs, newMaps,
1093                                             iteratorTypes);
1094     rewriter.inlineRegionBefore(genericOp.region(), newOp.region(),
1095                                 newOp.region().begin());
1096     // 6. Reshape the so that the type matches the uses.
1097     SmallVector<Value> newResults;
1098     for (const auto &result : llvm::enumerate(newOp->getResults())) {
1099       newResults.push_back(rewriter.create<tensor::ExpandShapeOp>(
1100           genericOp->getLoc(), genericOp.getOutputTensorTypes()[result.index()],
1101           result.value(), reassociation));
1102     }
1103     rewriter.replaceOp(genericOp, newResults);
1104     return success();
1105   }
1106 };
1107 
1108 /// Pattern to fuse a tensor_collapse_shape op with its consumer generic op,
1109 /// when the reshape op is collapsing dimensions. The dimensionality of the loop
1110 /// in the consumer is expanded.
1111 class FoldWithProducerReshapeOpByExpansion
1112     : public OpRewritePattern<GenericOp> {
1113 public:
1114   FoldWithProducerReshapeOpByExpansion(
1115       MLIRContext *context, ControlElementwiseOpsFusionFn foldReshapes,
1116       PatternBenefit benefit = 1)
1117       : OpRewritePattern<GenericOp>(context, benefit),
1118         controlFoldingReshapes(std::move(foldReshapes)) {}
1119 
1120   LogicalResult matchAndRewrite(GenericOp genericOp,
1121                                 PatternRewriter &rewriter) const override {
1122     for (OpOperand *opOperand : genericOp.getInputTensorOperands()) {
1123       tensor::CollapseShapeOp reshapeOp =
1124           opOperand->get().getDefiningOp<tensor::CollapseShapeOp>();
1125       if (!reshapeOp)
1126         continue;
1127       // Fold only if
1128       // - The tensor reshape op is folding.
1129       // - All constraints of fusing with reshape by expansion are met.
1130       if (!isFusableWithReshapeByDimExpansion(genericOp, opOperand) ||
1131           (!controlFoldingReshapes(reshapeOp->getResult(0), *opOperand)))
1132         continue;
1133 
1134       Optional<SmallVector<Value>> replacementValues =
1135           fuseWithReshapeByExpansion(genericOp, reshapeOp, opOperand, rewriter);
1136       if (!replacementValues)
1137         return failure();
1138       rewriter.replaceOp(genericOp, replacementValues.getValue());
1139       return success();
1140     }
1141     return failure();
1142   }
1143 
1144 private:
1145   ControlElementwiseOpsFusionFn controlFoldingReshapes;
1146 };
1147 
1148 /// Pattern to fold tensor_collapse_shape or tensor_expand_shape op with its
1149 /// producer. The corresponding index map in the consumer needs to be modified
1150 /// to linearize the folded dimension.
1151 template <bool foldUnitDimReshapesOnly, typename TensorReshapeOp>
1152 struct FoldConsumerReshapeOpByLinearization
1153     : public OpRewritePattern<TensorReshapeOp> {
1154   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
1155 
1156   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
1157                                 PatternRewriter &rewriter) const override {
1158     GenericOp producer = reshapeOp.src().template getDefiningOp<GenericOp>();
1159     if (!producer || !producer.hasTensorSemantics() ||
1160         producer.getNumOutputs() != 1 ||
1161         !isTensorReshapeOpFoldableByLinearization(
1162             reshapeOp,
1163             producer.getTiedIndexingMap(producer.getOutputOperand(0)),
1164             /*asProducer =*/false) ||
1165         (foldUnitDimReshapesOnly && !isUnitDimExpansionOnly(reshapeOp)))
1166       return failure();
1167     // The indexing_maps for the operands of the fused operation are same as
1168     // those for the operands of the producer.
1169     SmallVector<AffineMap> fusedIndexMaps = producer.getIndexingMaps();
1170 
1171     auto invMap = inversePermutation(
1172         producer.getTiedIndexingMap(producer.getOutputOperand(0)));
1173 
1174     // Compute the indexing map to use for the operand of the producer.
1175     AffineMap modifiedMap = linearizeCollapsedDims(invMap, reshapeOp);
1176     for (AffineExpr expr : modifiedMap.getResults()) {
1177       if (!expr.isPureAffine()) {
1178         return rewriter.notifyMatchFailure(
1179             producer, "fused op indexing map is not affine");
1180       }
1181     }
1182     fusedIndexMaps.back() = modifiedMap;
1183 
1184     // Further check that the resulting index maps can be fused and
1185     // inverted. Without this the resultant op is not legal.
1186     if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) {
1187       return rewriter.notifyMatchFailure(
1188           producer, "fused op loop bound computation failed");
1189     }
1190 
1191     Location loc = producer.getLoc();
1192     SmallVector<Value> inputOperands = producer.getInputOperands();
1193     Value output = rewriter.create<TensorReshapeOp>(
1194         loc, producer.getOutputOperand(0)->get(),
1195         reshapeOp.getReassociationExprs());
1196     auto fusedOp = rewriter.create<GenericOp>(
1197         loc, reshapeOp.getResultType(),
1198         /*inputs=*/inputOperands,
1199         // TODO: handle outputs.
1200         /*outputs=*/output, rewriter.getAffineMapArrayAttr(fusedIndexMaps),
1201         producer.iterator_types(),
1202         /*doc=*/nullptr,
1203         /*library_call=*/nullptr);
1204     auto &fusedRegion = fusedOp->getRegion(0);
1205     rewriter.cloneRegionBefore(producer->getRegion(0), fusedRegion,
1206                                fusedRegion.begin());
1207     rewriter.replaceOp(reshapeOp, fusedOp->getResults());
1208     return success();
1209   }
1210 };
1211 
1212 /// Pattern to fold a tensor_expand_shape op with its producer generic op
1213 /// by expanding the dimensionality of the loop in the producer op.
1214 struct FoldReshapeWithGenericOpByExpansion
1215     : public OpRewritePattern<tensor::ExpandShapeOp> {
1216 
1217   FoldReshapeWithGenericOpByExpansion(
1218       MLIRContext *context, ControlElementwiseOpsFusionFn foldReshapes,
1219       PatternBenefit benefit = 1)
1220       : OpRewritePattern<tensor::ExpandShapeOp>(context, benefit),
1221         controlFoldingReshapes(std::move(foldReshapes)) {}
1222 
1223   LogicalResult matchAndRewrite(tensor::ExpandShapeOp reshapeOp,
1224                                 PatternRewriter &rewriter) const override {
1225     // Fold only if all constraints of fusing with reshape by expansion are met.
1226     GenericOp producer = reshapeOp.src().getDefiningOp<GenericOp>();
1227     if (!producer || producer.getNumOutputs() != 1 ||
1228         !isFusableWithReshapeByDimExpansion(producer,
1229                                             producer.getOutputOperand(0)) ||
1230         !controlFoldingReshapes(producer->getResult(0),
1231                                 reshapeOp->getOpOperand(0)))
1232       return failure();
1233     Optional<SmallVector<Value>> replacementValues = fuseWithReshapeByExpansion(
1234         producer, reshapeOp, producer.getOutputOperand(0), rewriter);
1235     if (!replacementValues)
1236       return failure();
1237     rewriter.replaceOp(reshapeOp, replacementValues.getValue());
1238     return success();
1239   }
1240 
1241 private:
1242   ControlElementwiseOpsFusionFn controlFoldingReshapes;
1243 };
1244 
1245 /// Pattern to fold a generic op with a splat constant/scalar constant. Does not
1246 /// handle cases where the constant is not single-valued.
1247 class FoldScalarOrSplatConstant : public OpRewritePattern<GenericOp> {
1248 public:
1249   FoldScalarOrSplatConstant(MLIRContext *context,
1250                             ControlElementwiseOpsFusionFn &fun,
1251                             PatternBenefit benefit = 1)
1252       : OpRewritePattern<GenericOp>(context, benefit), controlFn(fun) {}
1253 
1254   LogicalResult matchAndRewrite(GenericOp genericOp,
1255                                 PatternRewriter &rewriter) const override {
1256     if (!genericOp.hasTensorSemantics())
1257       return failure();
1258     for (OpOperand *opOperand : genericOp.getInputOperands()) {
1259       Operation *def = opOperand->get().getDefiningOp();
1260       Attribute constantAttr;
1261       auto isScalarOrSplatConstantOp = [&constantAttr](Operation *def) -> bool {
1262         {
1263           DenseElementsAttr splatAttr;
1264           if (matchPattern(def, m_Constant<DenseElementsAttr>(&splatAttr)) &&
1265               splatAttr.isSplat() &&
1266               splatAttr.getType().getElementType().isIntOrFloat()) {
1267             constantAttr = splatAttr.getSplatValue<Attribute>();
1268             return true;
1269           }
1270         }
1271         {
1272           IntegerAttr intAttr;
1273           if (matchPattern(def, m_Constant<IntegerAttr>(&intAttr))) {
1274             constantAttr = intAttr;
1275             return true;
1276           }
1277         }
1278         {
1279           FloatAttr floatAttr;
1280           if (matchPattern(def, m_Constant<FloatAttr>(&floatAttr))) {
1281             constantAttr = floatAttr;
1282             return true;
1283           }
1284         }
1285         return false;
1286       };
1287 
1288       auto resultValue = opOperand->get().dyn_cast<OpResult>();
1289       if (!def || !resultValue || !isScalarOrSplatConstantOp(def) ||
1290           !controlFn(resultValue, *opOperand))
1291         continue;
1292 
1293       // The operands and the indexing_maps of the fused operation the same as
1294       // the operands and indexing_maps of the generic operations with the
1295       // values at the constant index dropped.
1296       SmallVector<AffineMap> fusedIndexMaps;
1297       SmallVector<Value> fusedOperands;
1298       SmallVector<Location> fusedLocs{genericOp.getLoc()};
1299       fusedIndexMaps.reserve(genericOp.getNumInputsAndOutputs());
1300       fusedOperands.reserve(genericOp.getNumInputs());
1301       fusedLocs.reserve(fusedLocs.size() + genericOp.getNumInputs());
1302       for (OpOperand *inputOperand : genericOp.getInputOperands()) {
1303         if (inputOperand == opOperand)
1304           continue;
1305         Value inputValue = inputOperand->get();
1306         fusedIndexMaps.push_back(genericOp.getTiedIndexingMap(inputOperand));
1307         fusedOperands.push_back(inputValue);
1308         fusedLocs.push_back(inputValue.getLoc());
1309       }
1310       for (OpOperand *outputOperand : genericOp.getOutputOperands())
1311         fusedIndexMaps.push_back(genericOp.getTiedIndexingMap(outputOperand));
1312 
1313       // Check if the operation shapes to loops map is computable.
1314       if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) {
1315         return rewriter.notifyMatchFailure(
1316             genericOp, "fused op loop bound computation failed");
1317       }
1318 
1319       // Create a constant scalar value from the splat constant.
1320       Value scalarConstant = rewriter.create<arith::ConstantOp>(
1321           def->getLoc(), constantAttr, constantAttr.getType());
1322 
1323       SmallVector<Value> outputOperands = genericOp.getOutputOperands();
1324       auto fusedOp = rewriter.create<GenericOp>(
1325           rewriter.getFusedLoc(fusedLocs), genericOp->getResultTypes(),
1326           /*inputs=*/fusedOperands,
1327           /*outputs=*/outputOperands,
1328           rewriter.getAffineMapArrayAttr(fusedIndexMaps),
1329           genericOp.iterator_types(),
1330           /*doc=*/nullptr,
1331           /*library_call=*/nullptr);
1332 
1333       // Map the block argument corresponding to the replaced argument with the
1334       // scalar constant.
1335       Region &region = genericOp->getRegion(0);
1336       Block &entryBlock = *region.begin();
1337       BlockAndValueMapping mapping;
1338       mapping.map(entryBlock.getArgument(opOperand->getOperandNumber()),
1339                   scalarConstant);
1340       Region &fusedRegion = fusedOp->getRegion(0);
1341       rewriter.cloneRegionBefore(region, fusedRegion, fusedRegion.begin(),
1342                                  mapping);
1343       rewriter.replaceOp(genericOp, fusedOp->getResults());
1344       return success();
1345     }
1346     return failure();
1347   }
1348 
1349 private:
1350   ControlElementwiseOpsFusionFn controlFn;
1351 };
1352 
1353 /// Base class for constant folding linalg.generic ops with N inputs, 1 output,
1354 /// and permutation indexing maps.
1355 ///
1356 /// `ConcreteType` should provide methods with signatures
1357 ///
1358 /// ```c++
1359 ///   bool matchIndexingMaps(GenericOp genericOp) const;
1360 ///   RegionComputationFn getRegionComputeFn(GenericOp) const;
1361 /// ```
1362 ///
1363 /// The latter inspects the region and returns the computation inside as a
1364 /// functor. The functor will be invoked with constant elements for all inputs
1365 /// and should return the corresponding computea constant element for output.
1366 template <typename ConcreteType>
1367 class FoldConstantBase : public OpRewritePattern<GenericOp> {
1368 public:
1369   struct APIntOrFloat {
1370     Optional<APInt> apInt;
1371     Optional<APFloat> apFloat;
1372   };
1373   struct APIntOrFloatArray {
1374     SmallVector<APInt> apInts;
1375     SmallVector<APFloat> apFloats;
1376   };
1377   using RegionComputationFn =
1378       std::function<APIntOrFloat(const APIntOrFloatArray &)>;
1379 
1380   FoldConstantBase(MLIRContext *context,
1381                    const ControlElementwiseOpsFusionFn &controlFn,
1382                    PatternBenefit benefit = 1)
1383       : OpRewritePattern<GenericOp>(context, benefit), controlFn(controlFn) {}
1384 
1385   LogicalResult matchAndRewrite(GenericOp genericOp,
1386                                 PatternRewriter &rewriter) const override {
1387     if (genericOp.hasBufferSemantics())
1388       return failure();
1389 
1390     // Only support ops generating one output for now.
1391     if (genericOp.getNumOutputs() != 1)
1392       return failure();
1393 
1394     auto outputType = genericOp.getResultTypes().front().dyn_cast<ShapedType>();
1395     // Require the output types to be static give we are generating constants.
1396     if (!outputType || !outputType.hasStaticShape())
1397       return failure();
1398 
1399     if (!llvm::all_of(genericOp.getInputOperands(), [](OpOperand *operand) {
1400           return operand->get().getType().isa<ShapedType>();
1401         }))
1402       return failure();
1403 
1404     // Make sure all element types are the same.
1405     auto getOperandElementType = [](OpOperand *operand) {
1406       return operand->get().getType().cast<ShapedType>().getElementType();
1407     };
1408     if (!llvm::is_splat(llvm::map_range(genericOp.getInputAndOutputOperands(),
1409                                         getOperandElementType)))
1410       return failure();
1411 
1412     // We can only handle the case where we have int/float elements.
1413     auto elementType = outputType.getElementType();
1414     if (!elementType.isIntOrFloat())
1415       return failure();
1416 
1417     // Require all indexing maps to be permutations for now. This is common and
1418     // it simplifies input/output access greatly: we can do the data shuffling
1419     // entirely in the compiler, without needing to turn all indices into
1420     // Values, and then do affine apply on them, and then match back the
1421     // constant again.
1422     if (!llvm::all_of(genericOp.getIndexingMaps(),
1423                       [](AffineMap map) { return map.isPermutation(); }))
1424       return failure();
1425 
1426     for (OpOperand *operand : genericOp.getOutputOperands()) {
1427       if (genericOp.payloadUsesValueFromOperand(operand))
1428         return failure();
1429     }
1430 
1431     // Further check the indexing maps are okay for the ConcreteType.
1432     if (!static_cast<const ConcreteType *>(this)->matchIndexingMaps(genericOp))
1433       return failure();
1434 
1435     // Defer to the concrete type to check the region and discover the
1436     // computation inside.
1437     RegionComputationFn computeFn =
1438         static_cast<const ConcreteType *>(this)->getRegionComputeFn(genericOp);
1439     if (!computeFn)
1440       return failure();
1441 
1442     // All inputs should be constants.
1443     int numInputs = genericOp.getNumInputs();
1444     SmallVector<DenseIntOrFPElementsAttr> inputValues(numInputs);
1445     for (const auto &operand : llvm::enumerate(genericOp.getInputOperands())) {
1446       if (!matchPattern(operand.value()->get(),
1447                         m_Constant(&inputValues[operand.index()])))
1448         return failure();
1449     }
1450 
1451     // Identified this as a potential candidate for folding. Now check the
1452     // policy to see whether we are allowed to proceed.
1453     for (int i = 0; i < numInputs; ++i) {
1454       OpOperand *consumer = genericOp.getInputOperand(i);
1455       OpResult producer = consumer->get().cast<OpResult>();
1456       if (!controlFn(producer, *consumer))
1457         return failure();
1458     }
1459 
1460     auto linalgOp = cast<LinalgOp>(genericOp.getOperation());
1461     SmallVector<int64_t, 4> loopBounds = linalgOp.computeStaticLoopSizes();
1462     int64_t numElements = outputType.getNumElements();
1463 
1464     // Use APInt/APFloat instead of Attribute here for constructing the output.
1465     // This helps to avoid blowing up compiler memory usage: Attributes would
1466     // unify the following cases but they have lifetime as the MLIRContext.
1467     SmallVector<APInt> intOutputValues;
1468     SmallVector<APFloat> fpOutputValues;
1469     if (elementType.template isa<FloatType>())
1470       fpOutputValues.resize(numElements, APFloat(0.f));
1471     else
1472       intOutputValues.resize(numElements);
1473 
1474     // Return the constant dim positions from the given permutation map.
1475     auto getDimPositions = [](AffineMap map) {
1476       SmallVector<unsigned> dims;
1477       dims.reserve(map.getNumResults());
1478       for (AffineExpr result : map.getResults()) {
1479         dims.push_back(result.cast<AffineDimExpr>().getPosition());
1480       }
1481       return dims;
1482     };
1483 
1484     SmallVector<SmallVector<unsigned>> inputDims;
1485     for (int i = 0; i < numInputs; ++i)
1486       inputDims.push_back(getDimPositions(genericOp.getIndexingMaps()[i]));
1487     auto outputDims = getDimPositions(genericOp.getIndexingMaps().back());
1488     auto outputShape = outputType.getShape();
1489 
1490     // Allocate small vectors for index delinearization. Initial values do not
1491     // matter here as they will be overwritten later.
1492     SmallVector<uint64_t> indices(loopBounds.size(), 0);
1493     SmallVector<uint64_t> dstIndices(loopBounds.size(), 0);
1494     SmallVector<SmallVector<uint64_t>> srcIndices(
1495         numInputs, SmallVector<uint64_t>(loopBounds.size(), 0));
1496     SmallVector<uint64_t> srcLinearIndices(numInputs, 0);
1497     uint64_t dstLinearIndex = 0;
1498 
1499     // Allocate spaces for compute function inputs. Initial values do not matter
1500     // here as they will be overwritten later.
1501     APIntOrFloatArray computeFnInputs;
1502 
1503     auto inputShapes = llvm::to_vector<4>(
1504         llvm::map_range(genericOp.getInputOperands(), [](OpOperand *operand) {
1505           return operand->get().getType().cast<ShapedType>().getShape();
1506         }));
1507 
1508     // Given a `linearIndex`, remap it to a linear index to access linalg op
1509     // inputs/ouputs. This mutates `indices`, `srcIndices`, `dstIndices`,
1510     // `srcLinearIndices`, `dstLinearIndex` in place.
1511     auto computeRemappedLinearIndex = [&](int linearIndex) {
1512       int totalCount = linearIndex;
1513       for (int dim = loopBounds.size() - 1; dim >= 0; --dim) {
1514         indices[dim] = totalCount % loopBounds[dim];
1515         totalCount /= loopBounds[dim];
1516       }
1517 
1518       for (int dim = loopBounds.size() - 1; dim >= 0; --dim) {
1519         for (int i = 0; i < numInputs; ++i)
1520           srcIndices[i][dim] = indices[inputDims[i][dim]];
1521         dstIndices[dim] = indices[outputDims[dim]];
1522       }
1523 
1524       dstLinearIndex = dstIndices.front();
1525       for (int i = 0; i < numInputs; ++i)
1526         srcLinearIndices[i] = srcIndices[i].front();
1527 
1528       for (int dim = 1; dim < outputType.getRank(); ++dim) {
1529         dstLinearIndex = dstLinearIndex * outputShape[dim] + dstIndices[dim];
1530         for (int i = 0; i < numInputs; ++i)
1531           srcLinearIndices[i] =
1532               srcLinearIndices[i] * inputShapes[i][dim] + srcIndices[i][dim];
1533       }
1534     };
1535 
1536     bool isFloat = elementType.isa<FloatType>();
1537     if (isFloat) {
1538       SmallVector<DenseElementsAttr::iterator_range<APFloat>> inFpRanges;
1539       for (int i = 0; i < numInputs; ++i)
1540         inFpRanges.push_back(inputValues[i].getValues<APFloat>());
1541 
1542       computeFnInputs.apFloats.resize(numInputs, APFloat(0.f));
1543 
1544       // Transpose the input constant. Because we don't know its rank in
1545       // advance, we need to loop over the range [0, element count) and
1546       // delinearize the index.
1547       for (int linearIndex = 0; linearIndex < numElements; ++linearIndex) {
1548         computeRemappedLinearIndex(linearIndex);
1549 
1550         // Collect constant elements for all inputs at this loop iteration.
1551         for (int i = 0; i < numInputs; ++i)
1552           computeFnInputs.apFloats[i] = inFpRanges[i][srcLinearIndices[i]];
1553 
1554         // Invoke the computation to get the corresponding constant output
1555         // element.
1556         fpOutputValues[dstLinearIndex] = *computeFn(computeFnInputs).apFloat;
1557       }
1558     } else {
1559       SmallVector<DenseElementsAttr::iterator_range<APInt>> inIntRanges;
1560       for (int i = 0; i < numInputs; ++i)
1561         inIntRanges.push_back(inputValues[i].getValues<APInt>());
1562 
1563       computeFnInputs.apInts.resize(numInputs);
1564 
1565       // Transpose the input constant. Because we don't know its rank in
1566       // advance, we need to loop over the range [0, element count) and
1567       // delinearize the index.
1568       for (int linearIndex = 0; linearIndex < numElements; ++linearIndex) {
1569         computeRemappedLinearIndex(linearIndex);
1570 
1571         // Collect constant elements for all inputs at this loop iteration.
1572         for (int i = 0; i < numInputs; ++i)
1573           computeFnInputs.apInts[i] = inIntRanges[i][srcLinearIndices[i]];
1574 
1575         // Invoke the computation to get the corresponding constant output
1576         // element.
1577         intOutputValues[dstLinearIndex] = *computeFn(computeFnInputs).apInt;
1578       }
1579     }
1580 
1581     DenseElementsAttr outputAttr =
1582         isFloat ? DenseElementsAttr::get(outputType, fpOutputValues)
1583                 : DenseElementsAttr::get(outputType, intOutputValues);
1584 
1585     rewriter.replaceOpWithNewOp<ConstantOp>(genericOp, outputAttr);
1586     return success();
1587   }
1588 
1589 private:
1590   ControlElementwiseOpsFusionFn controlFn;
1591 };
1592 
1593 // Folds linalg.generic ops that are actually transposes on constant values.
1594 struct FoldConstantTranspose : public FoldConstantBase<FoldConstantTranspose> {
1595   using FoldConstantBase::FoldConstantBase;
1596 
1597   bool matchIndexingMaps(GenericOp genericOp) const {
1598     // We should have one input and one output.
1599     return genericOp.getIndexingMaps().size() == 2;
1600   }
1601 
1602   RegionComputationFn getRegionComputeFn(GenericOp genericOp) const {
1603     // Make sure the region only contains a yield op.
1604     Block &body = genericOp.region().front();
1605     if (!llvm::hasSingleElement(body))
1606       return nullptr;
1607     auto yieldOp = dyn_cast<linalg::YieldOp>(body.getTerminator());
1608     if (!yieldOp)
1609       return nullptr;
1610 
1611     // The yield op should return the block argument corresponds to the input.
1612     for (Value yieldVal : yieldOp.values()) {
1613       auto yieldArg = yieldVal.dyn_cast<BlockArgument>();
1614       if (!yieldArg || yieldArg.getOwner() != &body)
1615         return nullptr;
1616       if (yieldArg.getArgNumber() != 0)
1617         return nullptr;
1618     }
1619 
1620     // No computation; just return the orginal value.
1621     return [](const APIntOrFloatArray &inputs) {
1622       if (inputs.apFloats.empty())
1623         return APIntOrFloat{inputs.apInts.front(), llvm::None};
1624       return APIntOrFloat{llvm::None, inputs.apFloats.front()};
1625     };
1626   }
1627 
1628   ControlElementwiseOpsFusionFn controlFn;
1629 };
1630 
1631 } // namespace
1632 
1633 static Optional<SmallVector<Value>>
1634 fuseElementwiseOps(PatternRewriter &rewriter, OpOperand *consumerOpOperand,
1635                    GenericOp producer,
1636                    const ControlElementwiseOpsFusionFn &controlFn) {
1637   if (producer->getNumResults() != 1)
1638     return llvm::None;
1639 
1640   return fuseElementwiseOpsImpl(producer, consumerOpOperand, controlFn,
1641                                 rewriter);
1642 }
1643 
1644 bool mlir::linalg::skipUnitDimReshape(const OpResult &producer,
1645                                       OpOperand &consumer) {
1646   if (auto producerCollapseOp =
1647           dyn_cast<tensor::CollapseShapeOp>(producer.getOwner())) {
1648     return !isUnitDimExpansionOnly(producerCollapseOp);
1649   }
1650   if (auto consumerExpandOp =
1651           dyn_cast<tensor::ExpandShapeOp>(consumer.getOwner())) {
1652     return !isUnitDimExpansionOnly(consumerExpandOp);
1653   }
1654   return true;
1655 }
1656 
1657 namespace {
1658 /// Patterns to fuse a generic op, with the producer of its operands.
1659 class FuseElementwiseOps : public OpRewritePattern<GenericOp> {
1660 public:
1661   FuseElementwiseOps(MLIRContext *context, ControlElementwiseOpsFusionFn &fun,
1662                      PatternBenefit benefit = 1)
1663       : OpRewritePattern<GenericOp>(context, benefit), controlFn(fun) {}
1664 
1665   LogicalResult matchAndRewrite(GenericOp genericOp,
1666                                 PatternRewriter &rewriter) const override {
1667     // Find the first operand that is defined by another generic op on tensors.
1668     for (OpOperand *opOperand : genericOp.getInputAndOutputOperands()) {
1669       auto producer =
1670           dyn_cast_or_null<GenericOp>(opOperand->get().getDefiningOp());
1671       if (!producer || !producer.hasTensorSemantics())
1672         continue;
1673       Optional<SmallVector<Value>> fusedOpResults =
1674           fuseElementwiseOps(rewriter, opOperand, producer, controlFn);
1675       if (fusedOpResults) {
1676         rewriter.replaceOp(genericOp, *fusedOpResults);
1677         return success();
1678       }
1679     }
1680     return failure();
1681   }
1682 
1683 private:
1684   ControlElementwiseOpsFusionFn controlFn;
1685 };
1686 
1687 /// Pass that fuses generic ops on tensors. Used only for testing.
1688 struct LinalgElementwiseOpFusionPass
1689     : public LinalgElementwiseOpFusionBase<LinalgElementwiseOpFusionPass> {
1690   void runOnOperation() override {
1691     Operation *op = getOperation();
1692     RewritePatternSet patterns(op->getContext());
1693     ControlElementwiseOpsFusionFn allowFoldingFn =
1694         [](const OpResult &producer, const OpOperand &consumer) {
1695           return true;
1696         };
1697     populateElementwiseOpsFusionPatterns(
1698         patterns,
1699         LinalgElementwiseFusionOptions().setControlFoldingReshapes(
1700             allowFoldingUnitDimReshapes ? allowFoldingFn : skipUnitDimReshape));
1701 
1702     // Use TopDownTraversal for compile time reasons
1703     GreedyRewriteConfig grc;
1704     grc.useTopDownTraversal = true;
1705     (void)applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns),
1706                                        grc);
1707   }
1708 };
1709 
1710 /// Pass to test folding of reshape ops with generic ops by linearization.
1711 struct FoldReshapeOpsByLinearizationPass
1712     : public LinalgFoldReshapeOpsByLinearizationBase<
1713           FoldReshapeOpsByLinearizationPass> {
1714   void runOnOperation() override {
1715     Operation *op = getOperation();
1716     RewritePatternSet patterns(op->getContext());
1717     populateFoldReshapeOpsByLinearizationPatterns(patterns);
1718     if (allowFoldingUnitDimReshapes) {
1719       populateFoldUnitDimsReshapeOpsByLinearizationPatterns(patterns);
1720     }
1721     (void)applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns));
1722   }
1723 };
1724 
1725 /// Forces `outs` operands of linalg operations to use `linalg.init_tensor` if
1726 /// the value of the `outs` operand is not used within the op.  This is only
1727 /// implemented for `linalg.generic` operations for now, but should hold for all
1728 /// linalg structured ops.
1729 struct RemoveOutsDependency : public OpRewritePattern<GenericOp> {
1730   using OpRewritePattern<GenericOp>::OpRewritePattern;
1731 
1732   LogicalResult matchAndRewrite(GenericOp op,
1733                                 PatternRewriter &rewriter) const override {
1734     rewriter.startRootUpdate(op);
1735     bool modifiedOutput = false;
1736     Location loc = op.getLoc();
1737     for (OpOperand *opOperand : op.getOutputOperands()) {
1738       if (!op.payloadUsesValueFromOperand(opOperand)) {
1739         Value operandVal = opOperand->get();
1740         auto operandType = operandVal.getType().dyn_cast<RankedTensorType>();
1741         if (!operandType)
1742           continue;
1743 
1744         // If outs is already an `init_tensor` operation, nothing to do.
1745         auto definingOp = operandVal.getDefiningOp<InitTensorOp>();
1746         if (definingOp)
1747           continue;
1748         modifiedOutput = true;
1749         SmallVector<Value> dynamicDims;
1750         for (const auto &dim : llvm::enumerate(operandType.getShape())) {
1751           if (dim.value() != ShapedType::kDynamicSize)
1752             continue;
1753           dynamicDims.push_back(rewriter.createOrFold<tensor::DimOp>(
1754               loc, operandVal, dim.index()));
1755         }
1756         Value initTensor = rewriter.create<InitTensorOp>(
1757             loc, dynamicDims, operandType.getShape(),
1758             operandType.getElementType());
1759         op->setOperand(opOperand->getOperandNumber(), initTensor);
1760       }
1761     }
1762     if (!modifiedOutput) {
1763       rewriter.cancelRootUpdate(op);
1764       return failure();
1765     }
1766     rewriter.finalizeRootUpdate(op);
1767     return success();
1768   }
1769 };
1770 
1771 } // namespace
1772 
1773 void mlir::linalg::populateFoldReshapeOpsByLinearizationPatterns(
1774     RewritePatternSet &patterns) {
1775   patterns
1776       .add<FoldProducerReshapeOpByLinearization<false, tensor::CollapseShapeOp>,
1777            FoldProducerReshapeOpByLinearization<false, tensor::ExpandShapeOp>,
1778            FoldConsumerReshapeOpByLinearization<false, tensor::CollapseShapeOp>,
1779            FoldConsumerReshapeOpByLinearization<false, tensor::ExpandShapeOp>>(
1780           patterns.getContext());
1781 }
1782 
1783 void mlir::linalg::populateFoldUnitDimsReshapeOpsByLinearizationPatterns(
1784     RewritePatternSet &patterns) {
1785   patterns
1786       .add<FoldProducerReshapeOpByLinearization<true, tensor::CollapseShapeOp>,
1787            FoldProducerReshapeOpByLinearization<true, tensor::ExpandShapeOp>,
1788            FoldConsumerReshapeOpByLinearization<true, tensor::CollapseShapeOp>,
1789            FoldConsumerReshapeOpByLinearization<true, tensor::ExpandShapeOp>>(
1790           patterns.getContext());
1791 }
1792 
1793 void mlir::linalg::populateFoldReshapeOpsByExpansionPatterns(
1794     RewritePatternSet &patterns,
1795     const ControlElementwiseOpsFusionFn &controlFoldingReshapes) {
1796   patterns.add<FoldReshapeWithGenericOpByExpansion>(patterns.getContext(),
1797                                                     controlFoldingReshapes);
1798   patterns.add<FoldWithProducerReshapeOpByExpansion>(patterns.getContext(),
1799                                                      controlFoldingReshapes);
1800 }
1801 
1802 void mlir::linalg::populateElementwiseOpsFusionPatterns(
1803     RewritePatternSet &patterns, LinalgElementwiseFusionOptions options) {
1804   auto *context = patterns.getContext();
1805   patterns.add<FuseElementwiseOps, FoldScalarOrSplatConstant,
1806                FoldConstantTranspose>(context,
1807                                       options.controlElementwiseOpsFusionFn);
1808   patterns.add<RemoveOutsDependency>(context);
1809   populateFoldReshapeOpsByExpansionPatterns(patterns,
1810                                             options.controlFoldingReshapesFn);
1811   AffineApplyOp::getCanonicalizationPatterns(patterns, context);
1812   GenericOp::getCanonicalizationPatterns(patterns, context);
1813   tensor::ExpandShapeOp::getCanonicalizationPatterns(patterns, context);
1814   tensor::CollapseShapeOp::getCanonicalizationPatterns(patterns, context);
1815   context->getLoadedDialect<LinalgDialect>()->getCanonicalizationPatterns(
1816       patterns);
1817 }
1818 
1819 void mlir::linalg::populatePushReshapeOpsPatterns(RewritePatternSet &patterns) {
1820   auto *context = patterns.getContext();
1821   patterns.add<PushExpandingReshape>(context);
1822 }
1823 
1824 std::unique_ptr<Pass> mlir::createLinalgElementwiseOpFusionPass() {
1825   return std::make_unique<LinalgElementwiseOpFusionPass>();
1826 }
1827 
1828 std::unique_ptr<Pass> mlir::createFoldReshapeOpsByLinearizationPass() {
1829   return std::make_unique<FoldReshapeOpsByLinearizationPass>();
1830 }
1831