MLIR  20.0.0git
DropUnitDims.cpp
Go to the documentation of this file.
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 
16 
27 #include "mlir/IR/AffineExpr.h"
28 #include "mlir/IR/AffineMap.h"
29 #include "mlir/IR/BuiltinTypes.h"
32 #include "llvm/ADT/SetVector.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 
36 namespace mlir {
37 #define GEN_PASS_DEF_LINALGFOLDUNITEXTENTDIMSPASS
38 #include "mlir/Dialect/Linalg/Passes.h.inc"
39 } // namespace mlir
40 
41 #define DEBUG_TYPE "linalg-drop-unit-dims"
42 
43 using namespace mlir;
44 using namespace mlir::linalg;
45 
46 namespace {
47 /// Pattern to move init operands to ins when all the loops are parallel and
48 /// blockArgument corresponding to init is used in the region. This is a fix-up
49 /// when unit reduction dimensions are all folded away. In this context, it
50 /// becomes a elementwise generic op. E.g., it converts
51 ///
52 /// %0 = tensor.empty() : tensor<1x1xf32>
53 /// %1 = linalg.fill
54 /// ins(%cst : f32)
55 /// outs(%0 : tensor<1x1xf32>) -> tensor<1x1xf32>
56 /// %2 = linalg.generic {indexing_maps = [affine_map<(d0) -> (0, d0, 0, 0)>,
57 /// affine_map<(d0) -> (0, d0)>],
58 /// iterator_types = ["parallel"]}
59 /// ins(%arg0 : tensor<1x?x1x1xf32>)
60 /// outs(%1 : tensor<1x1xf32>) {
61 /// ^bb0(%in: f32, %out: f32):
62 /// %3 = arith.addf %in, %out : f32
63 /// linalg.yield %3 : f32
64 /// } -> tensor<1x1xf32>
65 ///
66 /// into
67 ///
68 /// %0 = tensor.empty() : tensor<1x1xf32>
69 /// %1 = linalg.fill
70 /// ins(%cst : f32)
71 /// outs(%0 : tensor<1x1xf32>) -> tensor<1x1xf32>
72 /// %2 = tensor.empty() : tensor<1x1xf32>
73 /// %3 = linalg.generic {indexing_maps = [affine_map<(d0) -> (0, d0, 0, 0)>,
74 /// affine_map<(d0) -> (0, d0)>,
75 /// affine_map<(d0) -> (0, d0)>],
76 /// iterator_types = ["parallel"]}
77 /// ins(%arg0, %1 : tensor<1x?x1x1xf32>, tensor<1x1xf32>)
78 /// outs(%2 : tensor<1x1xf32>) {
79 /// ^bb0(%in: f32, %in_0: f32, %out: f32):
80 /// %4 = arith.addf %in, %in_0 : f32
81 /// linalg.yield %4 : f32
82 /// } -> tensor<1x1xf32>
83 struct MoveInitOperandsToInput : public OpRewritePattern<GenericOp> {
85  LogicalResult matchAndRewrite(GenericOp genericOp,
86  PatternRewriter &rewriter) const override {
87  if (!genericOp.hasPureTensorSemantics())
88  return failure();
89  if (genericOp.getNumParallelLoops() != genericOp.getNumLoops())
90  return failure();
91 
92  auto outputOperands = genericOp.getDpsInitsMutable();
93  SetVector<OpOperand *> candidates;
94  for (OpOperand &op : outputOperands) {
95  if (genericOp.getMatchingBlockArgument(&op).use_empty())
96  continue;
97  candidates.insert(&op);
98  }
99 
100  if (candidates.empty())
101  return failure();
102 
103  // Compute the modified indexing maps.
104  int64_t origNumInput = genericOp.getNumDpsInputs();
105  SmallVector<Value> newInputOperands = genericOp.getDpsInputs();
106  SmallVector<AffineMap> indexingMaps = genericOp.getIndexingMapsArray();
107  SmallVector<AffineMap> newIndexingMaps;
108  newIndexingMaps.append(indexingMaps.begin(),
109  std::next(indexingMaps.begin(), origNumInput));
110  for (OpOperand *op : candidates) {
111  newInputOperands.push_back(op->get());
112  newIndexingMaps.push_back(genericOp.getMatchingIndexingMap(op));
113  }
114  newIndexingMaps.append(std::next(indexingMaps.begin(), origNumInput),
115  indexingMaps.end());
116 
117  Location loc = genericOp.getLoc();
118  SmallVector<Value> newOutputOperands =
119  llvm::to_vector(genericOp.getDpsInits());
120  for (OpOperand *op : candidates) {
121  OpBuilder::InsertionGuard guard(rewriter);
122  rewriter.setInsertionPointAfterValue(op->get());
123  auto elemType = cast<ShapedType>(op->get().getType()).getElementType();
124  auto empty = rewriter.create<tensor::EmptyOp>(
125  loc, tensor::getMixedSizes(rewriter, loc, op->get()), elemType);
126 
127  unsigned start = genericOp.getDpsInits().getBeginOperandIndex();
128  newOutputOperands[op->getOperandNumber() - start] = empty.getResult();
129  }
130 
131  auto newOp = rewriter.create<GenericOp>(
132  loc, genericOp.getResultTypes(), newInputOperands, newOutputOperands,
133  newIndexingMaps, genericOp.getIteratorTypesArray(),
134  /*bodyBuild=*/nullptr, linalg::getPrunedAttributeList(genericOp));
135 
136  OpBuilder::InsertionGuard guard(rewriter);
137  Region &region = newOp.getRegion();
138  Block *block = rewriter.createBlock(&region);
139  IRMapping mapper;
140  for (auto bbarg : genericOp.getRegionInputArgs())
141  mapper.map(bbarg, block->addArgument(bbarg.getType(), loc));
142 
143  for (OpOperand *op : candidates) {
144  BlockArgument bbarg = genericOp.getMatchingBlockArgument(op);
145  mapper.map(bbarg, block->addArgument(bbarg.getType(), loc));
146  }
147 
148  for (OpOperand &op : outputOperands) {
149  BlockArgument bbarg = genericOp.getMatchingBlockArgument(&op);
150  if (candidates.count(&op))
151  block->addArgument(bbarg.getType(), loc);
152  else
153  mapper.map(bbarg, block->addArgument(bbarg.getType(), loc));
154  }
155 
156  for (auto &op : genericOp.getBody()->getOperations()) {
157  rewriter.clone(op, mapper);
158  }
159  rewriter.replaceOp(genericOp, newOp.getResults());
160 
161  return success();
162  }
163 };
164 } // namespace
165 
166 //===---------------------------------------------------------------------===//
167 // Drop loops that are unit-extents within Linalg operations.
168 //===---------------------------------------------------------------------===//
169 
170 /// Implements a pass that canonicalizes the uses of unit-extent dimensions for
171 /// broadcasting. For example,
172 ///
173 /// ```mlir
174 /// #accesses = [
175 /// affine_map<(d0, d1) -> (0, d1)>,
176 /// affine_map<(d0, d1) -> (d0, 0)>,
177 /// affine_map<(d0, d1) -> (d0, d1)>
178 /// ]
179 ///
180 /// #trait = {
181 /// args_in = 2,
182 /// args_out = 1,
183 /// indexing_maps = #accesses,
184 /// iterator_types = ["parallel", "parallel"],
185 /// library_call = "some_external_fn"
186 /// }
187 ///
188 /// func @broadcast_test(%arg0 : tensor<5xf32>, %arg1 : tensor<5xf32>) ->
189 /// tensor<5x5xf32>
190 /// {
191 /// %0 = linalg.tensor_reshape %arg0 [affine_map<(d0, d1) -> (d0, d1)>] :
192 /// tensor<5xf32> into tensor<1x5xf32>
193 /// %1 = linalg.tensor_reshape %arg1 [affine_map<(d0, d1) -> (d0, d1)>] :
194 /// tensor<5xf32> into tensor<5x1xf32>
195 /// %2 = linalg.generic #trait %0, %1 {
196 /// ^bb0(%arg2: f32, %arg3: f32):
197 /// %3 = arith.addf %arg2, %arg3 : f32
198 /// linalg.yield %3 : f32
199 /// } : tensor<1x5xf32>, tensor<5x1xf32> -> tensor<5x5xf32>
200 /// return %2 : tensor<5x5xf32>
201 /// }
202 ///
203 /// would canonicalize to
204 ///
205 /// ```mlir
206 /// #accesses = [
207 /// affine_map<(d0, d1) -> (d1)>,
208 /// affine_map<(d0, d1) -> (d0)>,
209 /// affine_map<(d0, d1) -> (d0, d1)>
210 /// ]
211 ///
212 /// #trait = {
213 /// args_in = 2,
214 /// args_out = 1,
215 /// indexing_maps = #accesses,
216 /// iterator_types = ["parallel", "parallel"],
217 /// library_call = "some_external_fn"
218 /// }
219 ///
220 /// func @broadcast_test(%arg0 : tensor<5xf32>, %arg1 : tensor<5xf32>) ->
221 /// tensor<5x5xf32>
222 /// {
223 /// %0 = linalg.generic #trait %arg0, %arg1 {
224 /// ^bb0(%arg2: f32, %arg3: f32):
225 /// %3 = arith.addf %arg2, %arg3 : f32
226 /// linalg.yield %3 : f32
227 /// } : tensor<5xf32>, tensor<5xf32> -> tensor<5x5xf32>
228 /// return %0 : tensor<5x5xf32>
229 /// }
230 
231 /// Update the index accesses of linalg operations having index semantics.
232 static void
233 replaceUnitDimIndexOps(GenericOp genericOp,
234  const llvm::SmallDenseSet<unsigned> &unitDims,
235  RewriterBase &rewriter) {
236  for (IndexOp indexOp :
237  llvm::make_early_inc_range(genericOp.getBody()->getOps<IndexOp>())) {
238  OpBuilder::InsertionGuard guard(rewriter);
239  rewriter.setInsertionPoint(indexOp);
240  if (unitDims.count(indexOp.getDim()) != 0) {
241  rewriter.replaceOpWithNewOp<arith::ConstantIndexOp>(indexOp, 0);
242  } else {
243  // Update the dimension of the index operation if needed.
244  unsigned droppedDims = llvm::count_if(
245  unitDims, [&](unsigned dim) { return dim < indexOp.getDim(); });
246  if (droppedDims != 0)
247  rewriter.replaceOpWithNewOp<IndexOp>(indexOp,
248  indexOp.getDim() - droppedDims);
249  }
250  }
251 }
252 
253 /// Expand the given `value` so that the type matches the type of `origDest`.
254 /// The `reassociation` is used when `rankReductionStrategy` is set to
255 /// `RankReductionStrategy::ReassociativeReshape`.
256 static Value
257 expandValue(RewriterBase &rewriter, Location loc, Value result, Value origDest,
258  ArrayRef<ReassociationIndices> reassociation,
259  ControlDropUnitDims::RankReductionStrategy rankReductionStrategy) {
260  // There are no results for memref outputs.
261  auto origResultType = cast<RankedTensorType>(origDest.getType());
262  if (rankReductionStrategy ==
264  unsigned rank = origResultType.getRank();
265  SmallVector<OpFoldResult> offsets(rank, rewriter.getIndexAttr(0));
267  tensor::getMixedSizes(rewriter, loc, origDest);
268  SmallVector<OpFoldResult> strides(rank, rewriter.getIndexAttr(1));
269  return rewriter.createOrFold<tensor::InsertSliceOp>(
270  loc, result, origDest, offsets, sizes, strides);
271  }
272 
273  assert(rankReductionStrategy ==
275  "unknown rank reduction strategy");
276  return rewriter
277  .create<tensor::ExpandShapeOp>(loc, origResultType, result, reassociation)
278  .getResult();
279 }
280 
281 /// Collapse the given `value` so that the type matches the type of
282 /// `origOutput`. The `reassociation` is used when `rankReductionStrategy` is
283 /// set to `RankReductionStrategy::ReassociativeReshape`.
285  RewriterBase &rewriter, Location loc, Value operand,
286  ArrayRef<int64_t> targetShape, ArrayRef<ReassociationIndices> reassociation,
287  ControlDropUnitDims::RankReductionStrategy rankReductionStrategy) {
288  if (auto memrefType = dyn_cast<MemRefType>(operand.getType())) {
289  if (rankReductionStrategy ==
291  FailureOr<Value> rankReducingExtract =
292  memref::SubViewOp::rankReduceIfNeeded(rewriter, loc, operand,
293  targetShape);
294  assert(succeeded(rankReducingExtract) && "not a unit-extent collapse");
295  return *rankReducingExtract;
296  }
297 
298  assert(
299  rankReductionStrategy ==
301  "unknown rank reduction strategy");
302  MemRefLayoutAttrInterface layout;
303  auto targetType = MemRefType::get(targetShape, memrefType.getElementType(),
304  layout, memrefType.getMemorySpace());
305  return rewriter.create<memref::CollapseShapeOp>(loc, targetType, operand,
306  reassociation);
307  }
308  if (auto tensorType = dyn_cast<RankedTensorType>(operand.getType())) {
309  if (rankReductionStrategy ==
311  FailureOr<Value> rankReducingExtract =
312  tensor::ExtractSliceOp::rankReduceIfNeeded(rewriter, loc, operand,
313  targetShape);
314  assert(succeeded(rankReducingExtract) && "not a unit-extent collapse");
315  return *rankReducingExtract;
316  }
317 
318  assert(
319  rankReductionStrategy ==
321  "unknown rank reduction strategy");
322  auto targetType =
323  RankedTensorType::get(targetShape, tensorType.getElementType());
324  return rewriter.create<tensor::CollapseShapeOp>(loc, targetType, operand,
325  reassociation);
326  }
327  llvm_unreachable("unsupported operand type");
328 }
329 
330 /// Compute the modified metadata for an operands of operation
331 /// whose unit dims are being dropped. Return the new indexing map
332 /// to use, the shape of the operand in the replacement op
333 /// and the `reassocation` to use to go from original operand shape
334 /// to modified operand shape.
339 };
341  MLIRContext *context, GenericOp genericOp, OpOperand *opOperand,
342  llvm::SmallDenseMap<unsigned, unsigned> &oldDimsToNewDimsMap,
343  ArrayRef<AffineExpr> dimReplacements) {
345  ReassociationIndices reassociationGroup;
346  SmallVector<AffineExpr> newIndexExprs;
347  AffineMap indexingMap = genericOp.getMatchingIndexingMap(opOperand);
348  ArrayRef<int64_t> operandShape = genericOp.getShape(opOperand);
349  ArrayRef<AffineExpr> exprs = indexingMap.getResults();
350 
351  auto isUnitDim = [&](unsigned dim) {
352  if (auto dimExpr = dyn_cast<AffineDimExpr>(exprs[dim])) {
353  unsigned oldPosition = dimExpr.getPosition();
354  return !oldDimsToNewDimsMap.count(oldPosition) &&
355  (operandShape[dim] == 1);
356  }
357  // Handle the other case where the shape is 1, and is accessed using a
358  // constant 0.
359  if (operandShape[dim] == 1) {
360  auto constAffineExpr = dyn_cast<AffineConstantExpr>(exprs[dim]);
361  return constAffineExpr && constAffineExpr.getValue() == 0;
362  }
363  return false;
364  };
365 
366  unsigned dim = 0;
367  while (dim < operandShape.size() && isUnitDim(dim))
368  reassociationGroup.push_back(dim++);
369  while (dim < operandShape.size()) {
370  assert(!isUnitDim(dim) && "expected non unit-extent");
371  reassociationGroup.push_back(dim);
372  AffineExpr newExpr = exprs[dim].replaceDims(dimReplacements);
373  newIndexExprs.push_back(newExpr);
374  info.targetShape.push_back(operandShape[dim]);
375  ++dim;
376  // Fold all following dimensions that are unit-extent.
377  while (dim < operandShape.size() && isUnitDim(dim)) {
378  reassociationGroup.push_back(dim++);
379  }
380  info.reassociation.push_back(reassociationGroup);
381  reassociationGroup.clear();
382  }
383  info.indexMap =
384  AffineMap::get(oldDimsToNewDimsMap.size(), indexingMap.getNumSymbols(),
385  newIndexExprs, context);
386  return info;
387 }
388 
389 LogicalResult linalg::dropUnitDims(RewriterBase &rewriter, GenericOp genericOp,
390  const ControlDropUnitDims &options) {
391  SmallVector<AffineMap> indexingMaps = genericOp.getIndexingMapsArray();
392  if (indexingMaps.empty())
393  return failure();
394 
395  // 1. Check if any of the iteration dimensions are unit-trip count. They will
396  // end up being unit-trip count if they are used to index into a unit-dim
397  // tensor/memref.
398  AffineMap invertedMap = inversePermutation(concatAffineMaps(indexingMaps));
399  if (!invertedMap) {
400  return rewriter.notifyMatchFailure(genericOp,
401  "invalid indexing maps for operation");
402  }
403  SmallVector<int64_t> dims = genericOp.getStaticShape();
404 
405  // 1a. Get the allowed list of dimensions to drop from the `options`.
406  SmallVector<unsigned> allowedUnitDims = options.controlFn(genericOp);
407  if (allowedUnitDims.empty()) {
408  return rewriter.notifyMatchFailure(
409  genericOp, "control function returns no allowed unit dims to prune");
410  }
411  llvm::SmallDenseSet<unsigned> unitDimsFilter(allowedUnitDims.begin(),
412  allowedUnitDims.end());
413  llvm::SmallDenseSet<unsigned> unitDims;
414  for (const auto &expr : enumerate(invertedMap.getResults())) {
415  if (AffineDimExpr dimExpr = dyn_cast<AffineDimExpr>(expr.value())) {
416  if (dims[dimExpr.getPosition()] == 1 &&
417  unitDimsFilter.count(expr.index()))
418  unitDims.insert(expr.index());
419  }
420  }
421 
422  // 2. Compute the iterator types of the modified op by dropping the one-trip
423  // count loops.
424  SmallVector<utils::IteratorType> newIteratorTypes;
425  llvm::SmallDenseMap<unsigned, unsigned> oldDimToNewDimMap;
426  SmallVector<AffineExpr> dimReplacements;
427  unsigned newDims = 0;
428  for (auto [index, attr] :
429  llvm::enumerate(genericOp.getIteratorTypesArray())) {
430  if (unitDims.count(index)) {
431  dimReplacements.push_back(
432  getAffineConstantExpr(0, rewriter.getContext()));
433  } else {
434  newIteratorTypes.push_back(attr);
435  oldDimToNewDimMap[index] = newDims;
436  dimReplacements.push_back(
437  getAffineDimExpr(newDims, rewriter.getContext()));
438  newDims++;
439  }
440  }
441 
442  // 3. For each of the operands, find the
443  // - modified affine map to use.
444  // - shape of the operands after the unit-dims are dropped.
445  // - the reassociation indices used to convert from the original
446  // operand type to modified operand (needed only when using reshapes
447  // for rank reduction strategy)
448  // Note that the indexing maps might need changing even if there are no
449  // unit dimensions that are dropped to handle cases where `0` is used to
450  // access a unit-extent tensor. Consider moving this out of this specific
451  // transformation as a stand-alone transformation. Kept here right now due
452  // to legacy.
453  SmallVector<AffineMap> newIndexingMaps;
455  SmallVector<SmallVector<int64_t>> targetShapes;
456  SmallVector<bool> collapsed;
457  auto hasCollapsibleType = [](OpOperand &operand) {
458  Type operandType = operand.get().getType();
459  if (auto memrefOperandType = dyn_cast_or_null<MemRefType>(operandType)) {
460  return memrefOperandType.getLayout().isIdentity();
461  }
462  if (auto tensorOperandType = dyn_cast<RankedTensorType>(operandType)) {
463  return tensorOperandType.getEncoding() == nullptr;
464  }
465  return false;
466  };
467  for (OpOperand &opOperand : genericOp->getOpOperands()) {
468  auto indexingMap = genericOp.getMatchingIndexingMap(&opOperand);
469  ArrayRef<int64_t> shape = genericOp.getShape(&opOperand);
470  if (!hasCollapsibleType(opOperand)) {
471  AffineMap newIndexingMap = indexingMap.replaceDimsAndSymbols(
472  dimReplacements, ArrayRef<AffineExpr>{}, oldDimToNewDimMap.size(), 0);
473  newIndexingMaps.push_back(newIndexingMap);
474  targetShapes.push_back(llvm::to_vector(shape));
475  collapsed.push_back(false);
476  reassociations.push_back({});
477  continue;
478  }
479  auto replacementInfo = dropUnitExtentFromOperandMetadata(
480  rewriter.getContext(), genericOp, &opOperand, oldDimToNewDimMap,
481  dimReplacements);
482  reassociations.push_back(replacementInfo.reassociation);
483  newIndexingMaps.push_back(replacementInfo.indexMap);
484  targetShapes.push_back(replacementInfo.targetShape);
485  collapsed.push_back(!(replacementInfo.indexMap.getNumResults() ==
486  indexingMap.getNumResults()));
487  }
488 
489  // Abort if the indexing maps of the result operation are not invertible
490  // (i.e. not legal) or if no dimension was reduced.
491  if (newIndexingMaps == indexingMaps ||
492  !inversePermutation(concatAffineMaps(newIndexingMaps)))
493  return failure();
494 
495  Location loc = genericOp.getLoc();
496  // 4. For each of the operands, collapse the operand to convert
497  // from original shape to shape in the modified operation if needed,
498  // either through use of reshapes or rank-reducing slices as
499  // specified in `options`.
500  SmallVector<Value> newOperands;
501  for (OpOperand &opOperand : genericOp->getOpOperands()) {
502  int64_t idx = opOperand.getOperandNumber();
503  if (!collapsed[idx]) {
504  newOperands.push_back(opOperand.get());
505  continue;
506  }
507  newOperands.push_back(collapseValue(rewriter, loc, opOperand.get(),
508  targetShapes[idx], reassociations[idx],
509  options.rankReductionStrategy));
510  }
511 
512  // 5. Create the `linalg.generic` operation with the new operands,
513  // indexing maps, iterator types and result types.
514  ArrayRef<Value> newInputs =
515  ArrayRef<Value>(newOperands).take_front(genericOp.getNumDpsInputs());
516  ArrayRef<Value> newOutputs =
517  ArrayRef<Value>(newOperands).take_back(genericOp.getNumDpsInits());
518  SmallVector<Type> resultTypes;
519  resultTypes.reserve(genericOp.getNumResults());
520  for (unsigned i : llvm::seq<unsigned>(0, genericOp.getNumResults()))
521  resultTypes.push_back(newOutputs[i].getType());
522  GenericOp replacementOp =
523  rewriter.create<GenericOp>(loc, resultTypes, newInputs, newOutputs,
524  newIndexingMaps, newIteratorTypes);
525  rewriter.inlineRegionBefore(genericOp.getRegion(), replacementOp.getRegion(),
526  replacementOp.getRegion().begin());
527  // 5a. Replace `linalg.index` operations that refer to the dropped unit
528  // dimensions.
529  replaceUnitDimIndexOps(replacementOp, unitDims, rewriter);
530 
531  // 6. If any result type changes, insert a reshape/slice to convert from the
532  // original
533  // type to the new type.
534  SmallVector<Value> resultReplacements;
535  for (auto [index, result] : llvm::enumerate(replacementOp.getResults())) {
536  unsigned opOperandIndex = index + replacementOp.getNumDpsInputs();
537  Value origDest = genericOp.getDpsInitOperand(index)->get();
538  if (!collapsed[opOperandIndex]) {
539  resultReplacements.push_back(result);
540  continue;
541  }
542  Value expandedValue = expandValue(rewriter, loc, result, origDest,
543  reassociations[opOperandIndex],
544  options.rankReductionStrategy);
545  resultReplacements.push_back(expandedValue);
546  }
547 
548  rewriter.replaceOp(genericOp, resultReplacements);
549  return success();
550 }
551 
552 namespace {
553 struct DropUnitDims : public OpRewritePattern<GenericOp> {
554  DropUnitDims(MLIRContext *context, ControlDropUnitDims options = {},
555  PatternBenefit benefit = 1)
556  : OpRewritePattern(context, benefit), options(std::move(options)) {}
557 
558  LogicalResult matchAndRewrite(GenericOp genericOp,
559  PatternRewriter &rewriter) const override {
560  return dropUnitDims(rewriter, genericOp, options);
561  }
562 
563 private:
565 };
566 } // namespace
567 
568 //===---------------------------------------------------------------------===//
569 // Drop dimensions that are unit-extents within tensor operations.
570 //===---------------------------------------------------------------------===//
571 
572 namespace {
573 struct DropPadUnitDims : public OpRewritePattern<tensor::PadOp> {
574  DropPadUnitDims(MLIRContext *context, ControlDropUnitDims options = {},
575  PatternBenefit benefit = 1)
576  : OpRewritePattern(context, benefit), options(std::move(options)) {}
577 
578  LogicalResult matchAndRewrite(tensor::PadOp padOp,
579  PatternRewriter &rewriter) const override {
580  // 1a. Get the allowed list of dimensions to drop from the `options`.
581  SmallVector<unsigned> allowedUnitDims = options.controlFn(padOp);
582  if (allowedUnitDims.empty()) {
583  return rewriter.notifyMatchFailure(
584  padOp, "control function returns no allowed unit dims to prune");
585  }
586 
587  if (padOp.getSourceType().getEncoding()) {
588  return rewriter.notifyMatchFailure(
589  padOp, "cannot collapse dims of tensor with encoding");
590  }
591 
592  // Fail for non-constant padding values. The body of the pad could
593  // depend on the padding indices and/or properties of the padded
594  // tensor so for now we fail.
595  // TODO: Support non-constant padding values.
596  Value paddingVal = padOp.getConstantPaddingValue();
597  if (!paddingVal) {
598  return rewriter.notifyMatchFailure(
599  padOp, "unimplemented: non-constant padding value");
600  }
601 
602  ArrayRef<int64_t> sourceShape = padOp.getSourceType().getShape();
603  int64_t padRank = sourceShape.size();
604 
605  auto isStaticZero = [](OpFoldResult f) {
606  std::optional<int64_t> maybeInt = getConstantIntValue(f);
607  return maybeInt && *maybeInt == 0;
608  };
609 
610  llvm::SmallDenseSet<unsigned> unitDimsFilter(allowedUnitDims.begin(),
611  allowedUnitDims.end());
612  llvm::SmallDenseSet<unsigned> unitDims;
613  SmallVector<int64_t> newShape;
614  SmallVector<OpFoldResult> newLowPad;
615  SmallVector<OpFoldResult> newHighPad;
616  for (const auto [dim, size, low, high] :
617  zip_equal(llvm::seq(static_cast<int64_t>(0), padRank), sourceShape,
618  padOp.getMixedLowPad(), padOp.getMixedHighPad())) {
619  if (unitDimsFilter.contains(dim) && size == 1 && isStaticZero(low) &&
620  isStaticZero(high)) {
621  unitDims.insert(dim);
622  } else {
623  newShape.push_back(size);
624  newLowPad.push_back(low);
625  newHighPad.push_back(high);
626  }
627  }
628 
629  if (unitDims.empty()) {
630  return rewriter.notifyMatchFailure(padOp, "no unit dims to collapse");
631  }
632 
633  ReassociationIndices reassociationGroup;
634  SmallVector<ReassociationIndices> reassociationMap;
635  int64_t dim = 0;
636  while (dim < padRank && unitDims.contains(dim))
637  reassociationGroup.push_back(dim++);
638  while (dim < padRank) {
639  assert(!unitDims.contains(dim) && "expected non unit-extent");
640  reassociationGroup.push_back(dim);
641  dim++;
642  // Fold all following dimensions that are unit-extent.
643  while (dim < padRank && unitDims.contains(dim))
644  reassociationGroup.push_back(dim++);
645  reassociationMap.push_back(reassociationGroup);
646  reassociationGroup.clear();
647  }
648 
649  Value collapsedSource =
650  collapseValue(rewriter, padOp.getLoc(), padOp.getSource(), newShape,
651  reassociationMap, options.rankReductionStrategy);
652 
653  auto newPadOp = rewriter.create<tensor::PadOp>(
654  padOp.getLoc(), /*result=*/Type(), collapsedSource, newLowPad,
655  newHighPad, paddingVal, padOp.getNofold());
656 
657  Value dest = padOp.getResult();
658  if (options.rankReductionStrategy ==
660  SmallVector<OpFoldResult> expandedSizes;
661  int64_t numUnitDims = 0;
662  for (auto dim : llvm::seq(static_cast<int64_t>(0), padRank)) {
663  if (unitDims.contains(dim)) {
664  expandedSizes.push_back(rewriter.getIndexAttr(1));
665  numUnitDims++;
666  continue;
667  }
668  expandedSizes.push_back(tensor::getMixedSize(
669  rewriter, padOp.getLoc(), newPadOp, dim - numUnitDims));
670  }
671  dest = rewriter.create<tensor::EmptyOp>(
672  padOp.getLoc(), expandedSizes,
673  padOp.getResultType().getElementType());
674  }
675 
676  Value expandedValue =
677  expandValue(rewriter, padOp.getLoc(), newPadOp.getResult(), dest,
678  reassociationMap, options.rankReductionStrategy);
679  rewriter.replaceOp(padOp, expandedValue);
680  return success();
681  }
682 
683 private:
685 };
686 } // namespace
687 
688 namespace {
689 /// Convert `extract_slice` operations to rank-reduced versions.
690 struct RankReducedExtractSliceOp
691  : public OpRewritePattern<tensor::ExtractSliceOp> {
693 
694  LogicalResult matchAndRewrite(tensor::ExtractSliceOp sliceOp,
695  PatternRewriter &rewriter) const override {
696  RankedTensorType resultType = sliceOp.getType();
697  SmallVector<OpFoldResult> targetShape;
698  for (auto size : resultType.getShape())
699  targetShape.push_back(rewriter.getIndexAttr(size));
700  auto reassociation = getReassociationMapForFoldingUnitDims(targetShape);
701  if (!reassociation ||
702  reassociation->size() == static_cast<size_t>(resultType.getRank()))
703  return failure();
704 
705  SmallVector<OpFoldResult> offsets = sliceOp.getMixedOffsets();
706  SmallVector<OpFoldResult> strides = sliceOp.getMixedStrides();
707  SmallVector<OpFoldResult> sizes = sliceOp.getMixedSizes();
708  auto rankReducedType = cast<RankedTensorType>(
709  tensor::ExtractSliceOp::inferCanonicalRankReducedResultType(
710  reassociation->size(), sliceOp.getSourceType(), offsets, sizes,
711  strides));
712 
713  Location loc = sliceOp.getLoc();
714  Value newSlice = rewriter.create<tensor::ExtractSliceOp>(
715  loc, rankReducedType, sliceOp.getSource(), offsets, sizes, strides);
716  rewriter.replaceOpWithNewOp<tensor::ExpandShapeOp>(
717  sliceOp, resultType, newSlice, *reassociation);
718  return success();
719  }
720 };
721 
722 /// Convert `insert_slice` operations to rank-reduced versions.
723 /// This patterns works with both InsertSliceOp and ParallelInsertSliceOp.
724 template <typename InsertOpTy>
725 struct RankReducedInsertSliceOp : public OpRewritePattern<InsertOpTy> {
727 
728  LogicalResult matchAndRewrite(InsertOpTy insertSliceOp,
729  PatternRewriter &rewriter) const override {
730  RankedTensorType sourceType = insertSliceOp.getSourceType();
731  SmallVector<OpFoldResult> targetShape;
732  for (auto size : sourceType.getShape())
733  targetShape.push_back(rewriter.getIndexAttr(size));
734  auto reassociation = getReassociationMapForFoldingUnitDims(targetShape);
735  if (!reassociation ||
736  reassociation->size() == static_cast<size_t>(sourceType.getRank()))
737  return failure();
738 
739  Location loc = insertSliceOp.getLoc();
740  tensor::CollapseShapeOp reshapedSource;
741  {
742  OpBuilder::InsertionGuard g(rewriter);
743  // The only difference between InsertSliceOp and ParallelInsertSliceOp
744  // is the insertion point is just before the ParallelCombiningOp in the
745  // parallel case.
746  if (std::is_same<InsertOpTy, tensor::ParallelInsertSliceOp>::value)
747  rewriter.setInsertionPoint(insertSliceOp->getParentOp());
748  reshapedSource = rewriter.create<tensor::CollapseShapeOp>(
749  loc, insertSliceOp.getSource(), *reassociation);
750  }
751  rewriter.replaceOpWithNewOp<InsertOpTy>(
752  insertSliceOp, reshapedSource, insertSliceOp.getDest(),
753  insertSliceOp.getMixedOffsets(), insertSliceOp.getMixedSizes(),
754  insertSliceOp.getMixedStrides());
755  return success();
756  }
757 };
758 } // namespace
759 
760 /// Patterns that are used to canonicalize the use of unit-extent dims for
761 /// broadcasting.
762 static void
765  auto *context = patterns.getContext();
766  patterns.add<DropUnitDims>(context, options);
767  patterns.add<DropPadUnitDims>(context, options);
768  // TODO: Patterns unrelated to unit dim folding should be factored out.
769  patterns.add<RankReducedExtractSliceOp,
770  RankReducedInsertSliceOp<tensor::InsertSliceOp>,
771  RankReducedInsertSliceOp<tensor::ParallelInsertSliceOp>>(
772  context);
773  linalg::FillOp::getCanonicalizationPatterns(patterns, context);
774  tensor::CollapseShapeOp::getCanonicalizationPatterns(patterns, context);
775  tensor::EmptyOp::getCanonicalizationPatterns(patterns, context);
776  tensor::ExpandShapeOp::getCanonicalizationPatterns(patterns, context);
780 }
781 
782 static void
785  auto *context = patterns.getContext();
786  options.rankReductionStrategy =
788  patterns.add<DropUnitDims>(context, options);
789  patterns.add<DropPadUnitDims>(context, options);
790  // TODO: Patterns unrelated to unit dim folding should be factored out.
791  linalg::FillOp::getCanonicalizationPatterns(patterns, context);
792  tensor::EmptyOp::getCanonicalizationPatterns(patterns, context);
796 }
797 
800  if (options.rankReductionStrategy ==
803  } else if (options.rankReductionStrategy ==
805  ReassociativeReshape) {
807  }
808 }
809 
811  RewritePatternSet &patterns) {
812  patterns.add<MoveInitOperandsToInput>(patterns.getContext());
813 }
814 
815 namespace {
816 /// Pass that removes unit-extent dims within generic ops.
817 struct LinalgFoldUnitExtentDimsPass
818  : public impl::LinalgFoldUnitExtentDimsPassBase<
819  LinalgFoldUnitExtentDimsPass> {
820  using impl::LinalgFoldUnitExtentDimsPassBase<
821  LinalgFoldUnitExtentDimsPass>::LinalgFoldUnitExtentDimsPassBase;
822  void runOnOperation() override {
823  Operation *op = getOperation();
824  MLIRContext *context = op->getContext();
825  RewritePatternSet patterns(context);
827  if (useRankReducingSlices) {
828  options.rankReductionStrategy = linalg::ControlDropUnitDims::
830  }
833  (void)applyPatternsAndFoldGreedily(op, std::move(patterns));
834  }
835 };
836 
837 } // namespace
838 
839 namespace {
840 
841 /// Returns reassociation indices for collapsing/expanding a
842 /// tensor of rank `rank` at position `pos`.
844 getReassociationForReshapeAtDim(int64_t rank, int64_t pos) {
845  SmallVector<ReassociationIndices> reassociation(rank - 1, {0, 1});
846  bool lastDim = pos == rank - 1;
847  if (rank > 2) {
848  for (int64_t i = 0; i < rank - 1; i++) {
849  if (i == pos || (lastDim && i == pos - 1))
850  reassociation[i] = ReassociationIndices{i, i + 1};
851  else if (i < pos)
852  reassociation[i] = ReassociationIndices{i};
853  else
854  reassociation[i] = ReassociationIndices{i + 1};
855  }
856  }
857  return reassociation;
858 }
859 
860 /// Returns a collapsed `val` where the collapsing occurs at dim `pos`.
861 /// If `pos < 0`, then don't collapse.
862 static Value collapseSingletonDimAt(PatternRewriter &rewriter, Value val,
863  int64_t pos) {
864  if (pos < 0)
865  return val;
866  auto valType = cast<ShapedType>(val.getType());
867  SmallVector<int64_t> collapsedShape(valType.getShape());
868  collapsedShape.erase(collapsedShape.begin() + pos);
869  return collapseValue(
870  rewriter, val.getLoc(), val, collapsedShape,
871  getReassociationForReshapeAtDim(valType.getRank(), pos),
873 }
874 
875 /// Base class for all rank reduction patterns for contraction ops
876 /// with unit dimensions. All patterns should convert one named op
877 /// to another named op. Intended to reduce only one iteration space dim
878 /// at a time.
879 /// Reducing multiple dims will happen with recusive application of
880 /// pattern rewrites.
881 template <typename FromOpTy, typename ToOpTy>
882 struct RankReduceContractionOps : OpRewritePattern<FromOpTy> {
884 
885  /// Collapse all collapsable operands.
887  collapseOperands(PatternRewriter &rewriter, ArrayRef<Value> operands,
888  ArrayRef<int64_t> operandCollapseDims) const {
889  assert(operandCollapseDims.size() == 3 && operands.size() == 3 &&
890  "expected 3 operands and dims");
891  return llvm::map_to_vector(
892  llvm::zip(operands, operandCollapseDims), [&](auto pair) {
893  return collapseSingletonDimAt(rewriter, std::get<0>(pair),
894  std::get<1>(pair));
895  });
896  }
897 
898  /// Expand result tensor.
899  Value expandResult(PatternRewriter &rewriter, Value result,
900  RankedTensorType expandedType, int64_t dim) const {
901  return rewriter.create<tensor::ExpandShapeOp>(
902  result.getLoc(), expandedType, result,
903  getReassociationForReshapeAtDim(expandedType.getRank(), dim));
904  }
905 
906  LogicalResult matchAndRewrite(FromOpTy contractionOp,
907  PatternRewriter &rewriter) const override {
908 
909  auto loc = contractionOp.getLoc();
910  auto inputs = contractionOp.getDpsInputs();
911  auto inits = contractionOp.getDpsInits();
912  if (inputs.size() != 2 || inits.size() != 1)
913  return rewriter.notifyMatchFailure(contractionOp,
914  "expected 2 inputs and 1 init");
915  auto lhs = inputs[0];
916  auto rhs = inputs[1];
917  auto init = inits[0];
918  SmallVector<Value> operands{lhs, rhs, init};
919 
920  SmallVector<int64_t> operandUnitDims;
921  if (failed(getOperandUnitDims(contractionOp, operandUnitDims)))
922  return rewriter.notifyMatchFailure(contractionOp,
923  "no reducable dims found");
924 
925  SmallVector<Value> collapsedOperands =
926  collapseOperands(rewriter, operands, operandUnitDims);
927  Value collapsedLhs = collapsedOperands[0];
928  Value collapsedRhs = collapsedOperands[1];
929  Value collapsedInit = collapsedOperands[2];
930  SmallVector<Type, 1> collapsedResultTy;
931  if (isa<RankedTensorType>(collapsedInit.getType()))
932  collapsedResultTy.push_back(collapsedInit.getType());
933  auto collapsedOp = rewriter.create<ToOpTy>(
934  loc, collapsedResultTy, ValueRange{collapsedLhs, collapsedRhs},
935  ValueRange{collapsedInit});
936  for (auto attr : contractionOp->getAttrs()) {
937  if (attr.getName() == LinalgDialect::kMemoizedIndexingMapsAttrName)
938  continue;
939  collapsedOp->setAttr(attr.getName(), attr.getValue());
940  }
941 
942  auto results = contractionOp.getResults();
943  assert(results.size() < 2 && "expected at most one result");
944  if (results.empty()) {
945  rewriter.replaceOp(contractionOp, collapsedOp);
946  } else {
947  rewriter.replaceOp(
948  contractionOp,
949  expandResult(rewriter, collapsedOp.getResultTensors()[0],
950  cast<RankedTensorType>(results[0].getType()),
951  operandUnitDims[2]));
952  }
953 
954  return success();
955  }
956 
957  /// Populate `operandUnitDims` with 3 indices indicating the unit dim
958  /// for each operand that should be collapsed in this pattern. If an
959  /// operand shouldn't be collapsed, the index should be negative.
960  virtual LogicalResult
961  getOperandUnitDims(LinalgOp op,
962  SmallVectorImpl<int64_t> &operandUnitDims) const = 0;
963 };
964 
965 /// Patterns for unbatching batched contraction ops
966 template <typename FromOpTy, typename ToOpTy>
967 struct RankReduceToUnBatched : RankReduceContractionOps<FromOpTy, ToOpTy> {
968  using RankReduceContractionOps<FromOpTy, ToOpTy>::RankReduceContractionOps;
969 
970  /// Look for unit batch dims to collapse.
971  LogicalResult
972  getOperandUnitDims(LinalgOp op,
973  SmallVectorImpl<int64_t> &operandUnitDims) const override {
974  FailureOr<ContractionDimensions> maybeContractionDims =
976  if (failed(maybeContractionDims)) {
977  LLVM_DEBUG(llvm::dbgs() << "could not infer contraction dims");
978  return failure();
979  }
980  ContractionDimensions contractionDims = maybeContractionDims.value();
981 
982  if (contractionDims.batch.size() != 1)
983  return failure();
984  auto batchDim = contractionDims.batch[0];
986  op.mapIterationSpaceDimToAllOperandDims(batchDim, bOperands);
987  if (bOperands.size() != 3 || llvm::any_of(bOperands, [](auto pair) {
988  return cast<ShapedType>(std::get<0>(pair).getType())
989  .getShape()[std::get<1>(pair)] != 1;
990  })) {
991  LLVM_DEBUG(llvm::dbgs() << "specified unit dims not found");
992  return failure();
993  }
994 
995  operandUnitDims = SmallVector<int64_t>{std::get<1>(bOperands[0]),
996  std::get<1>(bOperands[1]),
997  std::get<1>(bOperands[2])};
998  return success();
999  }
1000 };
1001 
1002 /// Patterns for reducing non-batch dimensions
1003 template <typename FromOpTy, typename ToOpTy>
1004 struct RankReduceMatmul : RankReduceContractionOps<FromOpTy, ToOpTy> {
1005  using RankReduceContractionOps<FromOpTy, ToOpTy>::RankReduceContractionOps;
1006 
1007  /// Helper for determining whether the lhs/init or rhs/init are reduced.
1008  static bool constexpr reduceLeft =
1009  (std::is_same_v<FromOpTy, BatchMatmulOp> &&
1010  std::is_same_v<ToOpTy, BatchVecmatOp>) ||
1011  (std::is_same_v<FromOpTy, BatchMatmulTransposeAOp> &&
1012  std::is_same_v<ToOpTy, BatchVecmatOp>) ||
1013  (std::is_same_v<FromOpTy, MatmulOp> &&
1014  std::is_same_v<ToOpTy, VecmatOp>) ||
1015  (std::is_same_v<FromOpTy, MatmulTransposeAOp> &&
1016  std::is_same_v<ToOpTy, VecmatOp>) ||
1017  (std::is_same_v<FromOpTy, MatvecOp> && std::is_same_v<ToOpTy, DotOp>);
1018 
1019  /// Look for non-batch spatial dims to collapse.
1020  LogicalResult
1021  getOperandUnitDims(LinalgOp op,
1022  SmallVectorImpl<int64_t> &operandUnitDims) const override {
1023  FailureOr<ContractionDimensions> maybeContractionDims =
1025  if (failed(maybeContractionDims)) {
1026  LLVM_DEBUG(llvm::dbgs() << "could not infer contraction dims");
1027  return failure();
1028  }
1029  ContractionDimensions contractionDims = maybeContractionDims.value();
1030 
1031  if constexpr (reduceLeft) {
1032  auto m = contractionDims.m[0];
1034  op.mapIterationSpaceDimToAllOperandDims(m, mOperands);
1035  if (mOperands.size() != 2)
1036  return failure();
1037  if (llvm::all_of(mOperands, [](auto pair) {
1038  return cast<ShapedType>(std::get<0>(pair).getType())
1039  .getShape()[std::get<1>(pair)] == 1;
1040  })) {
1041  operandUnitDims = SmallVector<int64_t>{std::get<1>(mOperands[0]), -1,
1042  std::get<1>(mOperands[1])};
1043  return success();
1044  }
1045  } else {
1046  auto n = contractionDims.n[0];
1048  op.mapIterationSpaceDimToAllOperandDims(n, nOperands);
1049  if (nOperands.size() != 2)
1050  return failure();
1051  if (llvm::all_of(nOperands, [](auto pair) {
1052  return cast<ShapedType>(std::get<0>(pair).getType())
1053  .getShape()[std::get<1>(pair)] == 1;
1054  })) {
1055  operandUnitDims = SmallVector<int64_t>{-1, std::get<1>(nOperands[0]),
1056  std::get<1>(nOperands[1])};
1057  return success();
1058  }
1059  }
1060  LLVM_DEBUG(llvm::dbgs() << "specified unit dims not found");
1061  return failure();
1062  }
1063 };
1064 
1065 } // namespace
1066 
1068  RewritePatternSet &patterns) {
1069  MLIRContext *context = patterns.getContext();
1070  // Unbatching patterns for unit batch size
1071  patterns.add<RankReduceToUnBatched<BatchMatmulOp, MatmulOp>>(context);
1072  patterns
1073  .add<RankReduceToUnBatched<BatchMatmulTransposeAOp, MatmulTransposeAOp>>(
1074  context);
1075  patterns
1076  .add<RankReduceToUnBatched<BatchMatmulTransposeBOp, MatmulTransposeBOp>>(
1077  context);
1078  patterns.add<RankReduceToUnBatched<BatchMatvecOp, MatvecOp>>(context);
1079  patterns.add<RankReduceToUnBatched<BatchVecmatOp, VecmatOp>>(context);
1080 
1081  // Non-batch rank 1 reducing patterns
1082  patterns.add<RankReduceMatmul<MatmulOp, VecmatOp>>(context);
1083  patterns.add<RankReduceMatmul<MatmulOp, MatvecOp>>(context);
1084  patterns.add<RankReduceMatmul<MatmulTransposeAOp, VecmatOp>>(context);
1085  patterns.add<RankReduceMatmul<MatmulTransposeBOp, MatvecOp>>(context);
1086  // Batch rank 1 reducing patterns
1087  patterns.add<RankReduceMatmul<BatchMatmulOp, BatchVecmatOp>>(context);
1088  patterns.add<RankReduceMatmul<BatchMatmulOp, BatchMatvecOp>>(context);
1089  patterns.add<RankReduceMatmul<BatchMatmulTransposeAOp, BatchVecmatOp>>(
1090  context);
1091  patterns.add<RankReduceMatmul<BatchMatmulTransposeBOp, BatchMatvecOp>>(
1092  context);
1093 
1094  // Non-batch rank 0 reducing patterns
1095  patterns.add<RankReduceMatmul<MatvecOp, DotOp>>(context);
1096  patterns.add<RankReduceMatmul<VecmatOp, DotOp>>(context);
1097 }
static Value expandValue(RewriterBase &rewriter, Location loc, Value result, Value origDest, ArrayRef< ReassociationIndices > reassociation, ControlDropUnitDims::RankReductionStrategy rankReductionStrategy)
Expand the given value so that the type matches the type of origDest.
static void replaceUnitDimIndexOps(GenericOp genericOp, const llvm::SmallDenseSet< unsigned > &unitDims, RewriterBase &rewriter)
Implements a pass that canonicalizes the uses of unit-extent dimensions for broadcasting.
static UnitExtentReplacementInfo dropUnitExtentFromOperandMetadata(MLIRContext *context, GenericOp genericOp, OpOperand *opOperand, llvm::SmallDenseMap< unsigned, unsigned > &oldDimsToNewDimsMap, ArrayRef< AffineExpr > dimReplacements)
static void populateFoldUnitExtentDimsViaReshapesPatterns(RewritePatternSet &patterns, ControlDropUnitDims &options)
Patterns that are used to canonicalize the use of unit-extent dims for broadcasting.
static void populateFoldUnitExtentDimsViaSlicesPatterns(RewritePatternSet &patterns, ControlDropUnitDims &options)
static Value collapseValue(RewriterBase &rewriter, Location loc, Value operand, ArrayRef< int64_t > targetShape, ArrayRef< ReassociationIndices > reassociation, ControlDropUnitDims::RankReductionStrategy rankReductionStrategy)
Collapse the given value so that the type matches the type of origOutput.
static llvm::ManagedStatic< PassManagerOptions > options
A dimensional identifier appearing in an affine expression.
Definition: AffineExpr.h:236
Base type for affine expression.
Definition: AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition: AffineMap.h:46
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
unsigned getNumSymbols() const
Definition: AffineMap.cpp:398
ArrayRef< AffineExpr > getResults() const
Definition: AffineMap.cpp:407
AffineMap replaceDimsAndSymbols(ArrayRef< AffineExpr > dimReplacements, ArrayRef< AffineExpr > symReplacements, unsigned numResultDims, unsigned numResultSyms) const
This method substitutes any uses of dimensions and symbols (e.g.
Definition: AffineMap.cpp:500
This class represents an argument of a Block.
Definition: Value.h:319
Block represents an ordered list of Operations.
Definition: Block.h:31
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition: Block.cpp:152
IntegerAttr getIndexAttr(int64_t value)
Definition: Builders.cpp:128
MLIRContext * getContext() const
Definition: Builders.h:55
This is a utility class for mapping one set of IR entities to another.
Definition: IRMapping.h:26
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition: IRMapping.h:30
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:63
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:351
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition: Builders.cpp:559
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:401
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes=std::nullopt, ArrayRef< Location > locs=std::nullopt)
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition: Builders.cpp:441
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition: Builders.h:523
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Definition: Builders.h:424
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:468
This class represents a single result from folding an operation.
Definition: OpDefinition.h:268
This class represents an operand of an operation.
Definition: Value.h:267
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
MLIRContext * getContext()
Return the context this operation is associated with.
Definition: Operation.h:216
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
void setAttr(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
Definition: Operation.h:577
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
Definition: PatternMatch.h:34
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:785
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
MLIRContext * getContext() const
Definition: PatternMatch.h:823
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
Definition: PatternMatch.h:847
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:400
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
Definition: PatternMatch.h:718
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
void inlineRegionBefore(Region &region, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Definition: PatternMatch.h:536
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:381
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Type getType() const
Return the type of this value.
Definition: Value.h:129
Location getLoc() const
Return the location of this value.
Definition: Value.cpp:26
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:285
void populateMoveInitOperandsToInputPattern(RewritePatternSet &patterns)
A pattern that converts init operands to input operands.
void populateContractionOpRankReducingPatterns(RewritePatternSet &patterns)
Adds patterns that reduce the rank of named contraction ops that have unit dimensions in the operand(...
SmallVector< NamedAttribute > getPrunedAttributeList(OpTy op)
Returns an attribute list that excludes pre-defined attributes.
Definition: Utils.h:369
std::optional< SmallVector< ReassociationIndices > > getReassociationMapForFoldingUnitDims(ArrayRef< OpFoldResult > mixedSizes)
Get the reassociation maps to fold the result of a extract_slice (or source of a insert_slice) operat...
Definition: Utils.cpp:886
void populateFoldUnitExtentDimsPatterns(RewritePatternSet &patterns, ControlDropUnitDims &options)
Patterns to fold unit-extent dimensions in operands/results of linalg ops on tensors via reassociativ...
FailureOr< ContractionDimensions > inferContractionDims(LinalgOp linalgOp)
Find at least 2 parallel (m and n) and 1 reduction (k) dimension candidates that form a matmul subcom...
LogicalResult dropUnitDims(RewriterBase &rewriter, GenericOp genericOp, const ControlDropUnitDims &options)
void populateResolveRankedShapedTypeResultDimsPatterns(RewritePatternSet &patterns)
Appends patterns that resolve memref.dim operations with values that are defined by operations that i...
void populateResolveShapedTypeResultDimsPatterns(RewritePatternSet &patterns)
Appends patterns that resolve memref.dim operations with values that are defined by operations that i...
void populateFoldTensorEmptyPatterns(RewritePatternSet &patterns, bool foldSingleUseOnly=false)
Populates patterns with patterns that fold tensor.empty with its consumers.
OpFoldResult getMixedSize(OpBuilder &builder, Location loc, Value value, int64_t dim)
Return the dimension of the given tensor value.
Definition: TensorOps.cpp:55
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
Definition: TensorOps.cpp:65
Include the generated interface declarations.
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition: Utils.cpp:305
AffineMap inversePermutation(AffineMap map)
Returns a map of codomain to domain dimensions such that the first codomain dimension for a particula...
Definition: AffineMap.cpp:768
AffineMap concatAffineMaps(ArrayRef< AffineMap > maps)
Concatenates a list of maps into a single AffineMap, stepping over potentially empty maps.
Definition: AffineMap.cpp:813
LogicalResult applyPatternsAndFoldGreedily(Region &region, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context)
Definition: AffineExpr.cpp:631
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
Definition: AffineExpr.cpp:607
Compute the modified metadata for an operands of operation whose unit dims are being dropped.
SmallVector< ReassociationIndices > reassociation
SmallVector< int64_t > targetShape
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
Definition: PatternMatch.h:358
Positions of a Linalg op loops that correspond to different kinds of a contraction dimension.
SmallVector< unsigned, 2 > batch
SmallVector< unsigned, 2 > m
SmallVector< unsigned, 2 > n
Transformation to drop unit-extent dimensions from linalg.generic operations.
Definition: Transforms.h:473