1 //===- DropUnitDims.cpp - Pass to drop use of unit-extent for broadcasting ===//
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 patterns/pass to remove usage of unit-extent dimensions
10 // to specify broadcasting in favor of more canonical representation of the
11 // computation
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "PassDetail.h"
16 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
17 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
18 #include "mlir/Dialect/Linalg/Passes.h"
19 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
20 #include "mlir/Dialect/Linalg/Utils/Utils.h"
21 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
22 #include "mlir/IR/AffineExpr.h"
23 #include "mlir/IR/AffineMap.h"
24 #include "mlir/Transforms/FoldUtils.h"
25 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 
29 #define DEBUG_TYPE "linalg-drop-unit-dims"
30 
31 using namespace mlir;
32 using namespace mlir::edsc;
33 using namespace mlir::edsc::intrinsics;
34 using namespace mlir::linalg;
35 
36 /// Implements a pass that canonicalizes the uses of unit-extent dimensions for
37 /// broadcasting. For example,
38 ///
39 /// ```mlir
40 /// #accesses = [
41 ///   affine_map<(d0, d1) -> (0, d1)>,
42 ///   affine_map<(d0, d1) -> (d0, 0)>,
43 ///   affine_map<(d0, d1) -> (d0, d1)>
44 /// ]
45 ///
46 /// #trait = {
47 ///   args_in = 2,
48 ///   args_out = 1,
49 ///   indexing_maps = #accesses,
50 ///   iterator_types = ["parallel", "parallel"],
51 ///   library_call = "some_external_fn"
52 /// }
53 ///
54 /// func @broadcast_test(%arg0 : tensor<5xf32>, %arg1 : tensor<5xf32>) ->
55 /// tensor<5x5xf32>
56 /// {
57 ///   %0 = linalg.tensor_reshape %arg0 [affine_map<(d0, d1) -> (d0, d1)>] :
58 ///        tensor<5xf32> into tensor<1x5xf32>
59 ///   %1 = linalg.tensor_reshape %arg1 [affine_map<(d0, d1) -> (d0, d1)>] :
60 ///        tensor<5xf32> into tensor<5x1xf32>
61 ///   %2 = linalg.generic #trait %0, %1 {
62 ///        ^bb0(%arg2: f32, %arg3: f32):
63 ///          %3 = addf %arg2, %arg3 : f32
64 ///          linalg.yield %3 : f32
65 ///        } : tensor<1x5xf32>, tensor<5x1xf32> -> tensor<5x5xf32>
66 ///   return %2 : tensor<5x5xf32>
67 /// }
68 ///
69 /// would canonicalize to
70 ///
71 /// ```mlir
72 /// #accesses = [
73 ///   affine_map<(d0, d1) -> (d1)>,
74 ///   affine_map<(d0, d1) -> (d0)>,
75 ///   affine_map<(d0, d1) -> (d0, d1)>
76 /// ]
77 ///
78 /// #trait = {
79 ///   args_in = 2,
80 ///   args_out = 1,
81 ///   indexing_maps = #accesses,
82 ///   iterator_types = ["parallel", "parallel"],
83 ///   library_call = "some_external_fn"
84 /// }
85 ///
86 /// func @broadcast_test(%arg0 : tensor<5xf32>, %arg1 : tensor<5xf32>) ->
87 /// tensor<5x5xf32>
88 /// {
89 ///   %0 = linalg.generic #trait %arg0, %arg1 {
90 ///        ^bb0(%arg2: f32, %arg3: f32):
91 ///          %3 = addf %arg2, %arg3 : f32
92 ///          linalg.yield %3 : f32
93 ///        } : tensor<5xf32>, tensor<5xf32> -> tensor<5x5xf32>
94 ///   return %0 : tensor<5x5xf32>
95 /// }
96 
97 /// Given dims of the iteration space of a structured op that are known to be
98 /// single trip count (`unitDims`), return the indexing maps to use in the
99 /// canonicalized op with these dims removed, given the original `indexingMaps`.
100 static ArrayAttr replaceUnitDims(DenseSet<unsigned> &unitDims,
101                                  ArrayRef<AffineMap> indexingMaps,
102                                  MLIRContext *context) {
103   if (indexingMaps.empty())
104     return nullptr;
105   unsigned numIterationDims = indexingMaps.front().getNumDims();
106   unsigned numSymbols = indexingMaps.front().getNumSymbols();
107 
108   // Compute the replacement for each dim expr.
109   SmallVector<AffineExpr, 4> dimReplacements;
110   dimReplacements.reserve(numIterationDims);
111   unsigned numKeptDims = 0;
112   for (unsigned dim : llvm::seq<unsigned>(0, numIterationDims)) {
113     if (unitDims.count(dim))
114       dimReplacements.push_back(getAffineConstantExpr(0, context));
115     else
116       dimReplacements.push_back(getAffineDimExpr(numKeptDims++, context));
117   }
118 
119   // Symbols remain the same.
120   SmallVector<AffineExpr, 4> symReplacements;
121   symReplacements.reserve(numSymbols);
122   for (unsigned symbol : llvm::seq<unsigned>(0, numSymbols))
123     symReplacements.push_back(getAffineSymbolExpr(symbol, context));
124 
125   SmallVector<AffineMap, 4> newIndexingMaps;
126   newIndexingMaps.reserve(indexingMaps.size());
127   for (AffineMap operandMap : indexingMaps) {
128     // Expected indexing maps to have no symbols.
129     if (operandMap.getNumSymbols())
130       return nullptr;
131     newIndexingMaps.push_back(simplifyAffineMap(
132         operandMap.replaceDimsAndSymbols(dimReplacements, symReplacements,
133                                          numIterationDims - unitDims.size(),
134                                          numSymbols)));
135   }
136 
137   // Check that the new index maps are invertible. If not, something went
138   // wrong, so abort.
139   if (!inversePermutation(concatAffineMaps(newIndexingMaps)))
140     return nullptr;
141   return ArrayAttr::get(context,
142                         llvm::to_vector<4>(llvm::map_range(
143                             newIndexingMaps, [](AffineMap map) -> Attribute {
144                               return AffineMapAttr::get(map);
145                             })));
146 }
147 
148 /// Update the index accesses of linalg operations having index semantics.
149 template <typename GenericOpTy>
150 static void replaceUnitDimIndexOps(GenericOpTy op,
151                                    const DenseSet<unsigned> &unitDims,
152                                    PatternRewriter &rewriter) {
153   assert(op->getNumRegions() == 1 && op->getRegion(0).getBlocks().size() == 1 &&
154          "expected generic operation to have one block.");
155   Block &block = op->getRegion(0).front();
156 
157   for (IndexOp indexOp : llvm::make_early_inc_range(block.getOps<IndexOp>())) {
158     OpBuilder::InsertionGuard guard(rewriter);
159     rewriter.setInsertionPoint(indexOp);
160     if (unitDims.count(indexOp.dim()) != 0) {
161       rewriter.replaceOpWithNewOp<ConstantIndexOp>(indexOp, 0);
162     } else {
163       // Update the dimension of the index operation if needed.
164       unsigned droppedDims = llvm::count_if(
165           unitDims, [&](unsigned dim) { return dim < indexOp.dim(); });
166       if (droppedDims != 0)
167         rewriter.replaceOpWithNewOp<IndexOp>(indexOp,
168                                              indexOp.dim() - droppedDims);
169     }
170   }
171 }
172 
173 /// Modify the region of indexed generic op to drop arguments corresponding to
174 /// loops that are unit trip count.
175 template <typename OpTy>
176 static LogicalResult
177 replaceBlockArgForUnitDimLoops(OpTy op, const DenseSet<unsigned> &unitDims,
178                                PatternRewriter &rewriterp) {
179   return success();
180 }
181 
182 template <>
183 LogicalResult replaceBlockArgForUnitDimLoops<IndexedGenericOp>(
184     IndexedGenericOp op, const DenseSet<unsigned> &unitDims,
185     PatternRewriter &rewriter) {
186   OpBuilder::InsertionGuard guard(rewriter);
187   Block *entryBlock = &op->getRegion(0).front();
188   rewriter.setInsertionPointToStart(entryBlock);
189   Value zero = rewriter.create<ConstantIndexOp>(op.getLoc(), 0);
190   for (unsigned unitDimLoop : unitDims) {
191     entryBlock->getArgument(unitDimLoop).replaceAllUsesWith(zero);
192   }
193   SmallVector<unsigned, 8> unitDimsToErase(unitDims.begin(), unitDims.end());
194   entryBlock->eraseArguments(unitDimsToErase);
195   return success();
196 }
197 
198 namespace {
199 /// Pattern to fold unit-trip count loops in GenericOps.
200 template <typename GenericOpTy>
201 struct FoldUnitDimLoops : public OpRewritePattern<GenericOpTy> {
202   using OpRewritePattern<GenericOpTy>::OpRewritePattern;
203   LogicalResult matchAndRewrite(GenericOpTy op,
204                                 PatternRewriter &rewriter) const override {
205     SmallVector<AffineMap, 4> indexingMaps = op.getIndexingMaps();
206     if (indexingMaps.empty())
207       return failure();
208 
209     // Check if any of the iteration dimensions are unit-trip count. They will
210     // end up being unit-trip count if they are used to index into a unit-dim
211     // tensor/memref.
212     AffineMap invertedMap = inversePermutation(concatAffineMaps(indexingMaps));
213     if (!invertedMap)
214       return failure();
215     SmallVector<int64_t, 4> dims;
216     for (ShapedType shapedType : op.getShapedOperandTypes())
217       dims.append(shapedType.getShape().begin(), shapedType.getShape().end());
218 
219     // Find all the reduction iterators. Those need some special consideration
220     // (see below).
221     auto getLoopDimsOfType =
222         [&](StringRef iteratorTypeName) -> SmallVector<unsigned, 4> {
223       SmallVector<AffineExpr> dimExprs;
224       getDimsOfType(op, iteratorTypeName, dimExprs);
225       return llvm::to_vector<4>(llvm::map_range(dimExprs, [](AffineExpr expr) {
226         return expr.cast<AffineDimExpr>().getPosition();
227       }));
228     };
229     auto reductionDims = getLoopDimsOfType(getReductionIteratorTypeName());
230 
231     DenseSet<unsigned> unitDims;
232     SmallVector<unsigned, 4> unitDimsReductionLoops;
233     ArrayAttr iteratorTypes = op.iterator_types();
234     for (auto expr : enumerate(invertedMap.getResults())) {
235       if (AffineDimExpr dimExpr = expr.value().dyn_cast<AffineDimExpr>())
236         if (dims[dimExpr.getPosition()] == 1) {
237           if (isParallelIterator(iteratorTypes[expr.index()]))
238             unitDims.insert(expr.index());
239           else if (isReductionIterator(iteratorTypes[expr.index()]))
240             unitDimsReductionLoops.push_back(expr.index());
241         }
242     }
243 
244     // Reduction loops can be dropped if there is at least one other reduction
245     // loop that is not dropped. This accounts for the initial value read in the
246     // reduction loop.
247     if (!unitDimsReductionLoops.empty() && reductionDims.size() > 1) {
248       if (unitDimsReductionLoops.size() == reductionDims.size())
249         unitDims.insert(reductionDims.begin(), std::prev(reductionDims.end()));
250       else
251         unitDims.insert(unitDimsReductionLoops.begin(),
252                         unitDimsReductionLoops.end());
253     }
254 
255     if (unitDims.empty())
256       return failure();
257 
258     // Compute the modified indexing maps.
259     MLIRContext *context = rewriter.getContext();
260     ArrayAttr newIndexingMapAttr =
261         replaceUnitDims(unitDims, indexingMaps, context);
262     if (!newIndexingMapAttr)
263       return op.emitError("unable to compute modified indexing_maps");
264 
265     // Compute the iterator types of the modified op by dropping the one-trip
266     // count loops.
267     SmallVector<Attribute, 4> newIteratorTypes;
268     for (auto attr : llvm::enumerate(iteratorTypes)) {
269       if (!unitDims.count(attr.index()))
270         newIteratorTypes.push_back(attr.value());
271     }
272 
273     rewriter.startRootUpdate(op);
274     op.indexing_mapsAttr(newIndexingMapAttr);
275     op.iterator_typesAttr(ArrayAttr::get(context, newIteratorTypes));
276     (void)replaceBlockArgForUnitDimLoops(op, unitDims, rewriter);
277     replaceUnitDimIndexOps(op, unitDims, rewriter);
278     rewriter.finalizeRootUpdate(op);
279     return success();
280   }
281 };
282 
283 struct UnitExtentReplacementInfo {
284   RankedTensorType type;
285   AffineMap indexMap;
286   ArrayAttr reassociation;
287 };
288 } // namespace
289 
290 /// Utility function for replacing operands/results to a linalg generic
291 /// operation on tensors with unit-extent dimensions. These can be replaced with
292 /// an operand/result with the unit-extent dimension removed. This is only done
293 /// if the indexing map used to access that didimensionmension has a
294 /// AffineConstantExpr of value 0. Given the `type` of an result/operand of a
295 /// Linalg op, and its `indexMap` the utility function returns:
296 /// - the new type with dimensions of size 1 removed.
297 /// - modified index map that can be used to access the replaced result/operand
298 /// - the reassociation that converts from the original tensor type to the
299 ///   modified tensor type.
300 static UnitExtentReplacementInfo replaceUnitExtents(AffineMap indexMap,
301                                                     RankedTensorType type,
302                                                     MLIRContext *context) {
303   ArrayRef<int64_t> shape = type.getShape();
304   ArrayRef<AffineExpr> exprs = indexMap.getResults();
305   SmallVector<AffineExpr, 2> reassociations;
306   SmallVector<Attribute, 4> reassociationMaps;
307   SmallVector<AffineExpr, 4> newIndexExprs;
308   SmallVector<int64_t, 4> newShape;
309 
310   int64_t origRank = type.getRank();
311   AffineExpr zeroExpr = getAffineConstantExpr(0, context);
312   auto isUnitExtent = [&](int64_t dim) -> bool {
313     return shape[dim] == 1 && exprs[dim] == zeroExpr;
314   };
315 
316   unsigned dim = 0;
317   // Fold dimensions that are unit-extent at the beginning of the tensor.
318   while (dim < origRank && isUnitExtent(dim))
319     reassociations.push_back(getAffineDimExpr(dim++, context));
320   while (dim < origRank) {
321     reassociations.push_back(getAffineDimExpr(dim, context));
322     newIndexExprs.push_back(exprs[dim]);
323     newShape.push_back(shape[dim]);
324     // Fold all following dimensions that are unit-extent.
325     while (dim + 1 < origRank && isUnitExtent(dim + 1)) {
326       ++dim;
327       reassociations.push_back(getAffineDimExpr(dim, context));
328     }
329     reassociationMaps.push_back(AffineMapAttr::get(AffineMap::get(
330         origRank, /*numSymbols = */ 0, reassociations, context)));
331     reassociations.clear();
332     ++dim;
333   }
334   UnitExtentReplacementInfo info = {
335       RankedTensorType::get(newShape, type.getElementType()),
336       AffineMap::get(indexMap.getNumDims(), indexMap.getNumSymbols(),
337                      newIndexExprs, context),
338       ArrayAttr::get(context, reassociationMaps)};
339   return info;
340 }
341 
342 namespace {
343 
344 /// Pattern to replace tensors operands/results that are unit extents.
345 template <typename GenericOpTy>
346 struct ReplaceUnitExtentTensors : public OpRewritePattern<GenericOpTy> {
347   using OpRewritePattern<GenericOpTy>::OpRewritePattern;
348   LogicalResult matchAndRewrite(GenericOpTy op,
349                                 PatternRewriter &rewriter) const override {
350     if (!op.hasTensorSemantics())
351       return failure();
352 
353     MLIRContext *context = rewriter.getContext();
354     Location loc = op.getLoc();
355 
356     SmallVector<AffineMap, 4> newIndexingMaps;
357     SmallVector<ArrayAttr, 4> reassociationMaps;
358     SmallVector<ShapedType, 4> newInputOutputTypes;
359     bool doCanonicalization = false;
360     for (auto it :
361          llvm::zip(op.getIndexingMaps(), op.getShapedOperandTypes())) {
362       auto replacementInfo = replaceUnitExtents(
363           std::get<0>(it), std::get<1>(it).template cast<RankedTensorType>(),
364           context);
365       reassociationMaps.push_back(replacementInfo.reassociation);
366       newIndexingMaps.push_back(replacementInfo.indexMap);
367       newInputOutputTypes.push_back(replacementInfo.type);
368       doCanonicalization |= replacementInfo.type != std::get<1>(it);
369     }
370 
371     // If the indexing maps of the result operation are not invertible (i.e. not
372     // legal), abort.
373     if (!doCanonicalization ||
374         !inversePermutation(concatAffineMaps(newIndexingMaps)))
375       return failure();
376 
377     // If any operand type change, insert a reshape to convert from the original
378     // type to the new type.
379     // TODO: get rid of flattenedIdx which assumes operand order and contiguity.
380     unsigned flattenedIdx = 0;
381     auto insertReshapes = [&](ValueRange values) {
382       SmallVector<Value, 4> res;
383       res.reserve(values.size());
384       for (auto operand : llvm::enumerate(values)) {
385         if (operand.value().getType() == newInputOutputTypes[flattenedIdx])
386           res.push_back(operand.value());
387         else
388           res.push_back(rewriter.create<linalg::TensorReshapeOp>(
389               loc, newInputOutputTypes[flattenedIdx], operand.value(),
390               reassociationMaps[flattenedIdx]));
391         ++flattenedIdx;
392       }
393       return res;
394     };
395 
396     SmallVector<Value, 4> newInputs = insertReshapes(op.inputs());
397     SmallVector<Value, 4> newOutputs = insertReshapes(op.outputs());
398 
399     // If any result type changes, insert a reshape to convert from the original
400     // type to the new type.
401     SmallVector<Type, 4> resultTypes;
402     resultTypes.reserve(op.getNumResults());
403     for (unsigned i : llvm::seq<unsigned>(0, op.getNumResults()))
404       resultTypes.push_back(newInputOutputTypes[i + op.getNumInputs()]);
405     GenericOpTy replacementOp = rewriter.create<GenericOpTy>(
406         loc, resultTypes, newInputs, newOutputs, newIndexingMaps,
407         llvm::to_vector<4>(
408             op.iterator_types().template getAsValueRange<StringAttr>()));
409     rewriter.inlineRegionBefore(op.region(), replacementOp.region(),
410                                 replacementOp.region().begin());
411 
412     // If any result tensor has a modified shape, then add reshape to recover
413     // the original shape.
414     SmallVector<Value, 4> resultReplacements;
415     for (auto result : llvm::enumerate(replacementOp.getResults())) {
416       unsigned index = result.index() + replacementOp.getNumInputs();
417       RankedTensorType origResultType = op.getResult(result.index())
418                                             .getType()
419                                             .template cast<RankedTensorType>();
420       if (origResultType != result.value().getType())
421         resultReplacements.push_back(rewriter.create<linalg::TensorReshapeOp>(
422             loc, origResultType, result.value(), reassociationMaps[index]));
423       else
424         resultReplacements.push_back(result.value());
425     }
426     rewriter.replaceOp(op, resultReplacements);
427     return success();
428   }
429 };
430 
431 /// Pattern to fold pair of reshape ops where the intermediate has unit-dims for
432 /// example:
433 ///
434 ///  %0 = linalg.tensor_reshape %arg0
435 ///    [affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>]
436 ///    : tensor<2048xf32> into tensor<1x4x1x512xf32>
437 ///  %1 = linalg.tensor_reshape %0
438 ///    [affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>,
439 ///     affine_map<(d0, d1, d2, d3) -> (d3)>]
440 ///    : tensor<1x4x1x512xf32> into tensor<4x512xf32>
441 ///
442 /// can be replaced with
443 ///
444 ///  %0 = linalg.tensor_reshape %arg0 [affine_map<(d0, d1) -> (d0, d1)>]
445 ///    : tensor<2048xf32> into tensor<4x512xf32>
446 ///
447 /// Similarly,
448 ///
449 ///  %0 = linalg.tensor_reshape %arg0
450 ///    [affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>,
451 ///     affine_map<(d0, d1, d2, d3) -> (d3)>]
452 ///    : tensor<4x512xf32> into tensor<1x4x1x512xf32>
453 ///  %1 = linalg.tensor_reshape %0
454 ///   [affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>]
455 ///    : tensor<1x4x1x512xf32> into tensor<2048xf32>
456 ///
457 /// can be replaced with
458 ///
459 ///  %0 = linalg.tensor_reshape %arg0 [affine_map<(d0, d1) -> (d0, d1)>]
460 ///    : tensor<4x512xf32> into tensor<2048xf32>
461 struct FoldReshapeOpWithUnitExtent : OpRewritePattern<TensorReshapeOp> {
462   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
463 
464   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
465                                 PatternRewriter &rewriter) const override {
466     // Check that the source operand is created from a reshape as well.
467     TensorReshapeOp parentReshapeOp =
468         reshapeOp.src().getDefiningOp<TensorReshapeOp>();
469     if (!parentReshapeOp)
470       return failure();
471 
472     RankedTensorType srcType = reshapeOp.getSrcType(),
473                      dstType = reshapeOp.getResultType(),
474                      parentSrcType = parentReshapeOp.getSrcType();
475     if (!srcType.hasStaticShape() || !dstType.hasStaticShape() ||
476         !parentSrcType.hasStaticShape() ||
477         srcType.getRank() < dstType.getRank() ||
478         parentSrcType.getRank() == dstType.getRank())
479       return failure();
480 
481     // Check if the result tensor_reshape is folding or expanding after folding
482     // the reshapeOp and parentReshapeOp are combined.  If the final
483     // tensor_reshape is folding, the parentReshapeOp is introducing unit-dims,
484     // and the reshapeOp does an actual reshape.  If the final tensor_reshape op
485     // is expanding, the reshapeOp is introducing unit-dims, and the
486     // parentReshapeOp does an actual reshape.
487     bool isFoldingPattern = parentSrcType.getRank() > dstType.getRank();
488     ArrayRef<int64_t> expandedShape =
489         isFoldingPattern ? parentSrcType.getShape() : dstType.getShape();
490     ArrayRef<int64_t> foldedShape =
491         isFoldingPattern ? dstType.getShape() : parentSrcType.getShape();
492 
493     unsigned expandedDim = 0, foldedDim = 0;
494     SmallVector<SmallVector<AffineExpr, 4>, 4> reassociationExprs(
495         foldedShape.size());
496     while (expandedDim < expandedShape.size() &&
497            foldedDim < foldedShape.size()) {
498       int64_t dstSize = foldedShape[foldedDim];
499       int64_t srcSize = expandedShape[expandedDim];
500       while (srcSize < dstSize && expandedDim < expandedShape.size()) {
501         reassociationExprs[foldedDim].push_back(
502             rewriter.getAffineDimExpr(expandedDim++));
503         srcSize *= expandedShape[expandedDim];
504       }
505       if (srcSize == dstSize) {
506         reassociationExprs[foldedDim].push_back(
507             rewriter.getAffineDimExpr(expandedDim++));
508         // If the next dim in foldedShape is not 1, treat subsequent dims in
509         // expandedShape which are 1 to be collapsed.
510         if (foldedDim == foldedShape.size() - 1 ||
511             foldedShape[foldedDim + 1] != 1) {
512           while (expandedDim < expandedShape.size() &&
513                  expandedShape[expandedDim] == 1) {
514             reassociationExprs[foldedDim].push_back(
515                 rewriter.getAffineDimExpr(expandedDim++));
516           }
517         }
518       } else {
519         return failure();
520       }
521 
522       foldedDim++;
523       // If inner most dims are folded there shouldn't be any leading 1 dims.
524       // otherwise these dims are not mapped and will lead into an illegal
525       // reshape.
526       if (expandedDim == expandedShape.size()) {
527         if (foldedDim < foldedShape.size() && foldedShape[foldedDim] == 1) {
528           return failure();
529         }
530       }
531     }
532     if (expandedDim != expandedShape.size())
533       return failure();
534 
535     SmallVector<AffineMap, 4> reassociationMaps =
536         llvm::to_vector<4>(llvm::map_range(
537             reassociationExprs, [&](ArrayRef<AffineExpr> exprs) -> AffineMap {
538               return AffineMap::get(expandedShape.size(), 0, exprs,
539                                     rewriter.getContext());
540             }));
541     rewriter.replaceOpWithNewOp<TensorReshapeOp>(
542         reshapeOp, dstType, parentReshapeOp.src(),
543         rewriter.getAffineMapArrayAttr(reassociationMaps));
544     return success();
545   }
546 };
547 
548 /// Pattern to fold subtensors that are just taking a slice of unit-dimension
549 /// tensor. For example
550 ///
551 /// %1 = subtensor %0[0, %o1, 0] [1, %s1, 1] [1, 1, 1]
552 ///     : tensor<1x?x1xf32> to tensor<1x?x1xf32>
553 ///
554 /// can be replaced with
555 ///
556 /// %0 = linalg.tensor_reshape %0 [affine_map<(d0, d1, d2) -> (d0, d1, d2)>]
557 ///     : tensor<1x?x1xf32> into tensor<?xf32>
558 /// %1 = subtensor %0[%o1] [%s1] [1] : tensor<?xf32> to tensor<?xf32>
559 /// %2 = linalg.tensor_reshape %1 [affine_map<(d0, d1, d2) -> (d0, d1, d2)>]
560 ///     : tensor<?xf32> into tensor<1x?x1xf32>
561 ///
562 /// The additional tensor_reshapes will hopefully get canonicalized away with
563 /// other reshapes that drop unit dimensions. Three condiitions to fold a
564 /// dimension
565 /// - The offset must be 0
566 /// - The size must be 1
567 /// - The dimension of the source type must be 1.
568 struct FoldUnitDimSubTensorOp : public OpRewritePattern<SubTensorOp> {
569   using OpRewritePattern<SubTensorOp>::OpRewritePattern;
570 
571   LogicalResult matchAndRewrite(SubTensorOp subTensorOp,
572                                 PatternRewriter &rewriter) const override {
573     SmallVector<OpFoldResult> mixedOffsets = subTensorOp.getMixedOffsets();
574     SmallVector<OpFoldResult> mixedSizes = subTensorOp.getMixedSizes();
575     SmallVector<OpFoldResult> mixedStrides = subTensorOp.getMixedStrides();
576     auto hasValue = [](OpFoldResult valueOrAttr, int64_t val) {
577       auto attr = valueOrAttr.dyn_cast<Attribute>();
578       return attr && attr.cast<IntegerAttr>().getInt() == val;
579     };
580 
581     if (llvm::any_of(mixedStrides, [&](OpFoldResult valueOrAttr) {
582           return !hasValue(valueOrAttr, 1);
583         }))
584       return failure();
585 
586     // Find the expanded unit dimensions.
587     SmallVector<ReassociationIndices> reassociation;
588     SmallVector<OpFoldResult> newOffsets, newSizes;
589     ArrayRef<int64_t> sourceShape = subTensorOp.getSourceType().getShape();
590     ReassociationIndices curr;
591     for (int64_t dim : llvm::seq<int64_t>(0, mixedOffsets.size())) {
592       curr.push_back(dim);
593       if (sourceShape[dim] == 1 && hasValue(mixedOffsets[dim], 0) &&
594           hasValue(mixedSizes[dim], 1)) {
595         continue;
596       }
597       newOffsets.push_back(mixedOffsets[dim]);
598       newSizes.push_back(mixedSizes[dim]);
599       reassociation.emplace_back(ReassociationIndices{});
600       std::swap(reassociation.back(), curr);
601     }
602     if (newOffsets.size() == mixedOffsets.size())
603       return failure();
604     reassociation.back().append(curr.begin(), curr.end());
605     SmallVector<OpFoldResult> newStrides(newOffsets.size(),
606                                          rewriter.getI64IntegerAttr(1));
607     Location loc = subTensorOp->getLoc();
608     auto srcReshape = rewriter.create<TensorReshapeOp>(
609         loc, subTensorOp.source(), reassociation);
610     auto newSubTensorOp = rewriter.create<SubTensorOp>(
611         loc, srcReshape, newOffsets, newSizes, newStrides);
612     rewriter.replaceOpWithNewOp<TensorReshapeOp>(
613         subTensorOp, subTensorOp.getType(), newSubTensorOp, reassociation);
614     return success();
615   }
616 };
617 
618 } // namespace
619 
620 /// Patterns that are used to canonicalize the use of unit-extent dims for
621 /// broadcasting.
622 void mlir::linalg::populateFoldUnitExtentDimsPatterns(
623     RewritePatternSet &patterns) {
624   auto *context = patterns.getContext();
625   patterns.add<FoldUnitDimLoops<GenericOp>, FoldUnitDimLoops<IndexedGenericOp>,
626                FoldUnitDimSubTensorOp, ReplaceUnitExtentTensors<GenericOp>,
627                ReplaceUnitExtentTensors<IndexedGenericOp>>(context);
628   TensorReshapeOp::getCanonicalizationPatterns(patterns, context);
629   patterns.add<FoldReshapeOpWithUnitExtent>(context);
630 }
631 
632 namespace {
633 /// Pass that removes unit-extent dims within generic ops.
634 struct LinalgFoldUnitExtentDimsPass
635     : public LinalgFoldUnitExtentDimsBase<LinalgFoldUnitExtentDimsPass> {
636   void runOnFunction() override {
637     FuncOp funcOp = getFunction();
638     MLIRContext *context = funcOp.getContext();
639     RewritePatternSet patterns(context);
640     if (foldOneTripLoopsOnly)
641       patterns
642           .add<FoldUnitDimLoops<GenericOp>, FoldUnitDimLoops<IndexedGenericOp>>(
643               context);
644     else
645       populateFoldUnitExtentDimsPatterns(patterns);
646     (void)applyPatternsAndFoldGreedily(funcOp.getBody(), std::move(patterns));
647   }
648 };
649 } // namespace
650 
651 std::unique_ptr<OperationPass<FuncOp>>
652 mlir::createLinalgFoldUnitExtentDimsPass() {
653   return std::make_unique<LinalgFoldUnitExtentDimsPass>();
654 }
655