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 /// Modify the region of indexed generic op to drop arguments corresponding to
149 /// loops that are unit trip count.
150 template <typename OpTy>
151 static LogicalResult
152 replaceBlockArgForUnitDimLoops(OpTy op, const DenseSet<unsigned> &unitDims,
153                                PatternRewriter &rewriterp) {
154   return success();
155 }
156 
157 template <>
158 LogicalResult replaceBlockArgForUnitDimLoops<IndexedGenericOp>(
159     IndexedGenericOp op, const DenseSet<unsigned> &unitDims,
160     PatternRewriter &rewriter) {
161   OpBuilder::InsertionGuard guard(rewriter);
162   Block *entryBlock = &op->getRegion(0).front();
163   rewriter.setInsertionPointToStart(entryBlock);
164   Value zero = rewriter.create<ConstantIndexOp>(op.getLoc(), 0);
165   for (unsigned unitDimLoop : unitDims) {
166     entryBlock->getArgument(unitDimLoop).replaceAllUsesWith(zero);
167   }
168   SmallVector<unsigned, 8> unitDimsToErase(unitDims.begin(), unitDims.end());
169   entryBlock->eraseArguments(unitDimsToErase);
170   return success();
171 }
172 
173 namespace {
174 /// Pattern to fold unit-trip count loops in GenericOps.
175 template <typename GenericOpTy>
176 struct FoldUnitDimLoops : public OpRewritePattern<GenericOpTy> {
177   using OpRewritePattern<GenericOpTy>::OpRewritePattern;
178   LogicalResult matchAndRewrite(GenericOpTy op,
179                                 PatternRewriter &rewriter) const override {
180     SmallVector<AffineMap, 4> indexingMaps = op.getIndexingMaps();
181     if (indexingMaps.empty())
182       return failure();
183 
184     // Check if any of the iteration dimensions are unit-trip count. They will
185     // end up being unit-trip count if they are used to index into a unit-dim
186     // tensor/memref.
187     AffineMap invertedMap = inversePermutation(concatAffineMaps(indexingMaps));
188     if (!invertedMap)
189       return failure();
190     SmallVector<int64_t, 4> dims;
191     for (ShapedType shapedType : op.getShapedOperandTypes())
192       dims.append(shapedType.getShape().begin(), shapedType.getShape().end());
193     DenseSet<unsigned> unitDims;
194     ArrayAttr iteratorTypes = op.iterator_types();
195     for (auto expr : enumerate(invertedMap.getResults())) {
196       if (AffineDimExpr dimExpr = expr.value().dyn_cast<AffineDimExpr>())
197         if (dims[dimExpr.getPosition()] == 1 &&
198             iteratorTypes[expr.index()].dyn_cast<StringAttr>().getValue() ==
199                 getParallelIteratorTypeName())
200           unitDims.insert(expr.index());
201     }
202     if (unitDims.empty())
203       return failure();
204 
205     // Compute the modified indexing maps.
206     MLIRContext *context = rewriter.getContext();
207     ArrayAttr newIndexingMapAttr =
208         replaceUnitDims(unitDims, indexingMaps, context);
209     if (!newIndexingMapAttr)
210       return op.emitError("unable to compute modified indexing_maps");
211 
212     // Compute the iterator types of the modified op by dropping the one-trip
213     // count loops.
214     SmallVector<Attribute, 4> newIteratorTypes;
215     for (auto attr : llvm::enumerate(iteratorTypes)) {
216       if (!unitDims.count(attr.index()))
217         newIteratorTypes.push_back(attr.value());
218     }
219 
220     rewriter.startRootUpdate(op);
221     op.indexing_mapsAttr(newIndexingMapAttr);
222     op.iterator_typesAttr(ArrayAttr::get(context, newIteratorTypes));
223     (void)replaceBlockArgForUnitDimLoops(op, unitDims, rewriter);
224     rewriter.finalizeRootUpdate(op);
225     return success();
226   }
227 };
228 
229 struct UnitExtentReplacementInfo {
230   RankedTensorType type;
231   AffineMap indexMap;
232   ArrayAttr reassociation;
233 };
234 } // namespace
235 
236 /// Utility function for replacing operands/results to a linalg generic
237 /// operation on tensors with unit-extent dimensions. These can be replaced with
238 /// an operand/result with the unit-extent dimension removed. This is only done
239 /// if the indexing map used to access that didimensionmension has a
240 /// AffineConstantExpr of value 0. Given the `type` of an result/operand of a
241 /// Linalg op, and its `indexMap` the utility function returns:
242 /// - the new type with dimensions of size 1 removed.
243 /// - modified index map that can be used to access the replaced result/operand
244 /// - the reassociation that converts from the original tensor type to the
245 ///   modified tensor type.
246 static UnitExtentReplacementInfo replaceUnitExtents(AffineMap indexMap,
247                                                     RankedTensorType type,
248                                                     MLIRContext *context) {
249   ArrayRef<int64_t> shape = type.getShape();
250   ArrayRef<AffineExpr> exprs = indexMap.getResults();
251   SmallVector<AffineExpr, 2> reassociations;
252   SmallVector<Attribute, 4> reassociationMaps;
253   SmallVector<AffineExpr, 4> newIndexExprs;
254   SmallVector<int64_t, 4> newShape;
255 
256   int64_t origRank = type.getRank();
257   AffineExpr zeroExpr = getAffineConstantExpr(0, context);
258   auto isUnitExtent = [&](int64_t dim) -> bool {
259     return shape[dim] == 1 && exprs[dim] == zeroExpr;
260   };
261 
262   unsigned dim = 0;
263   // Fold dimensions that are unit-extent at the beginning of the tensor.
264   while (dim < origRank && isUnitExtent(dim))
265     reassociations.push_back(getAffineDimExpr(dim++, context));
266   while (dim < origRank) {
267     reassociations.push_back(getAffineDimExpr(dim, context));
268     newIndexExprs.push_back(exprs[dim]);
269     newShape.push_back(shape[dim]);
270     // Fold all following dimensions that are unit-extent.
271     while (dim + 1 < origRank && isUnitExtent(dim + 1)) {
272       ++dim;
273       reassociations.push_back(getAffineDimExpr(dim, context));
274     }
275     reassociationMaps.push_back(AffineMapAttr::get(AffineMap::get(
276         origRank, /*numSymbols = */ 0, reassociations, context)));
277     reassociations.clear();
278     ++dim;
279   }
280   UnitExtentReplacementInfo info = {
281       RankedTensorType::get(newShape, type.getElementType()),
282       AffineMap::get(indexMap.getNumDims(), indexMap.getNumSymbols(),
283                      newIndexExprs, context),
284       ArrayAttr::get(context, reassociationMaps)};
285   return info;
286 }
287 
288 namespace {
289 
290 /// Pattern to replace tensors operands/results that are unit extents.
291 template <typename GenericOpTy>
292 struct ReplaceUnitExtentTensors : public OpRewritePattern<GenericOpTy> {
293   using OpRewritePattern<GenericOpTy>::OpRewritePattern;
294   LogicalResult matchAndRewrite(GenericOpTy op,
295                                 PatternRewriter &rewriter) const override {
296     // TODO: support reductions.
297     if (!op.hasTensorSemantics())
298       return failure();
299 
300     MLIRContext *context = rewriter.getContext();
301     Location loc = op.getLoc();
302 
303     SmallVector<AffineMap, 4> newIndexingMaps;
304     SmallVector<ArrayAttr, 4> reassociationMaps;
305     SmallVector<ShapedType, 4> newInputOutputTypes;
306     bool doCanonicalization = false;
307     for (auto it :
308          llvm::zip(op.getIndexingMaps(), op.getShapedOperandTypes())) {
309       auto replacementInfo = replaceUnitExtents(
310           std::get<0>(it), std::get<1>(it).template cast<RankedTensorType>(),
311           context);
312       reassociationMaps.push_back(replacementInfo.reassociation);
313       newIndexingMaps.push_back(replacementInfo.indexMap);
314       newInputOutputTypes.push_back(replacementInfo.type);
315       doCanonicalization |= replacementInfo.type != std::get<1>(it);
316     }
317 
318     // If the indexing maps of the result operation are not invertible (i.e. not
319     // legal), abort.
320     if (!doCanonicalization ||
321         !inversePermutation(concatAffineMaps(newIndexingMaps)))
322       return failure();
323 
324     // If any operand type change, insert a reshape to convert from the original
325     // type to the new type.
326     // TODO: get rid of flattenedIdx which assumes operand order and contiguity.
327     unsigned flattenedIdx = 0;
328     auto insertReshapes = [&](ValueRange values) {
329       SmallVector<Value, 4> res;
330       res.reserve(values.size());
331       for (auto operand : llvm::enumerate(values)) {
332         if (operand.value().getType() == newInputOutputTypes[flattenedIdx])
333           res.push_back(operand.value());
334         else
335           res.push_back(rewriter.create<linalg::TensorReshapeOp>(
336               loc, newInputOutputTypes[flattenedIdx], operand.value(),
337               reassociationMaps[flattenedIdx]));
338         ++flattenedIdx;
339       }
340       return res;
341     };
342 
343     SmallVector<Value, 4> newInputs = insertReshapes(op.inputs());
344     SmallVector<Value, 4> newOutputs = insertReshapes(op.outputs());
345 
346     // If any result type changes, insert a reshape to convert from the original
347     // type to the new type.
348     SmallVector<Type, 4> resultTypes;
349     resultTypes.reserve(op.getNumResults());
350     for (unsigned i : llvm::seq<unsigned>(0, op.getNumResults()))
351       resultTypes.push_back(newInputOutputTypes[i + op.getNumInputs()]);
352     GenericOpTy replacementOp = rewriter.create<GenericOpTy>(
353         loc, resultTypes, newInputs, newOutputs, newIndexingMaps,
354         llvm::to_vector<4>(
355             op.iterator_types().template getAsValueRange<StringAttr>()));
356     rewriter.inlineRegionBefore(op.region(), replacementOp.region(),
357                                 replacementOp.region().begin());
358 
359     // If any result tensor has a modified shape, then add reshape to recover
360     // the original shape.
361     SmallVector<Value, 4> resultReplacements;
362     for (auto result : llvm::enumerate(replacementOp.getResults())) {
363       unsigned index = result.index() + replacementOp.getNumInputs();
364       RankedTensorType origResultType = op.getResult(result.index())
365                                             .getType()
366                                             .template cast<RankedTensorType>();
367       if (origResultType != result.value().getType())
368         resultReplacements.push_back(rewriter.create<linalg::TensorReshapeOp>(
369             loc, origResultType, result.value(), reassociationMaps[index]));
370       else
371         resultReplacements.push_back(result.value());
372     }
373     rewriter.replaceOp(op, resultReplacements);
374     return success();
375   }
376 };
377 
378 /// Pattern to fold pair of reshape ops where the intermediate has unit-dims for
379 /// example:
380 ///
381 ///  %0 = linalg.tensor_reshape %arg0
382 ///    [affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>]
383 ///    : tensor<2048xf32> into tensor<1x4x1x512xf32>
384 ///  %1 = linalg.tensor_reshape %0
385 ///    [affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>,
386 ///     affine_map<(d0, d1, d2, d3) -> (d3)>]
387 ///    : tensor<1x4x1x512xf32> into tensor<4x512xf32>
388 ///
389 /// can be replaced with
390 ///
391 ///  %0 = linalg.tensor_reshape %arg0 [affine_map<(d0, d1) -> (d0, d1)>]
392 ///    : tensor<2048xf32> into tensor<4x512xf32>
393 ///
394 /// Similarly,
395 ///
396 ///  %0 = linalg.tensor_reshape %arg0
397 ///    [affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>,
398 ///     affine_map<(d0, d1, d2, d3) -> (d3)>]
399 ///    : tensor<4x512xf32> into tensor<1x4x1x512xf32>
400 ///  %1 = linalg.tensor_reshape %0
401 ///   [affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>]
402 ///    : tensor<1x4x1x512xf32> into tensor<2048xf32>
403 ///
404 /// can be replaced with
405 ///
406 ///  %0 = linalg.tensor_reshape %arg0 [affine_map<(d0, d1) -> (d0, d1)>]
407 ///    : tensor<4x512xf32> into tensor<2048xf32>
408 struct FoldReshapeOpWithUnitExtent : OpRewritePattern<TensorReshapeOp> {
409   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
410 
411   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
412                                 PatternRewriter &rewriter) const override {
413     // Check that the source operand is created from a reshape as well.
414     TensorReshapeOp parentReshapeOp =
415         reshapeOp.src().getDefiningOp<TensorReshapeOp>();
416     if (!parentReshapeOp)
417       return failure();
418 
419     RankedTensorType srcType = reshapeOp.getSrcType(),
420                      dstType = reshapeOp.getResultType(),
421                      parentSrcType = parentReshapeOp.getSrcType();
422     if (!srcType.hasStaticShape() || !dstType.hasStaticShape() ||
423         !parentSrcType.hasStaticShape() ||
424         srcType.getRank() < dstType.getRank() ||
425         parentSrcType.getRank() == dstType.getRank())
426       return failure();
427 
428     // Check if the result tensor_reshape is folding or expanding after folding
429     // the reshapeOp and parentReshapeOp are combined.  If the final
430     // tensor_reshape is folding, the parentReshapeOp is introducing unit-dims,
431     // and the reshapeOp does an actual reshape.  If the final tensor_reshape op
432     // is expanding, the reshapeOp is introducing unit-dims, and the
433     // parentReshapeOp does an actual reshape.
434     bool isFoldingPattern = parentSrcType.getRank() > dstType.getRank();
435     ArrayRef<int64_t> expandedShape =
436         isFoldingPattern ? parentSrcType.getShape() : dstType.getShape();
437     ArrayRef<int64_t> foldedShape =
438         isFoldingPattern ? dstType.getShape() : parentSrcType.getShape();
439 
440     unsigned expandedDim = 0, foldedDim = 0;
441     SmallVector<SmallVector<AffineExpr, 4>, 4> reassociationExprs(
442         foldedShape.size());
443     while (expandedDim < expandedShape.size() &&
444            foldedDim < foldedShape.size()) {
445       int64_t dstSize = foldedShape[foldedDim];
446       int64_t srcSize = expandedShape[expandedDim];
447       while (srcSize < dstSize && expandedDim < expandedShape.size()) {
448         reassociationExprs[foldedDim].push_back(
449             rewriter.getAffineDimExpr(expandedDim++));
450         srcSize *= expandedShape[expandedDim];
451       }
452       if (srcSize == dstSize) {
453         reassociationExprs[foldedDim].push_back(
454             rewriter.getAffineDimExpr(expandedDim++));
455         // If the next dim in foldedShape is not 1, treat subsequent dims in
456         // expandedShape which are 1 to be collapsed.
457         if (foldedDim == foldedShape.size() - 1 ||
458             foldedShape[foldedDim + 1] != 1) {
459           while (expandedDim < expandedShape.size() &&
460                  expandedShape[expandedDim] == 1) {
461             reassociationExprs[foldedDim].push_back(
462                 rewriter.getAffineDimExpr(expandedDim++));
463           }
464         }
465       } else {
466         return failure();
467       }
468       foldedDim++;
469     }
470     if (expandedDim != expandedShape.size())
471       return failure();
472 
473     SmallVector<AffineMap, 4> reassociationMaps =
474         llvm::to_vector<4>(llvm::map_range(
475             reassociationExprs, [&](ArrayRef<AffineExpr> exprs) -> AffineMap {
476               return AffineMap::get(expandedShape.size(), 0, exprs,
477                                     rewriter.getContext());
478             }));
479     rewriter.replaceOpWithNewOp<TensorReshapeOp>(
480         reshapeOp, dstType, parentReshapeOp.src(),
481         rewriter.getAffineMapArrayAttr(reassociationMaps));
482     return success();
483   }
484 };
485 
486 /// Pattern to fold subtensors that are just taking a slice of unit-dimension
487 /// tensor. For example
488 ///
489 /// %1 = subtensor %0[0, %o1, 0] [1, %s1, 1] [1, 1, 1]
490 ///     : tensor<1x?x1xf32> to tensor<1x?x1xf32>
491 ///
492 /// can be replaced with
493 ///
494 /// %0 = linalg.tensor_reshape %0 [affine_map<(d0, d1, d2) -> (d0, d1, d2)>]
495 ///     : tensor<1x?x1xf32> into tensor<?xf32>
496 /// %1 = subtensor %0[%o1] [%s1] [1] : tensor<?xf32> to tensor<?xf32>
497 /// %2 = linalg.tensor_reshape %1 [affine_map<(d0, d1, d2) -> (d0, d1, d2)>]
498 ///     : tensor<?xf32> into tensor<1x?x1xf32>
499 ///
500 /// The additional tensor_reshapes will hopefully get canonicalized away with
501 /// other reshapes that drop unit dimensions. Three condiitions to fold a
502 /// dimension
503 /// - The offset must be 0
504 /// - The size must be 1
505 /// - The dimension of the source type must be 1.
506 struct FoldUnitDimSubTensorOp : public OpRewritePattern<SubTensorOp> {
507   using OpRewritePattern<SubTensorOp>::OpRewritePattern;
508 
509   LogicalResult matchAndRewrite(SubTensorOp subTensorOp,
510                                 PatternRewriter &rewriter) const override {
511     SmallVector<OpFoldResult> mixedOffsets = subTensorOp.getMixedOffsets();
512     SmallVector<OpFoldResult> mixedSizes = subTensorOp.getMixedSizes();
513     SmallVector<OpFoldResult> mixedStrides = subTensorOp.getMixedStrides();
514     auto hasValue = [](OpFoldResult valueOrAttr, int64_t val) {
515       auto attr = valueOrAttr.dyn_cast<Attribute>();
516       return attr && attr.cast<IntegerAttr>().getInt() == val;
517     };
518 
519     if (llvm::any_of(mixedStrides, [&](OpFoldResult valueOrAttr) {
520           return !hasValue(valueOrAttr, 1);
521         }))
522       return failure();
523 
524     // Find the expanded unit dimensions.
525     SmallVector<ReassociationIndices> reassociation;
526     SmallVector<OpFoldResult> newOffsets, newSizes;
527     ArrayRef<int64_t> sourceShape = subTensorOp.getSourceType().getShape();
528     ReassociationIndices curr;
529     for (int64_t dim : llvm::seq<int64_t>(0, mixedOffsets.size())) {
530       curr.push_back(dim);
531       if (sourceShape[dim] == 1 && hasValue(mixedOffsets[dim], 0) &&
532           hasValue(mixedSizes[dim], 1)) {
533         continue;
534       }
535       newOffsets.push_back(mixedOffsets[dim]);
536       newSizes.push_back(mixedSizes[dim]);
537       reassociation.emplace_back(ReassociationIndices{});
538       std::swap(reassociation.back(), curr);
539     }
540     if (newOffsets.size() == mixedOffsets.size())
541       return failure();
542     reassociation.back().append(curr.begin(), curr.end());
543     SmallVector<OpFoldResult> newStrides(newOffsets.size(),
544                                          rewriter.getI64IntegerAttr(1));
545     Location loc = subTensorOp->getLoc();
546     auto srcReshape = rewriter.create<TensorReshapeOp>(
547         loc, subTensorOp.source(), reassociation);
548     auto newSubTensorOp = rewriter.create<SubTensorOp>(
549         loc, srcReshape, newOffsets, newSizes, newStrides);
550     rewriter.replaceOpWithNewOp<TensorReshapeOp>(
551         subTensorOp, subTensorOp.getType(), newSubTensorOp, reassociation);
552     return success();
553   }
554 };
555 
556 } // namespace
557 
558 /// Patterns that are used to canonicalize the use of unit-extent dims for
559 /// broadcasting.
560 void mlir::linalg::populateFoldUnitExtentDimsPatterns(
561     RewritePatternSet &patterns) {
562   auto *context = patterns.getContext();
563   patterns.add<FoldUnitDimLoops<GenericOp>, FoldUnitDimLoops<IndexedGenericOp>,
564                FoldUnitDimSubTensorOp, ReplaceUnitExtentTensors<GenericOp>,
565                ReplaceUnitExtentTensors<IndexedGenericOp>>(context);
566   TensorReshapeOp::getCanonicalizationPatterns(patterns, context);
567   patterns.add<FoldReshapeOpWithUnitExtent>(context);
568   populateFoldUnitDimsReshapeOpsByLinearizationPatterns(patterns);
569 }
570 
571 namespace {
572 /// Pass that removes unit-extent dims within generic ops.
573 struct LinalgFoldUnitExtentDimsPass
574     : public LinalgFoldUnitExtentDimsBase<LinalgFoldUnitExtentDimsPass> {
575   void runOnFunction() override {
576     FuncOp funcOp = getFunction();
577     MLIRContext *context = funcOp.getContext();
578     RewritePatternSet patterns(context);
579     if (foldOneTripLoopsOnly)
580       patterns
581           .add<FoldUnitDimLoops<GenericOp>, FoldUnitDimLoops<IndexedGenericOp>>(
582               context);
583     else
584       populateFoldUnitExtentDimsPatterns(patterns);
585     (void)applyPatternsAndFoldGreedily(funcOp.getBody(), std::move(patterns));
586   }
587 };
588 } // namespace
589 
590 std::unique_ptr<OperationPass<FuncOp>>
591 mlir::createLinalgFoldUnitExtentDimsPass() {
592   return std::make_unique<LinalgFoldUnitExtentDimsPass>();
593 }
594