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 /// indexing_maps = #accesses,
182 /// iterator_types = ["parallel", "parallel"],
183 /// library_call = "some_external_fn"
184 /// }
185 ///
186 /// func @broadcast_test(%arg0 : tensor<5xf32>, %arg1 : tensor<5xf32>) ->
187 /// tensor<5x5xf32>
188 /// {
189 /// %0 = linalg.tensor_reshape %arg0 [affine_map<(d0, d1) -> (d0, d1)>] :
190 /// tensor<5xf32> into tensor<1x5xf32>
191 /// %1 = linalg.tensor_reshape %arg1 [affine_map<(d0, d1) -> (d0, d1)>] :
192 /// tensor<5xf32> into tensor<5x1xf32>
193 /// %2 = linalg.generic #trait %0, %1 {
194 /// ^bb0(%arg2: f32, %arg3: f32):
195 /// %3 = arith.addf %arg2, %arg3 : f32
196 /// linalg.yield %3 : f32
197 /// } : tensor<1x5xf32>, tensor<5x1xf32> -> tensor<5x5xf32>
198 /// return %2 : tensor<5x5xf32>
199 /// }
200 ///
201 /// would canonicalize to
202 ///
203 /// ```mlir
204 /// #accesses = [
205 /// affine_map<(d0, d1) -> (d1)>,
206 /// affine_map<(d0, d1) -> (d0)>,
207 /// affine_map<(d0, d1) -> (d0, d1)>
208 /// ]
209 ///
210 /// #trait = {
211 /// indexing_maps = #accesses,
212 /// iterator_types = ["parallel", "parallel"],
213 /// library_call = "some_external_fn"
214 /// }
215 ///
216 /// func @broadcast_test(%arg0 : tensor<5xf32>, %arg1 : tensor<5xf32>) ->
217 /// tensor<5x5xf32>
218 /// {
219 /// %0 = linalg.generic #trait %arg0, %arg1 {
220 /// ^bb0(%arg2: f32, %arg3: f32):
221 /// %3 = arith.addf %arg2, %arg3 : f32
222 /// linalg.yield %3 : f32
223 /// } : tensor<5xf32>, tensor<5xf32> -> tensor<5x5xf32>
224 /// return %0 : tensor<5x5xf32>
225 /// }
226 
227 /// Update the index accesses of linalg operations having index semantics.
228 static void
229 replaceUnitDimIndexOps(GenericOp genericOp,
230  const llvm::SmallDenseSet<unsigned> &unitDims,
231  RewriterBase &rewriter) {
232  for (IndexOp indexOp :
233  llvm::make_early_inc_range(genericOp.getBody()->getOps<IndexOp>())) {
234  OpBuilder::InsertionGuard guard(rewriter);
235  rewriter.setInsertionPoint(indexOp);
236  if (unitDims.count(indexOp.getDim()) != 0) {
237  rewriter.replaceOpWithNewOp<arith::ConstantIndexOp>(indexOp, 0);
238  } else {
239  // Update the dimension of the index operation if needed.
240  unsigned droppedDims = llvm::count_if(
241  unitDims, [&](unsigned dim) { return dim < indexOp.getDim(); });
242  if (droppedDims != 0)
243  rewriter.replaceOpWithNewOp<IndexOp>(indexOp,
244  indexOp.getDim() - droppedDims);
245  }
246  }
247 }
248 
249 /// Expand the given `value` so that the type matches the type of `origDest`.
250 /// The `reassociation` is used when `rankReductionStrategy` is set to
251 /// `RankReductionStrategy::ReassociativeReshape`.
252 static Value
253 expandValue(RewriterBase &rewriter, Location loc, Value result, Value origDest,
254  ArrayRef<ReassociationIndices> reassociation,
255  ControlDropUnitDims::RankReductionStrategy rankReductionStrategy) {
256  // There are no results for memref outputs.
257  auto origResultType = cast<RankedTensorType>(origDest.getType());
258  if (rankReductionStrategy ==
260  unsigned rank = origResultType.getRank();
261  SmallVector<OpFoldResult> offsets(rank, rewriter.getIndexAttr(0));
263  tensor::getMixedSizes(rewriter, loc, origDest);
264  SmallVector<OpFoldResult> strides(rank, rewriter.getIndexAttr(1));
265  return rewriter.createOrFold<tensor::InsertSliceOp>(
266  loc, result, origDest, offsets, sizes, strides);
267  }
268 
269  assert(rankReductionStrategy ==
271  "unknown rank reduction strategy");
272  return rewriter
273  .create<tensor::ExpandShapeOp>(loc, origResultType, result, reassociation)
274  .getResult();
275 }
276 
277 /// Collapse the given `value` so that the type matches the type of
278 /// `origOutput`. The `reassociation` is used when `rankReductionStrategy` is
279 /// set to `RankReductionStrategy::ReassociativeReshape`.
281  RewriterBase &rewriter, Location loc, Value operand,
282  ArrayRef<int64_t> targetShape, ArrayRef<ReassociationIndices> reassociation,
283  ControlDropUnitDims::RankReductionStrategy rankReductionStrategy) {
284  if (auto memrefType = dyn_cast<MemRefType>(operand.getType())) {
285  if (rankReductionStrategy ==
287  FailureOr<Value> rankReducingExtract =
288  memref::SubViewOp::rankReduceIfNeeded(rewriter, loc, operand,
289  targetShape);
290  assert(succeeded(rankReducingExtract) && "not a unit-extent collapse");
291  return *rankReducingExtract;
292  }
293 
294  assert(
295  rankReductionStrategy ==
297  "unknown rank reduction strategy");
298  MemRefLayoutAttrInterface layout;
299  auto targetType = MemRefType::get(targetShape, memrefType.getElementType(),
300  layout, memrefType.getMemorySpace());
301  return rewriter.create<memref::CollapseShapeOp>(loc, targetType, operand,
302  reassociation);
303  }
304  if (auto tensorType = dyn_cast<RankedTensorType>(operand.getType())) {
305  if (rankReductionStrategy ==
307  FailureOr<Value> rankReducingExtract =
308  tensor::ExtractSliceOp::rankReduceIfNeeded(rewriter, loc, operand,
309  targetShape);
310  assert(succeeded(rankReducingExtract) && "not a unit-extent collapse");
311  return *rankReducingExtract;
312  }
313 
314  assert(
315  rankReductionStrategy ==
317  "unknown rank reduction strategy");
318  auto targetType =
319  RankedTensorType::get(targetShape, tensorType.getElementType());
320  return rewriter.create<tensor::CollapseShapeOp>(loc, targetType, operand,
321  reassociation);
322  }
323  llvm_unreachable("unsupported operand type");
324 }
325 
326 /// Compute the modified metadata for an operands of operation
327 /// whose unit dims are being dropped. Return the new indexing map
328 /// to use, the shape of the operand in the replacement op
329 /// and the `reassocation` to use to go from original operand shape
330 /// to modified operand shape.
335 };
337  MLIRContext *context, GenericOp genericOp, OpOperand *opOperand,
338  llvm::SmallDenseMap<unsigned, unsigned> &oldDimsToNewDimsMap,
339  ArrayRef<AffineExpr> dimReplacements) {
341  ReassociationIndices reassociationGroup;
342  SmallVector<AffineExpr> newIndexExprs;
343  AffineMap indexingMap = genericOp.getMatchingIndexingMap(opOperand);
344  ArrayRef<int64_t> operandShape = genericOp.getShape(opOperand);
345  ArrayRef<AffineExpr> exprs = indexingMap.getResults();
346 
347  auto isUnitDim = [&](unsigned dim) {
348  if (auto dimExpr = dyn_cast<AffineDimExpr>(exprs[dim])) {
349  unsigned oldPosition = dimExpr.getPosition();
350  return !oldDimsToNewDimsMap.count(oldPosition) &&
351  (operandShape[dim] == 1);
352  }
353  // Handle the other case where the shape is 1, and is accessed using a
354  // constant 0.
355  if (operandShape[dim] == 1) {
356  auto constAffineExpr = dyn_cast<AffineConstantExpr>(exprs[dim]);
357  return constAffineExpr && constAffineExpr.getValue() == 0;
358  }
359  return false;
360  };
361 
362  unsigned dim = 0;
363  while (dim < operandShape.size() && isUnitDim(dim))
364  reassociationGroup.push_back(dim++);
365  while (dim < operandShape.size()) {
366  assert(!isUnitDim(dim) && "expected non unit-extent");
367  reassociationGroup.push_back(dim);
368  AffineExpr newExpr = exprs[dim].replaceDims(dimReplacements);
369  newIndexExprs.push_back(newExpr);
370  info.targetShape.push_back(operandShape[dim]);
371  ++dim;
372  // Fold all following dimensions that are unit-extent.
373  while (dim < operandShape.size() && isUnitDim(dim)) {
374  reassociationGroup.push_back(dim++);
375  }
376  info.reassociation.push_back(reassociationGroup);
377  reassociationGroup.clear();
378  }
379  info.indexMap =
380  AffineMap::get(oldDimsToNewDimsMap.size(), indexingMap.getNumSymbols(),
381  newIndexExprs, context);
382  return info;
383 }
384 
385 FailureOr<DropUnitDimsResult>
386 linalg::dropUnitDims(RewriterBase &rewriter, GenericOp genericOp,
387  const ControlDropUnitDims &options) {
388  SmallVector<AffineMap> indexingMaps = genericOp.getIndexingMapsArray();
389  if (indexingMaps.empty())
390  return failure();
391 
392  // 1. Check if any of the iteration dimensions are unit-trip count. They will
393  // end up being unit-trip count if they are used to index into a unit-dim
394  // tensor/memref.
395  AffineMap invertedMap = inversePermutation(concatAffineMaps(indexingMaps));
396  if (!invertedMap) {
397  return rewriter.notifyMatchFailure(genericOp,
398  "invalid indexing maps for operation");
399  }
400  SmallVector<int64_t> dims = genericOp.getStaticShape();
401 
402  // 1a. Get the allowed list of dimensions to drop from the `options`.
403  SmallVector<unsigned> allowedUnitDims = options.controlFn(genericOp);
404  if (allowedUnitDims.empty()) {
405  return rewriter.notifyMatchFailure(
406  genericOp, "control function returns no allowed unit dims to prune");
407  }
408  llvm::SmallDenseSet<unsigned> unitDimsFilter(allowedUnitDims.begin(),
409  allowedUnitDims.end());
410  llvm::SmallDenseSet<unsigned> unitDims;
411  for (const auto &expr : enumerate(invertedMap.getResults())) {
412  if (AffineDimExpr dimExpr = dyn_cast<AffineDimExpr>(expr.value())) {
413  if (dims[dimExpr.getPosition()] == 1 &&
414  unitDimsFilter.count(expr.index()))
415  unitDims.insert(expr.index());
416  }
417  }
418 
419  // 2. Compute the iterator types of the modified op by dropping the one-trip
420  // count loops.
421  SmallVector<utils::IteratorType> newIteratorTypes;
422  llvm::SmallDenseMap<unsigned, unsigned> oldDimToNewDimMap;
423  SmallVector<AffineExpr> dimReplacements;
424  unsigned newDims = 0;
425  for (auto [index, attr] :
426  llvm::enumerate(genericOp.getIteratorTypesArray())) {
427  if (unitDims.count(index)) {
428  dimReplacements.push_back(
429  getAffineConstantExpr(0, rewriter.getContext()));
430  } else {
431  newIteratorTypes.push_back(attr);
432  oldDimToNewDimMap[index] = newDims;
433  dimReplacements.push_back(
434  getAffineDimExpr(newDims, rewriter.getContext()));
435  newDims++;
436  }
437  }
438 
439  // 3. For each of the operands, find the
440  // - modified affine map to use.
441  // - shape of the operands after the unit-dims are dropped.
442  // - the reassociation indices used to convert from the original
443  // operand type to modified operand (needed only when using reshapes
444  // for rank reduction strategy)
445  // Note that the indexing maps might need changing even if there are no
446  // unit dimensions that are dropped to handle cases where `0` is used to
447  // access a unit-extent tensor. Consider moving this out of this specific
448  // transformation as a stand-alone transformation. Kept here right now due
449  // to legacy.
450  SmallVector<AffineMap> newIndexingMaps;
452  SmallVector<SmallVector<int64_t>> targetShapes;
453  SmallVector<bool> collapsed;
454  auto hasCollapsibleType = [](OpOperand &operand) {
455  Type operandType = operand.get().getType();
456  if (auto memrefOperandType = dyn_cast_or_null<MemRefType>(operandType)) {
457  return memrefOperandType.getLayout().isIdentity();
458  }
459  if (auto tensorOperandType = dyn_cast<RankedTensorType>(operandType)) {
460  return tensorOperandType.getEncoding() == nullptr;
461  }
462  return false;
463  };
464  for (OpOperand &opOperand : genericOp->getOpOperands()) {
465  auto indexingMap = genericOp.getMatchingIndexingMap(&opOperand);
466  ArrayRef<int64_t> shape = genericOp.getShape(&opOperand);
467  if (!hasCollapsibleType(opOperand)) {
468  AffineMap newIndexingMap = indexingMap.replaceDimsAndSymbols(
469  dimReplacements, ArrayRef<AffineExpr>{}, oldDimToNewDimMap.size(), 0);
470  newIndexingMaps.push_back(newIndexingMap);
471  targetShapes.push_back(llvm::to_vector(shape));
472  collapsed.push_back(false);
473  reassociations.push_back({});
474  continue;
475  }
476  auto replacementInfo = dropUnitExtentFromOperandMetadata(
477  rewriter.getContext(), genericOp, &opOperand, oldDimToNewDimMap,
478  dimReplacements);
479  reassociations.push_back(replacementInfo.reassociation);
480  newIndexingMaps.push_back(replacementInfo.indexMap);
481  targetShapes.push_back(replacementInfo.targetShape);
482  collapsed.push_back(!(replacementInfo.indexMap.getNumResults() ==
483  indexingMap.getNumResults()));
484  }
485 
486  // Abort if the indexing maps of the result operation are not invertible
487  // (i.e. not legal) or if no dimension was reduced.
488  if (newIndexingMaps == indexingMaps ||
489  !inversePermutation(concatAffineMaps(newIndexingMaps)))
490  return failure();
491 
492  Location loc = genericOp.getLoc();
493  // 4. For each of the operands, collapse the operand to convert
494  // from original shape to shape in the modified operation if needed,
495  // either through use of reshapes or rank-reducing slices as
496  // specified in `options`.
497  SmallVector<Value> newOperands;
498  for (OpOperand &opOperand : genericOp->getOpOperands()) {
499  int64_t idx = opOperand.getOperandNumber();
500  if (!collapsed[idx]) {
501  newOperands.push_back(opOperand.get());
502  continue;
503  }
504  newOperands.push_back(collapseValue(rewriter, loc, opOperand.get(),
505  targetShapes[idx], reassociations[idx],
506  options.rankReductionStrategy));
507  }
508 
509  // 5. Create the `linalg.generic` operation with the new operands,
510  // indexing maps, iterator types and result types.
511  ArrayRef<Value> newInputs =
512  ArrayRef<Value>(newOperands).take_front(genericOp.getNumDpsInputs());
513  ArrayRef<Value> newOutputs =
514  ArrayRef<Value>(newOperands).take_back(genericOp.getNumDpsInits());
515  SmallVector<Type> resultTypes;
516  resultTypes.reserve(genericOp.getNumResults());
517  for (unsigned i : llvm::seq<unsigned>(0, genericOp.getNumResults()))
518  resultTypes.push_back(newOutputs[i].getType());
519  GenericOp replacementOp =
520  rewriter.create<GenericOp>(loc, resultTypes, newInputs, newOutputs,
521  newIndexingMaps, newIteratorTypes);
522  rewriter.inlineRegionBefore(genericOp.getRegion(), replacementOp.getRegion(),
523  replacementOp.getRegion().begin());
524  // 5a. Replace `linalg.index` operations that refer to the dropped unit
525  // dimensions.
526  replaceUnitDimIndexOps(replacementOp, unitDims, rewriter);
527 
528  // 6. If any result type changes, insert a reshape/slice to convert from the
529  // original type to the new type.
530  SmallVector<Value> resultReplacements;
531  for (auto [index, result] : llvm::enumerate(replacementOp.getResults())) {
532  unsigned opOperandIndex = index + replacementOp.getNumDpsInputs();
533  Value origDest = genericOp.getDpsInitOperand(index)->get();
534  if (!collapsed[opOperandIndex]) {
535  resultReplacements.push_back(result);
536  continue;
537  }
538  Value expandedValue = expandValue(rewriter, loc, result, origDest,
539  reassociations[opOperandIndex],
540  options.rankReductionStrategy);
541  resultReplacements.push_back(expandedValue);
542  }
543 
544  return DropUnitDimsResult{replacementOp, resultReplacements};
545 }
546 
547 namespace {
548 struct DropUnitDims : public OpRewritePattern<GenericOp> {
549  DropUnitDims(MLIRContext *context, ControlDropUnitDims options = {},
550  PatternBenefit benefit = 1)
551  : OpRewritePattern(context, benefit), options(std::move(options)) {}
552 
553  LogicalResult matchAndRewrite(GenericOp genericOp,
554  PatternRewriter &rewriter) const override {
555  FailureOr<DropUnitDimsResult> result =
556  dropUnitDims(rewriter, genericOp, options);
557  if (failed(result)) {
558  return failure();
559  }
560  rewriter.replaceOp(genericOp, result->replacements);
561  return success();
562  }
563 
564 private:
566 };
567 } // namespace
568 
569 //===---------------------------------------------------------------------===//
570 // Drop dimensions that are unit-extents within tensor operations.
571 //===---------------------------------------------------------------------===//
572 
573 namespace {
574 struct DropPadUnitDims : public OpRewritePattern<tensor::PadOp> {
575  DropPadUnitDims(MLIRContext *context, ControlDropUnitDims options = {},
576  PatternBenefit benefit = 1)
577  : OpRewritePattern(context, benefit), options(std::move(options)) {}
578 
579  LogicalResult matchAndRewrite(tensor::PadOp padOp,
580  PatternRewriter &rewriter) const override {
581  // 1a. Get the allowed list of dimensions to drop from the `options`.
582  SmallVector<unsigned> allowedUnitDims = options.controlFn(padOp);
583  if (allowedUnitDims.empty()) {
584  return rewriter.notifyMatchFailure(
585  padOp, "control function returns no allowed unit dims to prune");
586  }
587 
588  if (padOp.getSourceType().getEncoding()) {
589  return rewriter.notifyMatchFailure(
590  padOp, "cannot collapse dims of tensor with encoding");
591  }
592 
593  // Fail for non-constant padding values. The body of the pad could
594  // depend on the padding indices and/or properties of the padded
595  // tensor so for now we fail.
596  // TODO: Support non-constant padding values.
597  Value paddingVal = padOp.getConstantPaddingValue();
598  if (!paddingVal) {
599  return rewriter.notifyMatchFailure(
600  padOp, "unimplemented: non-constant padding value");
601  }
602 
603  ArrayRef<int64_t> sourceShape = padOp.getSourceType().getShape();
604  int64_t padRank = sourceShape.size();
605 
606  auto isStaticZero = [](OpFoldResult f) {
607  std::optional<int64_t> maybeInt = getConstantIntValue(f);
608  return maybeInt && *maybeInt == 0;
609  };
610 
611  llvm::SmallDenseSet<unsigned> unitDimsFilter(allowedUnitDims.begin(),
612  allowedUnitDims.end());
613  llvm::SmallDenseSet<unsigned> unitDims;
614  SmallVector<int64_t> newShape;
615  SmallVector<OpFoldResult> newLowPad;
616  SmallVector<OpFoldResult> newHighPad;
617  for (const auto [dim, size, low, high] :
618  zip_equal(llvm::seq(static_cast<int64_t>(0), padRank), sourceShape,
619  padOp.getMixedLowPad(), padOp.getMixedHighPad())) {
620  if (unitDimsFilter.contains(dim) && size == 1 && isStaticZero(low) &&
621  isStaticZero(high)) {
622  unitDims.insert(dim);
623  } else {
624  newShape.push_back(size);
625  newLowPad.push_back(low);
626  newHighPad.push_back(high);
627  }
628  }
629 
630  if (unitDims.empty()) {
631  return rewriter.notifyMatchFailure(padOp, "no unit dims to collapse");
632  }
633 
634  ReassociationIndices reassociationGroup;
635  SmallVector<ReassociationIndices> reassociationMap;
636  int64_t dim = 0;
637  while (dim < padRank && unitDims.contains(dim))
638  reassociationGroup.push_back(dim++);
639  while (dim < padRank) {
640  assert(!unitDims.contains(dim) && "expected non unit-extent");
641  reassociationGroup.push_back(dim);
642  dim++;
643  // Fold all following dimensions that are unit-extent.
644  while (dim < padRank && unitDims.contains(dim))
645  reassociationGroup.push_back(dim++);
646  reassociationMap.push_back(reassociationGroup);
647  reassociationGroup.clear();
648  }
649 
650  Value collapsedSource =
651  collapseValue(rewriter, padOp.getLoc(), padOp.getSource(), newShape,
652  reassociationMap, options.rankReductionStrategy);
653 
654  auto newPadOp = rewriter.create<tensor::PadOp>(
655  padOp.getLoc(), /*result=*/Type(), collapsedSource, newLowPad,
656  newHighPad, paddingVal, padOp.getNofold());
657 
658  Value dest = padOp.getResult();
659  if (options.rankReductionStrategy ==
661  SmallVector<OpFoldResult> expandedSizes;
662  int64_t numUnitDims = 0;
663  for (auto dim : llvm::seq(static_cast<int64_t>(0), padRank)) {
664  if (unitDims.contains(dim)) {
665  expandedSizes.push_back(rewriter.getIndexAttr(1));
666  numUnitDims++;
667  continue;
668  }
669  expandedSizes.push_back(tensor::getMixedSize(
670  rewriter, padOp.getLoc(), newPadOp, dim - numUnitDims));
671  }
672  dest = rewriter.create<tensor::EmptyOp>(
673  padOp.getLoc(), expandedSizes,
674  padOp.getResultType().getElementType());
675  }
676 
677  Value expandedValue =
678  expandValue(rewriter, padOp.getLoc(), newPadOp.getResult(), dest,
679  reassociationMap, options.rankReductionStrategy);
680  rewriter.replaceOp(padOp, expandedValue);
681  return success();
682  }
683 
684 private:
686 };
687 } // namespace
688 
689 namespace {
690 /// Convert `extract_slice` operations to rank-reduced versions.
691 struct RankReducedExtractSliceOp
692  : public OpRewritePattern<tensor::ExtractSliceOp> {
694 
695  LogicalResult matchAndRewrite(tensor::ExtractSliceOp sliceOp,
696  PatternRewriter &rewriter) const override {
697  RankedTensorType resultType = sliceOp.getType();
698  SmallVector<OpFoldResult> targetShape;
699  for (auto size : resultType.getShape())
700  targetShape.push_back(rewriter.getIndexAttr(size));
701  auto reassociation = getReassociationMapForFoldingUnitDims(targetShape);
702  if (!reassociation ||
703  reassociation->size() == static_cast<size_t>(resultType.getRank()))
704  return failure();
705 
706  SmallVector<OpFoldResult> offsets = sliceOp.getMixedOffsets();
707  SmallVector<OpFoldResult> strides = sliceOp.getMixedStrides();
708  SmallVector<OpFoldResult> sizes = sliceOp.getMixedSizes();
709  auto rankReducedType = cast<RankedTensorType>(
710  tensor::ExtractSliceOp::inferCanonicalRankReducedResultType(
711  reassociation->size(), sliceOp.getSourceType(), offsets, sizes,
712  strides));
713 
714  Location loc = sliceOp.getLoc();
715  Value newSlice = rewriter.create<tensor::ExtractSliceOp>(
716  loc, rankReducedType, sliceOp.getSource(), offsets, sizes, strides);
717  rewriter.replaceOpWithNewOp<tensor::ExpandShapeOp>(
718  sliceOp, resultType, newSlice, *reassociation);
719  return success();
720  }
721 };
722 
723 /// Convert `insert_slice` operations to rank-reduced versions.
724 /// This patterns works with both InsertSliceOp and ParallelInsertSliceOp.
725 template <typename InsertOpTy>
726 struct RankReducedInsertSliceOp : public OpRewritePattern<InsertOpTy> {
728 
729  LogicalResult matchAndRewrite(InsertOpTy insertSliceOp,
730  PatternRewriter &rewriter) const override {
731  RankedTensorType sourceType = insertSliceOp.getSourceType();
732  SmallVector<OpFoldResult> targetShape;
733  for (auto size : sourceType.getShape())
734  targetShape.push_back(rewriter.getIndexAttr(size));
735  auto reassociation = getReassociationMapForFoldingUnitDims(targetShape);
736  if (!reassociation ||
737  reassociation->size() == static_cast<size_t>(sourceType.getRank()))
738  return failure();
739 
740  Location loc = insertSliceOp.getLoc();
741  tensor::CollapseShapeOp reshapedSource;
742  {
743  OpBuilder::InsertionGuard g(rewriter);
744  // The only difference between InsertSliceOp and ParallelInsertSliceOp
745  // is the insertion point is just before the ParallelCombiningOp in the
746  // parallel case.
747  if (std::is_same<InsertOpTy, tensor::ParallelInsertSliceOp>::value)
748  rewriter.setInsertionPoint(insertSliceOp->getParentOp());
749  reshapedSource = rewriter.create<tensor::CollapseShapeOp>(
750  loc, insertSliceOp.getSource(), *reassociation);
751  }
752  rewriter.replaceOpWithNewOp<InsertOpTy>(
753  insertSliceOp, reshapedSource, insertSliceOp.getDest(),
754  insertSliceOp.getMixedOffsets(), insertSliceOp.getMixedSizes(),
755  insertSliceOp.getMixedStrides());
756  return success();
757  }
758 };
759 } // namespace
760 
761 /// Patterns that are used to canonicalize the use of unit-extent dims for
762 /// broadcasting.
763 static void
766  auto *context = patterns.getContext();
767  patterns.add<DropUnitDims>(context, options);
768  patterns.add<DropPadUnitDims>(context, options);
769  // TODO: Patterns unrelated to unit dim folding should be factored out.
770  patterns.add<RankReducedExtractSliceOp,
771  RankReducedInsertSliceOp<tensor::InsertSliceOp>,
772  RankReducedInsertSliceOp<tensor::ParallelInsertSliceOp>>(
773  context);
774  linalg::FillOp::getCanonicalizationPatterns(patterns, context);
775  tensor::CollapseShapeOp::getCanonicalizationPatterns(patterns, context);
776  tensor::EmptyOp::getCanonicalizationPatterns(patterns, context);
777  tensor::ExpandShapeOp::getCanonicalizationPatterns(patterns, context);
781 }
782 
783 static void
786  auto *context = patterns.getContext();
787  patterns.add<DropUnitDims>(context, options);
788  patterns.add<DropPadUnitDims>(context, options);
789  // TODO: Patterns unrelated to unit dim folding should be factored out.
790  linalg::FillOp::getCanonicalizationPatterns(patterns, context);
791  tensor::EmptyOp::getCanonicalizationPatterns(patterns, context);
795 }
796 
799  if (options.rankReductionStrategy ==
802  } else if (options.rankReductionStrategy ==
804  ReassociativeReshape) {
806  }
807 }
808 
810  RewritePatternSet &patterns) {
811  patterns.add<MoveInitOperandsToInput>(patterns.getContext());
812 }
813 
814 namespace {
815 /// Pass that removes unit-extent dims within generic ops.
816 struct LinalgFoldUnitExtentDimsPass
817  : public impl::LinalgFoldUnitExtentDimsPassBase<
818  LinalgFoldUnitExtentDimsPass> {
819  using impl::LinalgFoldUnitExtentDimsPassBase<
820  LinalgFoldUnitExtentDimsPass>::LinalgFoldUnitExtentDimsPassBase;
821  void runOnOperation() override {
822  Operation *op = getOperation();
823  MLIRContext *context = op->getContext();
824  RewritePatternSet patterns(context);
826  if (useRankReducingSlices) {
827  options.rankReductionStrategy = linalg::ControlDropUnitDims::
829  }
832  (void)applyPatternsAndFoldGreedily(op, std::move(patterns));
833  }
834 };
835 
836 } // namespace
837 
838 namespace {
839 
840 /// Returns reassociation indices for collapsing/expanding a
841 /// tensor of rank `rank` at position `pos`.
843 getReassociationForReshapeAtDim(int64_t rank, int64_t pos) {
844  SmallVector<ReassociationIndices> reassociation(rank - 1, {0, 1});
845  bool lastDim = pos == rank - 1;
846  if (rank > 2) {
847  for (int64_t i = 0; i < rank - 1; i++) {
848  if (i == pos || (lastDim && i == pos - 1))
849  reassociation[i] = ReassociationIndices{i, i + 1};
850  else if (i < pos)
851  reassociation[i] = ReassociationIndices{i};
852  else
853  reassociation[i] = ReassociationIndices{i + 1};
854  }
855  }
856  return reassociation;
857 }
858 
859 /// Returns a collapsed `val` where the collapsing occurs at dim `pos`.
860 /// If `pos < 0`, then don't collapse.
861 static Value collapseSingletonDimAt(PatternRewriter &rewriter, Value val,
862  int64_t pos) {
863  if (pos < 0)
864  return val;
865  auto valType = cast<ShapedType>(val.getType());
866  SmallVector<int64_t> collapsedShape(valType.getShape());
867  collapsedShape.erase(collapsedShape.begin() + pos);
868  return collapseValue(
869  rewriter, val.getLoc(), val, collapsedShape,
870  getReassociationForReshapeAtDim(valType.getRank(), pos),
872 }
873 
874 /// Base class for all rank reduction patterns for contraction ops
875 /// with unit dimensions. All patterns should convert one named op
876 /// to another named op. Intended to reduce only one iteration space dim
877 /// at a time.
878 /// Reducing multiple dims will happen with recusive application of
879 /// pattern rewrites.
880 template <typename FromOpTy, typename ToOpTy>
881 struct RankReduceContractionOps : OpRewritePattern<FromOpTy> {
883 
884  /// Collapse all collapsable operands.
886  collapseOperands(PatternRewriter &rewriter, ArrayRef<Value> operands,
887  ArrayRef<int64_t> operandCollapseDims) const {
888  assert(operandCollapseDims.size() == 3 && operands.size() == 3 &&
889  "expected 3 operands and dims");
890  return llvm::map_to_vector(
891  llvm::zip(operands, operandCollapseDims), [&](auto pair) {
892  return collapseSingletonDimAt(rewriter, std::get<0>(pair),
893  std::get<1>(pair));
894  });
895  }
896 
897  /// Expand result tensor.
898  Value expandResult(PatternRewriter &rewriter, Value result,
899  RankedTensorType expandedType, int64_t dim) const {
900  return rewriter.create<tensor::ExpandShapeOp>(
901  result.getLoc(), expandedType, result,
902  getReassociationForReshapeAtDim(expandedType.getRank(), dim));
903  }
904 
905  LogicalResult matchAndRewrite(FromOpTy contractionOp,
906  PatternRewriter &rewriter) const override {
907 
908  auto loc = contractionOp.getLoc();
909  auto inputs = contractionOp.getDpsInputs();
910  auto inits = contractionOp.getDpsInits();
911  if (inputs.size() != 2 || inits.size() != 1)
912  return rewriter.notifyMatchFailure(contractionOp,
913  "expected 2 inputs and 1 init");
914  auto lhs = inputs[0];
915  auto rhs = inputs[1];
916  auto init = inits[0];
917  SmallVector<Value> operands{lhs, rhs, init};
918 
919  SmallVector<int64_t> operandUnitDims;
920  if (failed(getOperandUnitDims(contractionOp, operandUnitDims)))
921  return rewriter.notifyMatchFailure(contractionOp,
922  "no reducable dims found");
923 
924  SmallVector<Value> collapsedOperands =
925  collapseOperands(rewriter, operands, operandUnitDims);
926  Value collapsedLhs = collapsedOperands[0];
927  Value collapsedRhs = collapsedOperands[1];
928  Value collapsedInit = collapsedOperands[2];
929  SmallVector<Type, 1> collapsedResultTy;
930  if (isa<RankedTensorType>(collapsedInit.getType()))
931  collapsedResultTy.push_back(collapsedInit.getType());
932  auto collapsedOp = rewriter.create<ToOpTy>(
933  loc, collapsedResultTy, ValueRange{collapsedLhs, collapsedRhs},
934  ValueRange{collapsedInit});
935  for (auto attr : contractionOp->getAttrs()) {
936  if (attr.getName() == LinalgDialect::kMemoizedIndexingMapsAttrName)
937  continue;
938  collapsedOp->setAttr(attr.getName(), attr.getValue());
939  }
940 
941  auto results = contractionOp.getResults();
942  assert(results.size() < 2 && "expected at most one result");
943  if (results.empty()) {
944  rewriter.replaceOp(contractionOp, collapsedOp);
945  } else {
946  rewriter.replaceOp(
947  contractionOp,
948  expandResult(rewriter, collapsedOp.getResultTensors()[0],
949  cast<RankedTensorType>(results[0].getType()),
950  operandUnitDims[2]));
951  }
952 
953  return success();
954  }
955 
956  /// Populate `operandUnitDims` with 3 indices indicating the unit dim
957  /// for each operand that should be collapsed in this pattern. If an
958  /// operand shouldn't be collapsed, the index should be negative.
959  virtual LogicalResult
960  getOperandUnitDims(LinalgOp op,
961  SmallVectorImpl<int64_t> &operandUnitDims) const = 0;
962 };
963 
964 /// Patterns for unbatching batched contraction ops
965 template <typename FromOpTy, typename ToOpTy>
966 struct RankReduceToUnBatched : RankReduceContractionOps<FromOpTy, ToOpTy> {
967  using RankReduceContractionOps<FromOpTy, ToOpTy>::RankReduceContractionOps;
968 
969  /// Look for unit batch dims to collapse.
970  LogicalResult
971  getOperandUnitDims(LinalgOp op,
972  SmallVectorImpl<int64_t> &operandUnitDims) const override {
973  FailureOr<ContractionDimensions> maybeContractionDims =
975  if (failed(maybeContractionDims)) {
976  LLVM_DEBUG(llvm::dbgs() << "could not infer contraction dims");
977  return failure();
978  }
979  ContractionDimensions contractionDims = maybeContractionDims.value();
980 
981  if (contractionDims.batch.size() != 1)
982  return failure();
983  auto batchDim = contractionDims.batch[0];
985  op.mapIterationSpaceDimToAllOperandDims(batchDim, bOperands);
986  if (bOperands.size() != 3 || llvm::any_of(bOperands, [](auto pair) {
987  return cast<ShapedType>(std::get<0>(pair).getType())
988  .getShape()[std::get<1>(pair)] != 1;
989  })) {
990  LLVM_DEBUG(llvm::dbgs() << "specified unit dims not found");
991  return failure();
992  }
993 
994  operandUnitDims = SmallVector<int64_t>{std::get<1>(bOperands[0]),
995  std::get<1>(bOperands[1]),
996  std::get<1>(bOperands[2])};
997  return success();
998  }
999 };
1000 
1001 /// Patterns for reducing non-batch dimensions
1002 template <typename FromOpTy, typename ToOpTy>
1003 struct RankReduceMatmul : RankReduceContractionOps<FromOpTy, ToOpTy> {
1004  using RankReduceContractionOps<FromOpTy, ToOpTy>::RankReduceContractionOps;
1005 
1006  /// Helper for determining whether the lhs/init or rhs/init are reduced.
1007  static bool constexpr reduceLeft =
1008  (std::is_same_v<FromOpTy, BatchMatmulOp> &&
1009  std::is_same_v<ToOpTy, BatchVecmatOp>) ||
1010  (std::is_same_v<FromOpTy, BatchMatmulTransposeAOp> &&
1011  std::is_same_v<ToOpTy, BatchVecmatOp>) ||
1012  (std::is_same_v<FromOpTy, MatmulOp> &&
1013  std::is_same_v<ToOpTy, VecmatOp>) ||
1014  (std::is_same_v<FromOpTy, MatmulTransposeAOp> &&
1015  std::is_same_v<ToOpTy, VecmatOp>) ||
1016  (std::is_same_v<FromOpTy, MatvecOp> && std::is_same_v<ToOpTy, DotOp>);
1017 
1018  /// Look for non-batch spatial dims to collapse.
1019  LogicalResult
1020  getOperandUnitDims(LinalgOp op,
1021  SmallVectorImpl<int64_t> &operandUnitDims) const override {
1022  FailureOr<ContractionDimensions> maybeContractionDims =
1024  if (failed(maybeContractionDims)) {
1025  LLVM_DEBUG(llvm::dbgs() << "could not infer contraction dims");
1026  return failure();
1027  }
1028  ContractionDimensions contractionDims = maybeContractionDims.value();
1029 
1030  if constexpr (reduceLeft) {
1031  auto m = contractionDims.m[0];
1033  op.mapIterationSpaceDimToAllOperandDims(m, mOperands);
1034  if (mOperands.size() != 2)
1035  return failure();
1036  if (llvm::all_of(mOperands, [](auto pair) {
1037  return cast<ShapedType>(std::get<0>(pair).getType())
1038  .getShape()[std::get<1>(pair)] == 1;
1039  })) {
1040  operandUnitDims = SmallVector<int64_t>{std::get<1>(mOperands[0]), -1,
1041  std::get<1>(mOperands[1])};
1042  return success();
1043  }
1044  } else {
1045  auto n = contractionDims.n[0];
1047  op.mapIterationSpaceDimToAllOperandDims(n, nOperands);
1048  if (nOperands.size() != 2)
1049  return failure();
1050  if (llvm::all_of(nOperands, [](auto pair) {
1051  return cast<ShapedType>(std::get<0>(pair).getType())
1052  .getShape()[std::get<1>(pair)] == 1;
1053  })) {
1054  operandUnitDims = SmallVector<int64_t>{-1, std::get<1>(nOperands[0]),
1055  std::get<1>(nOperands[1])};
1056  return success();
1057  }
1058  }
1059  LLVM_DEBUG(llvm::dbgs() << "specified unit dims not found");
1060  return failure();
1061  }
1062 };
1063 
1064 } // namespace
1065 
1067  RewritePatternSet &patterns) {
1068  MLIRContext *context = patterns.getContext();
1069  // Unbatching patterns for unit batch size
1070  patterns.add<RankReduceToUnBatched<BatchMatmulOp, MatmulOp>>(context);
1071  patterns
1072  .add<RankReduceToUnBatched<BatchMatmulTransposeAOp, MatmulTransposeAOp>>(
1073  context);
1074  patterns
1075  .add<RankReduceToUnBatched<BatchMatmulTransposeBOp, MatmulTransposeBOp>>(
1076  context);
1077  patterns.add<RankReduceToUnBatched<BatchMatvecOp, MatvecOp>>(context);
1078  patterns.add<RankReduceToUnBatched<BatchVecmatOp, VecmatOp>>(context);
1079 
1080  // Non-batch rank 1 reducing patterns
1081  patterns.add<RankReduceMatmul<MatmulOp, VecmatOp>>(context);
1082  patterns.add<RankReduceMatmul<MatmulOp, MatvecOp>>(context);
1083  patterns.add<RankReduceMatmul<MatmulTransposeAOp, VecmatOp>>(context);
1084  patterns.add<RankReduceMatmul<MatmulTransposeBOp, MatvecOp>>(context);
1085  // Batch rank 1 reducing patterns
1086  patterns.add<RankReduceMatmul<BatchMatmulOp, BatchVecmatOp>>(context);
1087  patterns.add<RankReduceMatmul<BatchMatmulOp, BatchMatvecOp>>(context);
1088  patterns.add<RankReduceMatmul<BatchMatmulTransposeAOp, BatchVecmatOp>>(
1089  context);
1090  patterns.add<RankReduceMatmul<BatchMatmulTransposeBOp, BatchMatvecOp>>(
1091  context);
1092 
1093  // Non-batch rank 0 reducing patterns
1094  patterns.add<RankReduceMatmul<MatvecOp, DotOp>>(context);
1095  patterns.add<RankReduceMatmul<VecmatOp, DotOp>>(context);
1096 }
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:33
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition: Block.cpp:155
IntegerAttr getIndexAttr(int64_t value)
Definition: Builders.cpp:148
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:66
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:356
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:588
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:406
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:470
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:528
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Definition: Builders.h:429
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:497
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:791
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:829
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:853
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:724
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:542
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:344
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(...
FailureOr< DropUnitDimsResult > dropUnitDims(RewriterBase &rewriter, GenericOp genericOp, const ControlDropUnitDims &options)
SmallVector< NamedAttribute > getPrunedAttributeList(OpTy op)
Returns an attribute list that excludes pre-defined attributes.
Definition: Utils.h:364
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:852
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...
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:56
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
Definition: TensorOps.cpp:66
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:791
AffineMap concatAffineMaps(ArrayRef< AffineMap > maps)
Concatenates a list of maps into a single AffineMap, stepping over potentially empty maps.
Definition: AffineMap.cpp:836
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:641
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:617
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