1 //===----------------------------------------------------------------------===//
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 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
10 #include "mlir/Dialect/StandardOps/Utils/Utils.h"
11 #include "mlir/Dialect/Tensor/IR/Tensor.h"
12 #include "mlir/Dialect/Utils/ReshapeOpsUtils.h"
13 #include "mlir/Dialect/Utils/StaticValueUtils.h"
14 #include "mlir/IR/BlockAndValueMapping.h"
15 #include "mlir/IR/Builders.h"
16 #include "mlir/IR/BuiltinAttributeInterfaces.h"
17 #include "mlir/IR/Matchers.h"
18 #include "mlir/IR/PatternMatch.h"
19 #include "mlir/IR/TypeUtilities.h"
20 #include "llvm/ADT/STLExtras.h"
21 
22 using namespace mlir;
23 using namespace mlir::tensor;
24 
25 /// Materialize a single constant operation from a given attribute value with
26 /// the desired resultant type.
27 Operation *TensorDialect::materializeConstant(OpBuilder &builder,
28                                               Attribute value, Type type,
29                                               Location loc) {
30   if (arith::ConstantOp::isBuildableWith(value, type))
31     return builder.create<arith::ConstantOp>(loc, value, type);
32   if (ConstantOp::isBuildableWith(value, type))
33     return builder.create<ConstantOp>(loc, value, type);
34   return nullptr;
35 }
36 
37 //===----------------------------------------------------------------------===//
38 // CastOp
39 //===----------------------------------------------------------------------===//
40 
41 /// Returns true if `target` is a ranked tensor type that preserves static
42 /// information available in the `source` ranked tensor type.
43 bool mlir::tensor::preservesStaticInformation(Type source, Type target) {
44   auto sourceType = source.dyn_cast<RankedTensorType>();
45   auto targetType = target.dyn_cast<RankedTensorType>();
46 
47   // Requires RankedTensorType.
48   if (!sourceType || !targetType)
49     return false;
50 
51   // Requires same elemental type.
52   if (sourceType.getElementType() != targetType.getElementType())
53     return false;
54 
55   // Requires same rank.
56   if (sourceType.getRank() != targetType.getRank())
57     return false;
58 
59   // If cast is towards more static sizes along any dimension, don't fold.
60   for (auto t : llvm::zip(sourceType.getShape(), targetType.getShape())) {
61     if (!ShapedType::isDynamic(std::get<0>(t)) &&
62         ShapedType::isDynamic(std::get<1>(t)))
63       return false;
64   }
65 
66   return true;
67 }
68 
69 /// Determines whether tensor::CastOp casts to a more dynamic version of the
70 /// source tensor. This is useful to fold a tensor.cast into a consuming op and
71 /// implement canonicalization patterns for ops in different dialects that may
72 /// consume the results of tensor.cast operations. Such foldable tensor.cast
73 /// operations are typically inserted as `slice` ops and are canonicalized,
74 /// to preserve the type compatibility of their uses.
75 ///
76 /// Returns true when all conditions are met:
77 /// 1. source and result are ranked tensors with same element type and rank.
78 /// 2. the tensor type has more static information than the result
79 ///
80 /// Example:
81 /// ```mlir
82 ///   %1 = tensor.cast %0 : tensor<8x16xf32> to tensor<?x?xf32>
83 ///   %2 = consumer %1 ... : tensor<?x?xf32> ...
84 /// ```
85 ///
86 /// folds into:
87 ///
88 /// ```mlir
89 ///   %2 = consumer %0 ... : tensor<8x16xf32> ...
90 /// ```
91 bool mlir::tensor::canFoldIntoConsumerOp(CastOp castOp) {
92   if (!castOp)
93     return false;
94 
95   // Can fold if the source of cast has at least as much static information as
96   // its results.
97   return preservesStaticInformation(castOp.getType(),
98                                     castOp.source().getType());
99 }
100 
101 /// Performs folding of any operand of `op` if it comes from a tensor::CastOp
102 /// that can be folded.
103 LogicalResult mlir::tensor::foldTensorCast(Operation *op) {
104   bool folded = false;
105   for (OpOperand &operand : op->getOpOperands()) {
106     auto castOp = operand.get().getDefiningOp<tensor::CastOp>();
107     if (castOp && tensor::canFoldIntoConsumerOp(castOp)) {
108       operand.set(castOp.getOperand());
109       folded = true;
110     }
111   }
112   return success(folded);
113 }
114 
115 bool CastOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
116   if (inputs.size() != 1 || outputs.size() != 1)
117     return false;
118   Type a = inputs.front(), b = outputs.front();
119   auto aT = a.dyn_cast<TensorType>();
120   auto bT = b.dyn_cast<TensorType>();
121   if (!aT || !bT)
122     return false;
123 
124   if (aT.getElementType() != bT.getElementType())
125     return false;
126 
127   return succeeded(verifyCompatibleShape(aT, bT));
128 }
129 
130 /// Compute a TensorType that has the joined shape knowledge of the two
131 /// given TensorTypes. The element types need to match.
132 static TensorType joinShapes(TensorType one, TensorType two) {
133   assert(one.getElementType() == two.getElementType());
134 
135   if (!one.hasRank())
136     return two;
137   if (!two.hasRank())
138     return one;
139 
140   int64_t rank = one.getRank();
141   if (rank != two.getRank())
142     return {};
143 
144   SmallVector<int64_t, 4> join;
145   join.reserve(rank);
146   for (int64_t i = 0; i < rank; ++i) {
147     if (one.isDynamicDim(i)) {
148       join.push_back(two.getDimSize(i));
149       continue;
150     }
151     if (two.isDynamicDim(i)) {
152       join.push_back(one.getDimSize(i));
153       continue;
154     }
155     if (one.getDimSize(i) != two.getDimSize(i))
156       return {};
157     join.push_back(one.getDimSize(i));
158   }
159   return RankedTensorType::get(join, one.getElementType());
160 }
161 
162 namespace {
163 
164 /// Replaces chains of two tensor.cast operations by a single tensor.cast
165 /// operation if doing so does not remove runtime constraints.
166 struct ChainedTensorCast : public OpRewritePattern<CastOp> {
167   using OpRewritePattern<CastOp>::OpRewritePattern;
168 
169   LogicalResult matchAndRewrite(CastOp tensorCast,
170                                 PatternRewriter &rewriter) const final {
171     auto tensorCastOperand = tensorCast.getOperand().getDefiningOp<CastOp>();
172 
173     if (!tensorCastOperand)
174       return failure();
175 
176     auto sourceType =
177         tensorCastOperand.getOperand().getType().cast<TensorType>();
178     auto intermediateType = tensorCastOperand.getType().cast<TensorType>();
179     auto resultType = tensorCast.getType().cast<TensorType>();
180 
181     // We can remove the intermediate cast if joining all three produces the
182     // same result as just joining the source and result shapes.
183     auto firstJoin =
184         joinShapes(joinShapes(sourceType, intermediateType), resultType);
185 
186     // The join might not exist if the cast sequence would fail at runtime.
187     if (!firstJoin)
188       return failure();
189 
190     // The newJoin always exists if the above join exists, it might just contain
191     // less information. If so, we cannot drop the intermediate cast, as doing
192     // so would remove runtime checks.
193     auto newJoin = joinShapes(sourceType, resultType);
194     if (firstJoin != newJoin)
195       return failure();
196 
197     rewriter.replaceOpWithNewOp<CastOp>(tensorCast, resultType,
198                                         tensorCastOperand.getOperand());
199     return success();
200   }
201 };
202 
203 } // namespace
204 
205 void CastOp::getCanonicalizationPatterns(RewritePatternSet &results,
206                                          MLIRContext *context) {
207   results.add<ChainedTensorCast>(context);
208 }
209 
210 //===----------------------------------------------------------------------===//
211 // DimOp
212 //===----------------------------------------------------------------------===//
213 
214 void DimOp::build(OpBuilder &builder, OperationState &result, Value source,
215                   int64_t index) {
216   auto loc = result.location;
217   Value indexValue = builder.create<arith::ConstantIndexOp>(loc, index);
218   build(builder, result, source, indexValue);
219 }
220 
221 Optional<int64_t> DimOp::getConstantIndex() {
222   if (auto constantOp = index().getDefiningOp<arith::ConstantOp>())
223     return constantOp.getValue().cast<IntegerAttr>().getInt();
224   return {};
225 }
226 
227 static LogicalResult verify(DimOp op) {
228   // Assume unknown index to be in range.
229   Optional<int64_t> index = op.getConstantIndex();
230   if (!index.hasValue())
231     return success();
232 
233   // Check that constant index is not knowingly out of range.
234   auto type = op.source().getType();
235   if (auto tensorType = type.dyn_cast<RankedTensorType>()) {
236     if (index.getValue() >= tensorType.getRank())
237       return op.emitOpError("index is out of range");
238   } else if (type.isa<UnrankedTensorType>()) {
239     // Assume index to be in range.
240   } else {
241     llvm_unreachable("expected operand with tensor type");
242   }
243   return success();
244 }
245 
246 OpFoldResult DimOp::fold(ArrayRef<Attribute> operands) {
247   // All forms of folding require a known index.
248   auto index = operands[1].dyn_cast_or_null<IntegerAttr>();
249   if (!index)
250     return {};
251 
252   // Folding for unranked types (UnrankedTensorType) is not supported.
253   auto tensorType = source().getType().dyn_cast<RankedTensorType>();
254   if (!tensorType)
255     return {};
256 
257   // Fold if the shape extent along the given index is known.
258   if (!tensorType.isDynamicDim(index.getInt())) {
259     Builder builder(getContext());
260     return builder.getIndexAttr(tensorType.getShape()[index.getInt()]);
261   }
262 
263   Operation *definingOp = source().getDefiningOp();
264 
265   // Fold dim to the operand of tensor.generate.
266   if (auto fromElements = dyn_cast_or_null<tensor::GenerateOp>(definingOp)) {
267     auto resultType =
268         fromElements.getResult().getType().cast<RankedTensorType>();
269     // The case where the type encodes the size of the dimension is handled
270     // above.
271     assert(ShapedType::isDynamic(resultType.getShape()[index.getInt()]));
272 
273     // Find the operand of the fromElements that corresponds to this index.
274     auto dynExtents = fromElements.dynamicExtents().begin();
275     for (auto dim : resultType.getShape().take_front(index.getInt()))
276       if (ShapedType::isDynamic(dim))
277         dynExtents++;
278 
279     return Value{*dynExtents};
280   }
281 
282   // The size at the given index is now known to be a dynamic size.
283   unsigned unsignedIndex = index.getValue().getZExtValue();
284 
285   if (auto sliceOp = dyn_cast_or_null<tensor::ExtractSliceOp>(definingOp)) {
286     // Fold only for non-rank reduced ops. For the rank-reduced version, rely on
287     // `resolve-shaped-type-result-dims` pass.
288     if (sliceOp.getType().getRank() == sliceOp.getSourceType().getRank() &&
289         sliceOp.isDynamicSize(unsignedIndex)) {
290       return {sliceOp.getDynamicSize(unsignedIndex)};
291     }
292   }
293 
294   // dim(cast) -> dim
295   if (succeeded(foldTensorCast(*this)))
296     return getResult();
297 
298   return {};
299 }
300 
301 namespace {
302 /// Fold dim of a cast into the dim of the source of the tensor cast.
303 struct DimOfCastOp : public OpRewritePattern<DimOp> {
304   using OpRewritePattern<DimOp>::OpRewritePattern;
305 
306   LogicalResult matchAndRewrite(DimOp dimOp,
307                                 PatternRewriter &rewriter) const override {
308     auto castOp = dimOp.source().getDefiningOp<CastOp>();
309     if (!castOp)
310       return failure();
311     Value newSource = castOp.getOperand();
312     rewriter.replaceOpWithNewOp<DimOp>(dimOp, newSource, dimOp.index());
313     return success();
314   }
315 };
316 } // namespace
317 
318 void DimOp::getCanonicalizationPatterns(RewritePatternSet &results,
319                                         MLIRContext *context) {
320   results.add<DimOfCastOp>(context);
321 }
322 
323 //===----------------------------------------------------------------------===//
324 // ExtractOp
325 //===----------------------------------------------------------------------===//
326 
327 static LogicalResult verify(ExtractOp op) {
328   // Verify the # indices match if we have a ranked type.
329   if (auto tensorType = op.tensor().getType().dyn_cast<RankedTensorType>())
330     if (tensorType.getRank() != static_cast<int64_t>(op.indices().size()))
331       return op.emitOpError("incorrect number of indices for extract_element");
332 
333   return success();
334 }
335 
336 OpFoldResult ExtractOp::fold(ArrayRef<Attribute> operands) {
337   // The tensor operand must be a known constant.
338   Attribute tensor = operands.front();
339   if (!tensor)
340     return {};
341   // If this is a splat elements attribute, simply return the value. All of the
342   // elements of a splat attribute are the same.
343   if (auto splatTensor = tensor.dyn_cast<SplatElementsAttr>())
344     return splatTensor.getSplatValue<Attribute>();
345 
346   // Otherwise, collect the constant indices into the tensor.
347   SmallVector<uint64_t, 8> indices;
348   for (Attribute indice : llvm::drop_begin(operands, 1)) {
349     if (!indice || !indice.isa<IntegerAttr>())
350       return {};
351     indices.push_back(indice.cast<IntegerAttr>().getInt());
352   }
353 
354   // If this is an elements attribute, query the value at the given indices.
355   auto elementsAttr = tensor.dyn_cast<ElementsAttr>();
356   if (elementsAttr && elementsAttr.isValidIndex(indices))
357     return elementsAttr.getValues<Attribute>()[indices];
358   return {};
359 }
360 
361 //===----------------------------------------------------------------------===//
362 // FromElementsOp
363 //===----------------------------------------------------------------------===//
364 
365 void FromElementsOp::build(OpBuilder &builder, OperationState &result,
366                            Type resultType, ValueRange elements) {
367   result.addOperands(elements);
368   result.addTypes(resultType);
369 }
370 
371 void FromElementsOp::build(OpBuilder &builder, OperationState &result,
372                            ValueRange elements) {
373   assert(!elements.empty() && "expected at least one element");
374   Type resultType = RankedTensorType::get(
375       {static_cast<int64_t>(elements.size())}, elements.front().getType());
376   build(builder, result, resultType, elements);
377 }
378 
379 OpFoldResult FromElementsOp::fold(ArrayRef<Attribute> operands) {
380   if (!llvm::is_contained(operands, nullptr))
381     return DenseElementsAttr::get(getType(), operands);
382   return {};
383 }
384 
385 namespace {
386 
387 // Canonicalizes the pattern of the form
388 //
389 // %tensor = tensor.from_elements(%element) : (i32) -> tensor<1xi32>
390 // %extracted_element = tensor.extract %tensor[%c0] : tensor<1xi32>
391 //
392 // to just %element.
393 struct ExtractElementFromTensorFromElements
394     : public OpRewritePattern<tensor::ExtractOp> {
395   using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern;
396 
397   LogicalResult matchAndRewrite(tensor::ExtractOp extract,
398                                 PatternRewriter &rewriter) const final {
399     auto tensorFromElements = extract.tensor().getDefiningOp<FromElementsOp>();
400     if (!tensorFromElements)
401       return failure();
402     auto tensorType = tensorFromElements.getType().cast<RankedTensorType>();
403     auto rank = tensorType.getRank();
404     if (rank == 0) {
405       rewriter.replaceOp(extract, tensorFromElements.getOperand(0));
406       return success();
407     }
408     SmallVector<APInt, 3> indices(rank);
409     int64_t flatIndex = 0;
410     int64_t stride = 1;
411     for (int i = rank - 1; i >= 0; --i) {
412       APInt index;
413       if (!matchPattern(extract.indices()[i], m_ConstantInt(&index)))
414         return failure();
415       if (i < rank - 1)
416         stride *= tensorType.getDimSize(i);
417       flatIndex += index.getSExtValue() * stride;
418     }
419     // Prevent out of bounds accesses. This can happen in invalid code that will
420     // never execute.
421     if (tensorFromElements->getNumOperands() <= flatIndex || flatIndex < 0)
422       return failure();
423     rewriter.replaceOp(extract, tensorFromElements.getOperand(flatIndex));
424     return success();
425   }
426 };
427 
428 } // namespace
429 
430 void FromElementsOp::getCanonicalizationPatterns(RewritePatternSet &results,
431                                                  MLIRContext *context) {
432   results.add<ExtractElementFromTensorFromElements>(context);
433 }
434 
435 //===----------------------------------------------------------------------===//
436 // InsertOp
437 //===----------------------------------------------------------------------===//
438 
439 static LogicalResult verify(InsertOp op) {
440   // Verify the # indices match if we have a ranked type.
441   if (auto destType = op.dest().getType().dyn_cast<RankedTensorType>())
442     if (destType.getRank() != static_cast<int64_t>(op.indices().size()))
443       return op.emitOpError("incorrect number of indices");
444   return success();
445 }
446 
447 OpFoldResult InsertOp::fold(ArrayRef<Attribute> operands) {
448   Attribute scalar = operands[0];
449   Attribute dest = operands[1];
450   if (scalar && dest)
451     if (auto splatDest = dest.dyn_cast<SplatElementsAttr>())
452       if (scalar == splatDest.getSplatValue<Attribute>())
453         return dest;
454   return {};
455 }
456 
457 //===----------------------------------------------------------------------===//
458 // GenerateOp
459 //===----------------------------------------------------------------------===//
460 
461 static LogicalResult verify(GenerateOp op) {
462   // Ensure that the tensor type has as many dynamic dimensions as are specified
463   // by the operands.
464   RankedTensorType resultTy = op.getType().cast<RankedTensorType>();
465   if (op.getNumOperands() != resultTy.getNumDynamicDims())
466     return op.emitError("must have as many index operands as dynamic extents "
467                         "in the result type");
468 
469   // Ensure that region arguments span the index space.
470   if (!llvm::all_of(op.body().getArgumentTypes(),
471                     [](Type ty) { return ty.isIndex(); }))
472     return op.emitError("all body arguments must be index");
473   if (op.body().getNumArguments() != resultTy.getRank())
474     return op.emitError("must have one body argument per input dimension");
475 
476   // Ensure that the region yields an element of the right type.
477   auto yieldOp =
478       llvm::cast<YieldOp>(op.body().getBlocks().front().getTerminator());
479 
480   if (yieldOp.value().getType() != resultTy.getElementType())
481     return op.emitOpError(
482         "body must be terminated with a `yield` operation of the tensor "
483         "element type");
484 
485   return success();
486 }
487 
488 void GenerateOp::build(
489     OpBuilder &b, OperationState &result, Type resultTy,
490     ValueRange dynamicExtents,
491     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilder) {
492   build(b, result, resultTy, dynamicExtents);
493 
494   // Build and populate body.
495   OpBuilder::InsertionGuard guard(b);
496   Region *bodyRegion = result.regions.front().get();
497   auto rank = resultTy.cast<RankedTensorType>().getRank();
498   SmallVector<Type, 2> argumentTypes(rank, b.getIndexType());
499   SmallVector<Location, 2> argumentLocs(rank, result.location);
500   Block *bodyBlock =
501       b.createBlock(bodyRegion, bodyRegion->end(), argumentTypes, argumentLocs);
502   bodyBuilder(b, result.location, bodyBlock->getArguments());
503 }
504 
505 namespace {
506 
507 /// Canonicalizes tensor.generate operations with a constant
508 /// operand into the equivalent operation with the operand expressed in the
509 /// result type, instead. We also insert a type cast to make sure that the
510 /// resulting IR is still well-typed.
511 struct StaticTensorGenerate : public OpRewritePattern<GenerateOp> {
512   using OpRewritePattern<GenerateOp>::OpRewritePattern;
513 
514   LogicalResult matchAndRewrite(GenerateOp tensorFromElements,
515                                 PatternRewriter &rewriter) const final {
516     auto resultType =
517         tensorFromElements.getResult().getType().cast<RankedTensorType>();
518 
519     if (resultType.hasStaticShape())
520       return failure();
521 
522     SmallVector<Value, 4> newOperands;
523     SmallVector<int64_t, 4> newShape;
524     auto operandsIt = tensorFromElements.dynamicExtents().begin();
525 
526     for (int64_t dim : resultType.getShape()) {
527       if (!ShapedType::isDynamic(dim)) {
528         newShape.push_back(dim);
529         continue;
530       }
531       APInt index;
532       if (!matchPattern(*operandsIt, m_ConstantInt(&index))) {
533         newShape.push_back(ShapedType::kDynamicSize);
534         newOperands.push_back(*operandsIt++);
535         continue;
536       }
537       newShape.push_back(index.getSExtValue());
538       operandsIt++;
539     }
540 
541     if (newOperands.size() == tensorFromElements.dynamicExtents().size())
542       return failure();
543 
544     auto loc = tensorFromElements.getLoc();
545     auto newOp = rewriter.create<GenerateOp>(
546         loc, RankedTensorType::get(newShape, resultType.getElementType()),
547         newOperands);
548     rewriter.inlineRegionBefore(tensorFromElements.body(), newOp.body(),
549                                 newOp.body().begin());
550     rewriter.replaceOpWithNewOp<tensor::CastOp>(tensorFromElements, resultType,
551                                                 newOp);
552     return success();
553   }
554 };
555 
556 /// Canonicalizes the pattern of the form
557 ///
558 /// %tensor = tensor.generate %x {
559 ///   ^bb0(%arg0: index):
560 ///   <computation>
561 ///   yield %1 : index
562 /// } : tensor<?xindex>
563 /// %extracted_element = tensor.extract %tensor[%c0] : tensor<?xi32>
564 ///
565 /// to just <computation> with %arg0 replaced by %c0. We only do this if the
566 /// tensor.generate operation has no side-effects.
567 struct ExtractFromTensorGenerate : public OpRewritePattern<tensor::ExtractOp> {
568   using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern;
569 
570   LogicalResult matchAndRewrite(tensor::ExtractOp extract,
571                                 PatternRewriter &rewriter) const final {
572     auto tensorFromElements = extract.tensor().getDefiningOp<GenerateOp>();
573     if (!tensorFromElements || !wouldOpBeTriviallyDead(tensorFromElements))
574       return failure();
575 
576     BlockAndValueMapping mapping;
577     Block *body = tensorFromElements.getBody();
578     mapping.map(body->getArguments(), extract.indices());
579     for (auto &op : body->without_terminator())
580       rewriter.clone(op, mapping);
581 
582     auto yield = cast<YieldOp>(body->getTerminator());
583 
584     rewriter.replaceOp(extract, mapping.lookupOrDefault(yield.value()));
585     return success();
586   }
587 };
588 
589 /// Canonicalizes the pattern of the form
590 ///
591 /// %val = tensor.cast %source : : tensor<?xi32> to tensor<2xi32>
592 /// %extracted_element = tensor.extract %val[%c0] : tensor<2xi32>
593 ///
594 /// to
595 ///
596 /// %extracted_element = tensor.extract %source[%c0] : tensor<?xi32>
597 struct ExtractFromTensorCast : public OpRewritePattern<tensor::ExtractOp> {
598   using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern;
599 
600   LogicalResult matchAndRewrite(tensor::ExtractOp extract,
601                                 PatternRewriter &rewriter) const final {
602     auto tensorCast = extract.tensor().getDefiningOp<tensor::CastOp>();
603     if (!tensorCast)
604       return failure();
605 
606     rewriter.replaceOpWithNewOp<tensor::ExtractOp>(extract, tensorCast.source(),
607                                                    extract.indices());
608     return success();
609   }
610 };
611 
612 } // namespace
613 
614 void GenerateOp::getCanonicalizationPatterns(RewritePatternSet &results,
615                                              MLIRContext *context) {
616   // TODO: Move extract patterns to tensor::ExtractOp.
617   results.add<ExtractFromTensorGenerate, ExtractFromTensorCast,
618               StaticTensorGenerate>(context);
619 }
620 
621 //===----------------------------------------------------------------------===//
622 // RankOp
623 //===----------------------------------------------------------------------===//
624 
625 OpFoldResult RankOp::fold(ArrayRef<Attribute> operands) {
626   // Constant fold rank when the rank of the operand is known.
627   auto type = getOperand().getType();
628   auto shapedType = type.dyn_cast<ShapedType>();
629   if (shapedType && shapedType.hasRank())
630     return IntegerAttr::get(IndexType::get(getContext()), shapedType.getRank());
631   return IntegerAttr();
632 }
633 
634 //===----------------------------------------------------------------------===//
635 // ReshapeOp
636 //===----------------------------------------------------------------------===//
637 
638 static int64_t getNumElements(ShapedType type) {
639   int64_t numElements = 1;
640   for (auto dim : type.getShape())
641     numElements *= dim;
642   return numElements;
643 }
644 
645 static LogicalResult verify(ReshapeOp op) {
646   TensorType operandType = op.source().getType().cast<TensorType>();
647   TensorType resultType = op.result().getType().cast<TensorType>();
648 
649   if (operandType.getElementType() != resultType.getElementType())
650     return op.emitOpError("element types of source and destination tensor "
651                           "types should be the same");
652 
653   int64_t shapeSize =
654       op.shape().getType().cast<RankedTensorType>().getDimSize(0);
655   auto resultRankedType = resultType.dyn_cast<RankedTensorType>();
656   auto operandRankedType = operandType.dyn_cast<RankedTensorType>();
657 
658   if (resultRankedType) {
659     if (operandRankedType && resultRankedType.hasStaticShape() &&
660         operandRankedType.hasStaticShape()) {
661       if (getNumElements(operandRankedType) != getNumElements(resultRankedType))
662         return op.emitOpError("source and destination tensor should have the "
663                               "same number of elements");
664     }
665     if (ShapedType::isDynamic(shapeSize))
666       return op.emitOpError("cannot use shape operand with dynamic length to "
667                             "reshape to statically-ranked tensor type");
668     if (shapeSize != resultRankedType.getRank())
669       return op.emitOpError(
670           "length of shape operand differs from the result's tensor rank");
671   }
672   return success();
673 }
674 
675 //===----------------------------------------------------------------------===//
676 // Reassociative reshape ops
677 //===----------------------------------------------------------------------===//
678 
679 SmallVector<AffineMap, 4> CollapseShapeOp::getReassociationMaps() {
680   return getSymbolLessAffineMaps(getReassociationExprs());
681 }
682 SmallVector<ReassociationExprs, 4> CollapseShapeOp::getReassociationExprs() {
683   return convertReassociationIndicesToExprs(getContext(),
684                                             getReassociationIndices());
685 }
686 
687 SmallVector<AffineMap, 4> ExpandShapeOp::getReassociationMaps() {
688   return getSymbolLessAffineMaps(getReassociationExprs());
689 }
690 SmallVector<ReassociationExprs, 4> ExpandShapeOp::getReassociationExprs() {
691   return convertReassociationIndicesToExprs(getContext(),
692                                             getReassociationIndices());
693 }
694 
695 static void print(OpAsmPrinter &p, ExpandShapeOp op) {
696   ::mlir::printReshapeOp<ExpandShapeOp>(p, op);
697 }
698 
699 static void print(OpAsmPrinter &p, CollapseShapeOp op) {
700   ::mlir::printReshapeOp<CollapseShapeOp>(p, op);
701 }
702 
703 /// Compute the RankedTensorType obtained by applying `reassociation` to `type`.
704 static RankedTensorType
705 computeTensorReshapeCollapsedType(RankedTensorType type,
706                                   ArrayRef<AffineMap> reassociation) {
707   auto shape = type.getShape();
708   SmallVector<int64_t, 4> newShape;
709   newShape.reserve(reassociation.size());
710 
711   // Use the fact that reassociation is valid to simplify the logic: only use
712   // each map's rank.
713   assert(isReassociationValid(reassociation) && "invalid reassociation");
714   unsigned currentDim = 0;
715   for (AffineMap m : reassociation) {
716     unsigned dim = m.getNumResults();
717     auto band = shape.slice(currentDim, dim);
718     int64_t size = 1;
719     if (llvm::is_contained(band, ShapedType::kDynamicSize))
720       size = ShapedType::kDynamicSize;
721     else
722       for (unsigned d = 0; d < dim; ++d)
723         size *= shape[currentDim + d];
724     newShape.push_back(size);
725     currentDim += dim;
726   }
727 
728   return RankedTensorType::get(newShape, type.getElementType());
729 }
730 
731 void CollapseShapeOp::build(OpBuilder &b, OperationState &result, Value src,
732                             ArrayRef<ReassociationIndices> reassociation,
733                             ArrayRef<NamedAttribute> attrs) {
734   auto resultType = computeTensorReshapeCollapsedType(
735       src.getType().cast<RankedTensorType>(),
736       getSymbolLessAffineMaps(
737           convertReassociationIndicesToExprs(b.getContext(), reassociation)));
738   build(b, result, resultType, src, attrs);
739   result.addAttribute(getReassociationAttrName(),
740                       getReassociationIndicesAttribute(b, reassociation));
741 }
742 
743 void ExpandShapeOp::build(OpBuilder &b, OperationState &result, Value src,
744                           ArrayRef<ReassociationIndices> reassociation,
745                           ArrayRef<NamedAttribute> attrs) {
746   auto resultType = computeTensorReshapeCollapsedType(
747       src.getType().cast<RankedTensorType>(),
748       getSymbolLessAffineMaps(
749           convertReassociationIndicesToExprs(b.getContext(), reassociation)));
750   build(b, result, resultType, src, attrs);
751   result.addAttribute(getReassociationAttrName(),
752                       getReassociationIndicesAttribute(b, reassociation));
753 }
754 
755 template <typename TensorReshapeOp, bool isExpansion = std::is_same<
756                                         TensorReshapeOp, ExpandShapeOp>::value>
757 static LogicalResult verifyTensorReshapeOp(TensorReshapeOp op,
758                                            RankedTensorType expandedType,
759                                            RankedTensorType collapsedType) {
760   if (failed(
761           verifyReshapeLikeTypes(op, expandedType, collapsedType, isExpansion)))
762     return failure();
763 
764   auto maps = op.getReassociationMaps();
765   RankedTensorType expectedType =
766       computeTensorReshapeCollapsedType(expandedType, maps);
767   if (collapsedType != expectedType)
768     return op.emitOpError("expected collapsed type to be ")
769            << expectedType << ", but got " << collapsedType;
770   return success();
771 }
772 
773 static LogicalResult verify(ExpandShapeOp op) {
774   return verifyTensorReshapeOp(op, op.getResultType(), op.getSrcType());
775 }
776 
777 static LogicalResult verify(CollapseShapeOp op) {
778   return verifyTensorReshapeOp(op, op.getSrcType(), op.getResultType());
779 }
780 
781 namespace {
782 /// Reshape of a splat constant can be replaced with a constant of the result
783 /// type.
784 template <typename TensorReshapeOp>
785 struct FoldReshapeWithConstant : OpRewritePattern<TensorReshapeOp> {
786   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
787   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
788                                 PatternRewriter &rewriter) const override {
789     DenseElementsAttr attr;
790     if (!matchPattern(reshapeOp.src(), m_Constant(&attr)))
791       return failure();
792     if (!attr || !attr.isSplat())
793       return failure();
794     DenseElementsAttr newAttr = DenseElementsAttr::getFromRawBuffer(
795         reshapeOp.getResultType(), attr.getRawData(), true);
796     rewriter.replaceOpWithNewOp<arith::ConstantOp>(reshapeOp, newAttr);
797     return success();
798   }
799 };
800 
801 } // namespace
802 
803 void ExpandShapeOp::getCanonicalizationPatterns(RewritePatternSet &results,
804                                                 MLIRContext *context) {
805   results.add<CollapseReshapeOps<ExpandShapeOp>,
806               CollapseMixedReshapeOps<ExpandShapeOp, CollapseShapeOp>,
807               FoldReshapeWithConstant<ExpandShapeOp>>(context);
808 }
809 
810 void CollapseShapeOp::getCanonicalizationPatterns(RewritePatternSet &results,
811                                                   MLIRContext *context) {
812   results.add<CollapseReshapeOps<CollapseShapeOp>,
813               CollapseMixedReshapeOps<CollapseShapeOp, ExpandShapeOp>,
814               FoldReshapeWithConstant<CollapseShapeOp>>(context);
815 }
816 
817 OpFoldResult ExpandShapeOp::fold(ArrayRef<Attribute> operands) {
818   return foldReshapeOp<ExpandShapeOp, CollapseShapeOp>(*this, operands);
819 }
820 OpFoldResult CollapseShapeOp::fold(ArrayRef<Attribute> operands) {
821   return foldReshapeOp<CollapseShapeOp, ExpandShapeOp>(*this, operands);
822 }
823 
824 //===----------------------------------------------------------------------===//
825 // ExtractSliceOp
826 //===----------------------------------------------------------------------===//
827 
828 /// An extract_slice op result type can be fully inferred from the source type
829 /// and the static representation of offsets, sizes and strides. Special
830 /// sentinels encode the dynamic case.
831 RankedTensorType ExtractSliceOp::inferResultType(
832     RankedTensorType sourceRankedTensorType, ArrayRef<int64_t> staticOffsets,
833     ArrayRef<int64_t> staticSizes, ArrayRef<int64_t> staticStrides) {
834   // An extract_slice op may specify only a leading subset of offset/sizes/
835   // strides in which case we complete with offset=0, sizes from memref type and
836   // strides=1.
837   unsigned rank = sourceRankedTensorType.getRank();
838   (void)rank;
839   assert(staticSizes.size() == rank &&
840          "unexpected staticSizes not equal to rank of source");
841   return RankedTensorType::get(staticSizes,
842                                sourceRankedTensorType.getElementType());
843 }
844 
845 RankedTensorType ExtractSliceOp::inferResultType(
846     RankedTensorType sourceRankedTensorType, ArrayRef<OpFoldResult> offsets,
847     ArrayRef<OpFoldResult> sizes, ArrayRef<OpFoldResult> strides) {
848   SmallVector<int64_t> staticOffsets, staticSizes, staticStrides;
849   SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides;
850   dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets,
851                              ShapedType::kDynamicStrideOrOffset);
852   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
853                              ShapedType::kDynamicSize);
854   dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides,
855                              ShapedType::kDynamicStrideOrOffset);
856   return ExtractSliceOp::inferResultType(sourceRankedTensorType, staticOffsets,
857                                          staticSizes, staticStrides);
858 }
859 
860 /// An extract_slice op result type can be fully inferred from the source type
861 /// and the static representation of offsets, sizes and strides. Special
862 /// sentinels encode the dynamic case.
863 RankedTensorType ExtractSliceOp::inferRankReducedResultType(
864     unsigned resultRank, RankedTensorType sourceRankedTensorType,
865     ArrayRef<int64_t> offsets, ArrayRef<int64_t> sizes,
866     ArrayRef<int64_t> strides) {
867   auto inferredType =
868       inferResultType(sourceRankedTensorType, offsets, sizes, strides)
869           .cast<RankedTensorType>();
870   int rankDiff = inferredType.getRank() - resultRank;
871   if (rankDiff > 0) {
872     auto shape = inferredType.getShape();
873     llvm::SmallDenseSet<unsigned> dimsToProject;
874     mlir::getPositionsOfShapeOne(rankDiff, shape, dimsToProject);
875     SmallVector<int64_t> projectedShape;
876     for (unsigned pos = 0, e = shape.size(); pos < e; ++pos)
877       if (!dimsToProject.contains(pos))
878         projectedShape.push_back(shape[pos]);
879     inferredType =
880         RankedTensorType::get(projectedShape, inferredType.getElementType());
881   }
882   return inferredType;
883 }
884 
885 RankedTensorType ExtractSliceOp::inferRankReducedResultType(
886     unsigned resultRank, RankedTensorType sourceRankedTensorType,
887     ArrayRef<OpFoldResult> offsets, ArrayRef<OpFoldResult> sizes,
888     ArrayRef<OpFoldResult> strides) {
889   SmallVector<int64_t> staticOffsets, staticSizes, staticStrides;
890   SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides;
891   dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets,
892                              ShapedType::kDynamicStrideOrOffset);
893   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
894                              ShapedType::kDynamicSize);
895   dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides,
896                              ShapedType::kDynamicStrideOrOffset);
897   return ExtractSliceOp::inferRankReducedResultType(
898       resultRank, sourceRankedTensorType, staticOffsets, staticSizes,
899       staticStrides);
900 }
901 
902 /// Build an ExtractSliceOp with mixed static and dynamic entries and custom
903 /// result type. If the type passed is nullptr, it is inferred.
904 void ExtractSliceOp::build(OpBuilder &b, OperationState &result,
905                            RankedTensorType resultType, Value source,
906                            ArrayRef<OpFoldResult> offsets,
907                            ArrayRef<OpFoldResult> sizes,
908                            ArrayRef<OpFoldResult> strides,
909                            ArrayRef<NamedAttribute> attrs) {
910   SmallVector<int64_t> staticOffsets, staticSizes, staticStrides;
911   SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides;
912   dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets,
913                              ShapedType::kDynamicStrideOrOffset);
914   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
915                              ShapedType::kDynamicSize);
916   dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides,
917                              ShapedType::kDynamicStrideOrOffset);
918   auto sourceRankedTensorType = source.getType().cast<RankedTensorType>();
919   // Structuring implementation this way avoids duplication between builders.
920   if (!resultType) {
921     resultType =
922         ExtractSliceOp::inferResultType(sourceRankedTensorType, staticOffsets,
923                                         staticSizes, staticStrides)
924             .cast<RankedTensorType>();
925   }
926   build(b, result, resultType, source, dynamicOffsets, dynamicSizes,
927         dynamicStrides, b.getI64ArrayAttr(staticOffsets),
928         b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides));
929   result.addAttributes(attrs);
930 }
931 
932 /// Build an ExtractSliceOp with mixed static and dynamic entries and inferred
933 /// result type.
934 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, Value source,
935                            ArrayRef<OpFoldResult> offsets,
936                            ArrayRef<OpFoldResult> sizes,
937                            ArrayRef<OpFoldResult> strides,
938                            ArrayRef<NamedAttribute> attrs) {
939   build(b, result, RankedTensorType(), source, offsets, sizes, strides, attrs);
940 }
941 
942 /// Build an ExtractSliceOp with dynamic entries and custom result type. If the
943 /// type passed is nullptr, it is inferred.
944 void ExtractSliceOp::build(OpBuilder &b, OperationState &result,
945                            RankedTensorType resultType, Value source,
946                            ValueRange offsets, ValueRange sizes,
947                            ValueRange strides, ArrayRef<NamedAttribute> attrs) {
948   SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>(
949       llvm::map_range(offsets, [](Value v) -> OpFoldResult { return v; }));
950   SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>(
951       llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; }));
952   SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>(
953       llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; }));
954   build(b, result, resultType, source, offsetValues, sizeValues, strideValues);
955 }
956 
957 /// Build an ExtractSliceOp with dynamic entries and inferred result type.
958 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, Value source,
959                            ValueRange offsets, ValueRange sizes,
960                            ValueRange strides, ArrayRef<NamedAttribute> attrs) {
961   build(b, result, RankedTensorType(), source, offsets, sizes, strides, attrs);
962 }
963 
964 template <typename OpTy>
965 static LogicalResult produceSliceErrorMsg(SliceVerificationResult result,
966                                           OpTy op, Type expectedType) {
967   auto memrefType = expectedType.cast<ShapedType>();
968   switch (result) {
969   case SliceVerificationResult::Success:
970     return success();
971   case SliceVerificationResult::RankTooLarge:
972     return op.emitError("expected rank to be smaller or equal to ")
973            << "the other rank. ";
974   case SliceVerificationResult::SizeMismatch:
975     return op.emitError("expected type to be ")
976            << expectedType << " or a rank-reduced version. (size mismatch) ";
977   case SliceVerificationResult::ElemTypeMismatch:
978     return op.emitError("expected element type to be ")
979            << memrefType.getElementType();
980   default:
981     llvm_unreachable("unexpected extract_slice op verification result");
982   }
983 }
984 
985 /// Verifier for ExtractSliceOp.
986 static LogicalResult verify(ExtractSliceOp op) {
987   // Verify result type against inferred type.
988   auto expectedType =
989       ExtractSliceOp::inferResultType(op.getSourceType(), op.getMixedOffsets(),
990                                       op.getMixedSizes(), op.getMixedStrides());
991   auto result =
992       isRankReducedType(expectedType.cast<ShapedType>(), op.getType());
993   return produceSliceErrorMsg(result, op, expectedType);
994 }
995 
996 /// Infer the canonical type of the result of an extract_slice op. Returns a
997 /// type with rank `resultRank` that is either the rank of the rank-reduced
998 /// type, or the non-rank-reduced type.
999 static RankedTensorType
1000 getCanonicalSliceResultType(unsigned resultRank, RankedTensorType sourceType,
1001                             ArrayRef<OpFoldResult> mixedOffsets,
1002                             ArrayRef<OpFoldResult> mixedSizes,
1003                             ArrayRef<OpFoldResult> mixedStrides) {
1004   auto resultType =
1005       ExtractSliceOp::inferRankReducedResultType(
1006           resultRank, sourceType, mixedOffsets, mixedSizes, mixedStrides)
1007           .cast<RankedTensorType>();
1008   if (resultType.getRank() != resultRank) {
1009     resultType = ExtractSliceOp::inferResultType(sourceType, mixedOffsets,
1010                                                  mixedSizes, mixedStrides)
1011                      .cast<RankedTensorType>();
1012   }
1013   return resultType;
1014 }
1015 
1016 llvm::SmallDenseSet<unsigned> ExtractSliceOp::getDroppedDims() {
1017   llvm::SmallDenseSet<unsigned> droppedDims;
1018   ArrayRef<int64_t> resultShape = getType().getShape();
1019   SmallVector<OpFoldResult> mixedSizes = getMixedSizes();
1020   unsigned shapePos = 0;
1021   for (const auto &size : enumerate(mixedSizes)) {
1022     Optional<int64_t> sizeVal = getConstantIntValue(size.value());
1023     // If the size is not 1, or if the current matched dimension of the result
1024     // is the same static shape as the size value (which is 1), then the
1025     // dimension is preserved.
1026     if (!sizeVal || sizeVal.getValue() != 1 ||
1027         (shapePos < resultShape.size() && resultShape[shapePos] == 1)) {
1028       shapePos++;
1029       continue;
1030     }
1031     droppedDims.insert(size.index());
1032   }
1033   return droppedDims;
1034 }
1035 
1036 LogicalResult ExtractSliceOp::reifyResultShapes(
1037     OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) {
1038   reifiedReturnShapes.resize(1);
1039   reifiedReturnShapes[0].reserve(getType().getRank());
1040   SmallVector<OpFoldResult> mixedSizes = getMixedSizes();
1041   llvm::SmallDenseSet<unsigned> droppedDims = getDroppedDims();
1042   Location loc = getLoc();
1043   for (const auto &size : enumerate(mixedSizes)) {
1044     if (droppedDims.count(size.index()))
1045       continue;
1046     if (auto attr = size.value().dyn_cast<Attribute>()) {
1047       reifiedReturnShapes[0].push_back(builder.create<arith::ConstantIndexOp>(
1048           loc, attr.cast<IntegerAttr>().getInt()));
1049       continue;
1050     }
1051     reifiedReturnShapes[0].push_back(size.value().get<Value>());
1052   }
1053   return success();
1054 }
1055 
1056 namespace {
1057 /// Pattern to rewrite an extract_slice op with tensor::Cast arguments.
1058 /// This essentially pushes memref_cast past its consuming slice when
1059 /// `canFoldIntoConsumerOp` is true.
1060 ///
1061 /// Example:
1062 /// ```
1063 ///   %0 = tensor.cast %V : tensor<16x16xf32> to tensor<?x?xf32>
1064 ///   %1 = tensor.extract_slice %0[0, 0][3, 4][1, 1] : tensor<?x?xf32> to
1065 ///   tensor<3x4xf32>
1066 /// ```
1067 /// is rewritten into:
1068 /// ```
1069 ///   %0 = tensor.extract_slice %V[0, 0][3, 4][1, 1] : tensor<16x16xf32> to
1070 ///   tensor<3x4xf32> %1 = tensor.cast %0: tensor<3x4xf32> to tensor<3x4xf32>
1071 /// ```
1072 class ExtractSliceOpCastFolder final : public OpRewritePattern<ExtractSliceOp> {
1073 public:
1074   using OpRewritePattern<ExtractSliceOp>::OpRewritePattern;
1075 
1076   LogicalResult matchAndRewrite(ExtractSliceOp sliceOp,
1077                                 PatternRewriter &rewriter) const override {
1078     // Any constant operand, just return to let SubViewOpConstantFolder kick in.
1079     if (llvm::any_of(sliceOp.getOperands(), [](Value operand) {
1080           return matchPattern(operand, matchConstantIndex());
1081         }))
1082       return failure();
1083 
1084     auto castOp = sliceOp.source().getDefiningOp<tensor::CastOp>();
1085     if (!castOp)
1086       return failure();
1087 
1088     if (!canFoldIntoConsumerOp(castOp))
1089       return failure();
1090 
1091     /// Deduce the type of the result to use for the canonicalized operation.
1092     RankedTensorType resultType = getCanonicalSliceResultType(
1093         sliceOp.getType().getRank(), sliceOp.getSourceType(),
1094         sliceOp.getMixedOffsets(), sliceOp.getMixedSizes(),
1095         sliceOp.getMixedStrides());
1096     Value newSlice = rewriter.create<ExtractSliceOp>(
1097         sliceOp.getLoc(), resultType, castOp.source(), sliceOp.offsets(),
1098         sliceOp.sizes(), sliceOp.strides(), sliceOp.static_offsets(),
1099         sliceOp.static_sizes(), sliceOp.static_strides());
1100     rewriter.replaceOpWithNewOp<tensor::CastOp>(sliceOp, sliceOp.getType(),
1101                                                 newSlice);
1102     return success();
1103   }
1104 };
1105 } // namespace
1106 
1107 /// Return the canonical type of the result of an extract_slice op.
1108 struct SliceReturnTypeCanonicalizer {
1109   RankedTensorType operator()(ExtractSliceOp op,
1110                               ArrayRef<OpFoldResult> mixedOffsets,
1111                               ArrayRef<OpFoldResult> mixedSizes,
1112                               ArrayRef<OpFoldResult> mixedStrides) {
1113     return getCanonicalSliceResultType(op.getType().getRank(),
1114                                        op.getSourceType(), mixedOffsets,
1115                                        mixedSizes, mixedStrides);
1116   }
1117 };
1118 
1119 /// A canonicalizer wrapper to replace ExtractSliceOps.
1120 struct SliceCanonicalizer {
1121   void operator()(PatternRewriter &rewriter, ExtractSliceOp op,
1122                   ExtractSliceOp newOp) {
1123     Value replacement = newOp.getResult();
1124     if (replacement.getType() != op.getType())
1125       replacement = rewriter.create<tensor::CastOp>(op.getLoc(), op.getType(),
1126                                                     replacement);
1127     rewriter.replaceOp(op, replacement);
1128   }
1129 };
1130 
1131 void ExtractSliceOp::getCanonicalizationPatterns(RewritePatternSet &results,
1132                                                  MLIRContext *context) {
1133   results.add<
1134       OpWithOffsetSizesAndStridesConstantArgumentFolder<
1135           ExtractSliceOp, SliceReturnTypeCanonicalizer, SliceCanonicalizer>,
1136       ExtractSliceOpCastFolder>(context);
1137 }
1138 
1139 //
1140 static LogicalResult
1141 foldIdentityOffsetSizeAndStrideOpInterface(OffsetSizeAndStrideOpInterface op,
1142                                            ShapedType shapedType) {
1143   OpBuilder b(op.getContext());
1144   for (OpFoldResult ofr : op.getMixedOffsets())
1145     if (getConstantIntValue(ofr) != static_cast<int64_t>(0))
1146       return failure();
1147   // Rank-reducing noops only need to inspect the leading dimensions: llvm::zip
1148   // is appropriate.
1149   auto shape = shapedType.getShape();
1150   for (auto it : llvm::zip(op.getMixedSizes(), shape))
1151     if (getConstantIntValue(std::get<0>(it)) != std::get<1>(it))
1152       return failure();
1153   for (OpFoldResult ofr : op.getMixedStrides())
1154     if (getConstantIntValue(ofr) != static_cast<int64_t>(1))
1155       return failure();
1156   return success();
1157 }
1158 
1159 /// If we have an ExtractSliceOp consuming an InsertSliceOp with the same slice,
1160 /// we can return the InsertSliceOp's source directly.
1161 // TODO: This only checks the immediate producer; extend to go up the
1162 // insert/extract chain if the slices are disjoint.
1163 static Value foldExtractAfterInsertSlice(ExtractSliceOp extractOp) {
1164   auto insertOp = extractOp.source().getDefiningOp<InsertSliceOp>();
1165 
1166   auto isSame = [](OpFoldResult a, OpFoldResult b) { return a == b; };
1167   if (insertOp && insertOp.source().getType() == extractOp.getType() &&
1168       insertOp.isSameAs(extractOp, isSame))
1169     return insertOp.source();
1170 
1171   return {};
1172 }
1173 
1174 OpFoldResult ExtractSliceOp::fold(ArrayRef<Attribute>) {
1175   if (getSourceType() == getType() &&
1176       succeeded(foldIdentityOffsetSizeAndStrideOpInterface(*this, getType())))
1177     return this->source();
1178   if (Value slice = foldExtractAfterInsertSlice(*this))
1179     return slice;
1180   return OpFoldResult();
1181 }
1182 
1183 Value mlir::tensor::createCanonicalRankReducingExtractSliceOp(
1184     OpBuilder &b, Location loc, Value tensor, RankedTensorType targetType) {
1185   auto rankedTensorType = tensor.getType().cast<RankedTensorType>();
1186   unsigned rank = rankedTensorType.getRank();
1187   auto shape = rankedTensorType.getShape();
1188   SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0));
1189   SmallVector<OpFoldResult> sizes;
1190   for (unsigned i = 0, e = rank; i < e; ++i) {
1191     OpFoldResult dim;
1192     if (rankedTensorType.isDynamicDim(i))
1193       dim = b.createOrFold<tensor::DimOp>(
1194           loc, tensor, b.create<arith::ConstantIndexOp>(loc, i));
1195     else
1196       dim = b.getIndexAttr(shape[i]);
1197     sizes.push_back(dim);
1198   }
1199   SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1));
1200   return b.createOrFold<tensor::ExtractSliceOp>(loc, targetType, tensor,
1201                                                 offsets, sizes, strides);
1202 }
1203 
1204 //===----------------------------------------------------------------------===//
1205 // InsertSliceOp
1206 //===----------------------------------------------------------------------===//
1207 
1208 // Build a InsertSliceOp with mixed static and dynamic entries.
1209 void InsertSliceOp::build(OpBuilder &b, OperationState &result, Value source,
1210                           Value dest, ArrayRef<OpFoldResult> offsets,
1211                           ArrayRef<OpFoldResult> sizes,
1212                           ArrayRef<OpFoldResult> strides,
1213                           ArrayRef<NamedAttribute> attrs) {
1214   SmallVector<int64_t> staticOffsets, staticSizes, staticStrides;
1215   SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides;
1216   dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets,
1217                              ShapedType::kDynamicStrideOrOffset);
1218   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
1219                              ShapedType::kDynamicSize);
1220   dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides,
1221                              ShapedType::kDynamicStrideOrOffset);
1222   build(b, result, dest.getType(), source, dest, dynamicOffsets, dynamicSizes,
1223         dynamicStrides, b.getI64ArrayAttr(staticOffsets),
1224         b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides));
1225   result.addAttributes(attrs);
1226 }
1227 
1228 // Build a InsertSliceOp with dynamic entries.
1229 void InsertSliceOp::build(OpBuilder &b, OperationState &result, Value source,
1230                           Value dest, ValueRange offsets, ValueRange sizes,
1231                           ValueRange strides, ArrayRef<NamedAttribute> attrs) {
1232   SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>(
1233       llvm::map_range(offsets, [](Value v) -> OpFoldResult { return v; }));
1234   SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>(
1235       llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; }));
1236   SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>(
1237       llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; }));
1238   build(b, result, source, dest, offsetValues, sizeValues, strideValues);
1239 }
1240 
1241 /// Verifier for InsertSliceOp.
1242 static LogicalResult verify(InsertSliceOp op) {
1243   // insert_slice is the inverse of extract_slice, use the same type inference.
1244   auto expectedType = ExtractSliceOp::inferRankReducedResultType(
1245       op.getSourceType().getRank(), op.getType(),
1246       extractFromI64ArrayAttr(op.static_offsets()),
1247       extractFromI64ArrayAttr(op.static_sizes()),
1248       extractFromI64ArrayAttr(op.static_strides()));
1249   auto result =
1250       isRankReducedType(expectedType.cast<ShapedType>(), op.getSourceType());
1251   return produceSliceErrorMsg(result, op, expectedType);
1252 }
1253 
1254 /// If we have two consecutive InsertSliceOp writing to the same slice, we
1255 /// can mutate the second InsertSliceOp's destination to the first one's.
1256 ///
1257 /// Example:
1258 ///
1259 /// ```mlir
1260 ///   %0 = tensor.insert_slice %slice0 into %input[0, 0] [64, 64] [1, 1]
1261 ///   %1 = tensor.insert_slice %slice1 into %0[0, 0] [64, 64] [1, 1]
1262 /// ```
1263 ///
1264 /// folds into:
1265 ///
1266 /// ```mlir
1267 ///   %1 = tensor.insert_slice %slice1 into %input[0, 0] [64, 64] [1, 1]
1268 /// ```
1269 static LogicalResult foldInsertAfterInsertSlice(InsertSliceOp insertOp) {
1270   auto prevInsertOp = insertOp.dest().getDefiningOp<InsertSliceOp>();
1271 
1272   auto isSame = [](OpFoldResult a, OpFoldResult b) { return a == b; };
1273   if (!prevInsertOp ||
1274       prevInsertOp.source().getType() != insertOp.source().getType() ||
1275       !prevInsertOp.isSameAs(insertOp, isSame))
1276     return failure();
1277 
1278   insertOp.destMutable().assign(prevInsertOp.dest());
1279   return success();
1280 }
1281 
1282 OpFoldResult InsertSliceOp::fold(ArrayRef<Attribute>) {
1283   if (getSourceType().hasStaticShape() && getType().hasStaticShape() &&
1284       getSourceType() == getType() &&
1285       succeeded(foldIdentityOffsetSizeAndStrideOpInterface(*this, getType())))
1286     return this->source();
1287   if (succeeded(foldInsertAfterInsertSlice(*this)))
1288     return getResult();
1289   return OpFoldResult();
1290 }
1291 
1292 LogicalResult InsertSliceOp::reifyResultShapes(
1293     OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) {
1294   reifiedReturnShapes.resize(1, SmallVector<Value>(getType().getRank()));
1295   for (auto dim : llvm::seq<int64_t>(0, getType().getRank())) {
1296     reifiedReturnShapes[0][dim] =
1297         builder.createOrFold<tensor::DimOp>(getLoc(), dest(), dim);
1298   }
1299   return success();
1300 }
1301 
1302 namespace {
1303 /// Pattern to rewrite a insert_slice op with constant arguments.
1304 class InsertSliceOpConstantArgumentFolder final
1305     : public OpRewritePattern<InsertSliceOp> {
1306 public:
1307   using OpRewritePattern<InsertSliceOp>::OpRewritePattern;
1308 
1309   LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp,
1310                                 PatternRewriter &rewriter) const override {
1311     // No constant operand, just return.
1312     if (llvm::none_of(insertSliceOp.getOperands(), [](Value operand) {
1313           return matchPattern(operand, matchConstantIndex());
1314         }))
1315       return failure();
1316 
1317     // At least one of offsets/sizes/strides is a new constant.
1318     // Form the new list of operands and constant attributes from the
1319     // existing.
1320     SmallVector<OpFoldResult> mixedOffsets(insertSliceOp.getMixedOffsets());
1321     SmallVector<OpFoldResult> mixedSizes(insertSliceOp.getMixedSizes());
1322     SmallVector<OpFoldResult> mixedStrides(insertSliceOp.getMixedStrides());
1323     canonicalizeSubViewPart(mixedOffsets, ShapedType::isDynamicStrideOrOffset);
1324     canonicalizeSubViewPart(mixedSizes, ShapedType::isDynamic);
1325     canonicalizeSubViewPart(mixedStrides, ShapedType::isDynamicStrideOrOffset);
1326 
1327     // Create the new op in canonical form.
1328     auto sourceType = ExtractSliceOp::inferRankReducedResultType(
1329         insertSliceOp.getSourceType().getRank(), insertSliceOp.getType(),
1330         mixedOffsets, mixedSizes, mixedStrides);
1331     Value toInsert = insertSliceOp.source();
1332     if (sourceType != insertSliceOp.getSourceType())
1333       toInsert = rewriter.create<tensor::CastOp>(insertSliceOp.getLoc(),
1334                                                  sourceType, toInsert);
1335     rewriter.replaceOpWithNewOp<InsertSliceOp>(
1336         insertSliceOp, toInsert, insertSliceOp.dest(), mixedOffsets, mixedSizes,
1337         mixedStrides);
1338     return success();
1339   }
1340 };
1341 
1342 /// Fold tensor_casts with insert_slice operations. If the source or destination
1343 /// tensor is a tensor_cast that removes static type information, the cast is
1344 /// folded into the insert_slice operation. E.g.:
1345 ///
1346 /// ```mlir
1347 ///   %1 = tensor.cast %0 : tensor<8x16xf32> to tensor<?x?xf32>
1348 ///   %2 = tensor.insert_slice %1 into ... : tensor<?x?xf32> into ...
1349 /// ```
1350 ///
1351 /// folds into:
1352 ///
1353 /// ```mlir
1354 ///   %2 = tensor.insert_slice %0 into ... : tensor<8x16xf32> into ...
1355 /// ```
1356 ///
1357 /// Note: When folding a cast on the destination tensor, the result of the
1358 /// insert_slice operation is casted to ensure that the type of the result did
1359 /// not change.
1360 struct InsertSliceOpCastFolder final : public OpRewritePattern<InsertSliceOp> {
1361   using OpRewritePattern<InsertSliceOp>::OpRewritePattern;
1362 
1363   LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp,
1364                                 PatternRewriter &rewriter) const override {
1365     if (llvm::any_of(insertSliceOp.getOperands(), [](Value operand) {
1366           return matchPattern(operand, matchConstantIndex());
1367         }))
1368       return failure();
1369 
1370     auto getSourceOfCastOp = [](Value v) -> Optional<Value> {
1371       auto castOp = v.getDefiningOp<tensor::CastOp>();
1372       if (!castOp || !canFoldIntoConsumerOp(castOp))
1373         return llvm::None;
1374       return castOp.source();
1375     };
1376     Optional<Value> sourceCastSource =
1377         getSourceOfCastOp(insertSliceOp.source());
1378     Optional<Value> destCastSource = getSourceOfCastOp(insertSliceOp.dest());
1379     if (!sourceCastSource && !destCastSource)
1380       return failure();
1381 
1382     Value replacement = rewriter.create<InsertSliceOp>(
1383         insertSliceOp.getLoc(),
1384         (sourceCastSource ? *sourceCastSource : insertSliceOp.source()),
1385         (destCastSource ? *destCastSource : insertSliceOp.dest()),
1386         insertSliceOp.getMixedOffsets(), insertSliceOp.getMixedSizes(),
1387         insertSliceOp.getMixedStrides());
1388 
1389     if (replacement.getType() != insertSliceOp.getType()) {
1390       replacement = rewriter.create<tensor::CastOp>(
1391           insertSliceOp.getLoc(), insertSliceOp.getType(), replacement);
1392     }
1393     rewriter.replaceOp(insertSliceOp, replacement);
1394     return success();
1395   }
1396 };
1397 
1398 /// If additional static type information can be deduced from a insert_slice's
1399 /// size operands, insert an explicit cast of the op's source operand. This
1400 /// enables other canonicalization patterns that are matching for tensor_cast
1401 /// ops such as `ForOpTensorCastFolder` in SCF.
1402 ///
1403 /// Example:
1404 ///
1405 /// ```mlir
1406 ///   %r = tensor.insert_slice %0 into %1[...] [64, 64] [1, 1]
1407 ///       : tensor<?x?xf32> into ...
1408 /// ```
1409 ///
1410 /// folds into:
1411 ///
1412 /// ```mlir
1413 ///   %tmp = tensor.cast %0 : tensor<?x?xf32> to tensor<64x64xf32>
1414 ///   %r = tensor.insert_slice %tmp into %1[...] [64, 64] [1, 1]
1415 ///       : tensor<64x64xf32> into ...
1416 /// ```
1417 struct InsertSliceOpSourceCastInserter final
1418     : public OpRewritePattern<InsertSliceOp> {
1419   using OpRewritePattern<InsertSliceOp>::OpRewritePattern;
1420 
1421   LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp,
1422                                 PatternRewriter &rewriter) const override {
1423     RankedTensorType srcType = insertSliceOp.getSourceType();
1424     if (srcType.getRank() != insertSliceOp.getType().getRank())
1425       return failure();
1426     SmallVector<int64_t> newSrcShape(srcType.getShape().begin(),
1427                                      srcType.getShape().end());
1428     for (int64_t i = 0; i < srcType.getRank(); ++i) {
1429       if (Optional<int64_t> constInt =
1430               getConstantIntValue(insertSliceOp.getMixedSizes()[i]))
1431         newSrcShape[i] = *constInt;
1432     }
1433 
1434     RankedTensorType newSrcType =
1435         RankedTensorType::get(newSrcShape, srcType.getElementType());
1436     if (srcType == newSrcType ||
1437         !preservesStaticInformation(srcType, newSrcType) ||
1438         !tensor::CastOp::areCastCompatible(srcType, newSrcType))
1439       return failure();
1440 
1441     // newSrcType is:
1442     //   1) Different from srcType.
1443     //   2) "More static" than srcType.
1444     //   3) Cast-compatible with srcType.
1445     // Insert the cast.
1446     Value cast = rewriter.create<tensor::CastOp>(
1447         insertSliceOp.getLoc(), newSrcType, insertSliceOp.source());
1448     rewriter.replaceOpWithNewOp<InsertSliceOp>(
1449         insertSliceOp, cast, insertSliceOp.dest(),
1450         insertSliceOp.getMixedOffsets(), insertSliceOp.getMixedSizes(),
1451         insertSliceOp.getMixedStrides());
1452     return success();
1453   }
1454 };
1455 } // namespace
1456 
1457 void InsertSliceOp::getCanonicalizationPatterns(RewritePatternSet &results,
1458                                                 MLIRContext *context) {
1459   results.add<InsertSliceOpConstantArgumentFolder, InsertSliceOpCastFolder,
1460               InsertSliceOpSourceCastInserter>(context);
1461 }
1462 
1463 Value mlir::tensor::createCanonicalRankReducingInsertSliceOp(OpBuilder &b,
1464                                                              Location loc,
1465                                                              Value tensor,
1466                                                              Value dest) {
1467   auto rankedTensorType = dest.getType().cast<RankedTensorType>();
1468   unsigned rank = rankedTensorType.getRank();
1469   auto shape = rankedTensorType.getShape();
1470   SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0));
1471   SmallVector<OpFoldResult> sizes;
1472   for (unsigned i = 0, e = rank; i < e; ++i) {
1473     OpFoldResult dim;
1474     if (rankedTensorType.isDynamicDim(i))
1475       dim = b.createOrFold<tensor::DimOp>(
1476           loc, dest, b.create<arith::ConstantIndexOp>(loc, i));
1477     else
1478       dim = b.getIndexAttr(shape[i]);
1479     sizes.push_back(dim);
1480   }
1481   SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1));
1482   return b.createOrFold<tensor::InsertSliceOp>(loc, tensor, dest, offsets,
1483                                                sizes, strides);
1484 }
1485 
1486 //===----------------------------------------------------------------------===//
1487 // PadOp
1488 //===----------------------------------------------------------------------===//
1489 
1490 // TODO: Replace custom<InferType> directive with AllTypesMatch as soon as it
1491 // supports optional types.
1492 void printInferType(OpAsmPrinter &printer, Operation *op, Value optOperand,
1493                     Type typeToInfer, Type typeToInferFrom) {}
1494 
1495 ParseResult parseInferType(OpAsmParser &parser,
1496                            Optional<OpAsmParser::OperandType> optOperand,
1497                            Type &typeToInfer, Type typeToInferFrom) {
1498   if (optOperand)
1499     typeToInfer = typeToInferFrom;
1500   return success();
1501 }
1502 
1503 static LogicalResult verify(PadOp op) {
1504   auto sourceType = op.source().getType().cast<RankedTensorType>();
1505   auto resultType = op.result().getType().cast<RankedTensorType>();
1506   auto expectedType = PadOp::inferResultType(
1507       sourceType, extractFromI64ArrayAttr(op.static_low()),
1508       extractFromI64ArrayAttr(op.static_high()));
1509   for (int i = 0, e = sourceType.getRank(); i < e; ++i) {
1510     if (resultType.getDimSize(i) == expectedType.getDimSize(i))
1511       continue;
1512     if (expectedType.isDynamicDim(i))
1513       continue;
1514     return op.emitError("specified type ")
1515            << resultType << " does not match the inferred type "
1516            << expectedType;
1517   }
1518 
1519   auto &region = op.region();
1520   unsigned rank = resultType.getRank();
1521   Block &block = region.front();
1522   if (block.getNumArguments() != rank)
1523     return op.emitError("expected the block to have ") << rank << " arguments";
1524 
1525   // Note: the number and type of yield values are checked in the YieldOp.
1526   for (const auto &en : llvm::enumerate(block.getArgumentTypes())) {
1527     if (!en.value().isIndex())
1528       return op.emitOpError("expected block argument ")
1529              << (en.index() + 1) << " to be an index";
1530   }
1531 
1532   // Ensure that the region yields an element of the right type.
1533   auto yieldOp = llvm::cast<YieldOp>(block.getTerminator());
1534   if (yieldOp.value().getType() !=
1535       op.getType().cast<ShapedType>().getElementType())
1536     return op.emitOpError("expected yield type to match shape element type");
1537 
1538   return success();
1539 }
1540 
1541 RankedTensorType PadOp::inferResultType(RankedTensorType sourceType,
1542                                         ArrayRef<int64_t> staticLow,
1543                                         ArrayRef<int64_t> staticHigh,
1544                                         ArrayRef<int64_t> resultShape) {
1545   unsigned rank = sourceType.getRank();
1546   assert(staticLow.size() == rank && "unexpected staticLow size mismatch");
1547   assert(staticHigh.size() == rank && "unexpected staticHigh size mismatch");
1548   assert((resultShape.empty() || resultShape.size() == rank) &&
1549          "unexpected resultShape size mismatch");
1550 
1551   SmallVector<int64_t, 4> inferredShape;
1552   for (auto i : llvm::seq<unsigned>(0, rank)) {
1553     if (sourceType.isDynamicDim(i) ||
1554         staticLow[i] == ShapedType::kDynamicSize ||
1555         staticHigh[i] == ShapedType::kDynamicSize) {
1556       inferredShape.push_back(resultShape.empty() ? ShapedType::kDynamicSize
1557                                                   : resultShape[i]);
1558     } else {
1559       int64_t size = sourceType.getDimSize(i) + staticLow[i] + staticHigh[i];
1560       assert((resultShape.empty() || size == resultShape[i] ||
1561               resultShape[i] == ShapedType::kDynamicSize) &&
1562              "mismatch between inferred shape and result shape");
1563       inferredShape.push_back(size);
1564     }
1565   }
1566 
1567   return RankedTensorType::get(inferredShape, sourceType.getElementType());
1568 }
1569 
1570 void PadOp::build(OpBuilder &b, OperationState &result, Value source,
1571                   ArrayRef<int64_t> staticLow, ArrayRef<int64_t> staticHigh,
1572                   ValueRange low, ValueRange high, bool nofold,
1573                   ArrayRef<NamedAttribute> attrs) {
1574   auto sourceType = source.getType().cast<RankedTensorType>();
1575   auto resultType = inferResultType(sourceType, staticLow, staticHigh);
1576   build(b, result, resultType, source, low, high, b.getI64ArrayAttr(staticLow),
1577         b.getI64ArrayAttr(staticHigh), nofold ? b.getUnitAttr() : UnitAttr());
1578   result.addAttributes(attrs);
1579 }
1580 
1581 void PadOp::build(OpBuilder &b, OperationState &result, Value source,
1582                   ValueRange low, ValueRange high, bool nofold,
1583                   ArrayRef<NamedAttribute> attrs) {
1584   auto sourceType = source.getType().cast<RankedTensorType>();
1585   unsigned rank = sourceType.getRank();
1586   SmallVector<int64_t, 4> staticVector(rank, ShapedType::kDynamicSize);
1587   build(b, result, source, staticVector, staticVector, low, high, nofold,
1588         attrs);
1589 }
1590 
1591 void PadOp::build(OpBuilder &b, OperationState &result, Type resultType,
1592                   Value source, ArrayRef<OpFoldResult> low,
1593                   ArrayRef<OpFoldResult> high, bool nofold,
1594                   ArrayRef<NamedAttribute> attrs) {
1595   assert(resultType.isa<RankedTensorType>());
1596   auto sourceType = source.getType().cast<RankedTensorType>();
1597   SmallVector<Value, 4> dynamicLow, dynamicHigh;
1598   SmallVector<int64_t, 4> staticLow, staticHigh;
1599   // staticLow and staticHigh have full information of the padding config.
1600   // This will grow staticLow and staticHigh with 1 value. If the config is
1601   // dynamic (ie not a constant), dynamicLow and dynamicHigh will grow with 1
1602   // value as well.
1603   dispatchIndexOpFoldResults(low, dynamicLow, staticLow,
1604                              ShapedType::kDynamicSize);
1605   dispatchIndexOpFoldResults(high, dynamicHigh, staticHigh,
1606                              ShapedType::kDynamicSize);
1607   if (!resultType) {
1608     resultType = PadOp::inferResultType(sourceType, staticLow, staticHigh);
1609   }
1610   build(b, result, resultType, source, dynamicLow, dynamicHigh,
1611         b.getI64ArrayAttr(staticLow), b.getI64ArrayAttr(staticHigh),
1612         nofold ? b.getUnitAttr() : UnitAttr());
1613   result.addAttributes(attrs);
1614 }
1615 
1616 namespace {
1617 // Folds tensor.pad when padding is static zeros and the attribute
1618 // doesn't request otherwise.
1619 struct FoldStaticZeroPadding : public OpRewritePattern<PadOp> {
1620   using OpRewritePattern<PadOp>::OpRewritePattern;
1621 
1622   LogicalResult matchAndRewrite(PadOp padTensorOp,
1623                                 PatternRewriter &rewriter) const override {
1624     if (!padTensorOp.hasZeroLowPad() || !padTensorOp.hasZeroHighPad())
1625       return failure();
1626     if (padTensorOp.nofold())
1627       return failure();
1628     rewriter.replaceOpWithNewOp<tensor::CastOp>(
1629         padTensorOp, padTensorOp.result().getType(), padTensorOp.source());
1630     return success();
1631   }
1632 };
1633 
1634 // Fold CastOp into PadOp when adding static information.
1635 struct FoldSourceTensorCast : public OpRewritePattern<PadOp> {
1636   using OpRewritePattern<PadOp>::OpRewritePattern;
1637 
1638   LogicalResult matchAndRewrite(PadOp padTensorOp,
1639                                 PatternRewriter &rewriter) const override {
1640     auto castOp = padTensorOp.source().getDefiningOp<tensor::CastOp>();
1641     if (!tensor::canFoldIntoConsumerOp(castOp))
1642       return failure();
1643 
1644     auto newResultType = PadOp::inferResultType(
1645         castOp.source().getType().cast<RankedTensorType>(),
1646         extractFromI64ArrayAttr(padTensorOp.static_low()),
1647         extractFromI64ArrayAttr(padTensorOp.static_high()),
1648         padTensorOp.getResultType().getShape());
1649 
1650     if (newResultType == padTensorOp.getResultType()) {
1651       rewriter.updateRootInPlace(padTensorOp, [&]() {
1652         padTensorOp.sourceMutable().assign(castOp.source());
1653       });
1654     } else {
1655       auto newOp = rewriter.create<PadOp>(
1656           padTensorOp->getLoc(), newResultType, padTensorOp.source(),
1657           padTensorOp.low(), padTensorOp.high(), padTensorOp.static_low(),
1658           padTensorOp.static_high(), padTensorOp.nofold());
1659       BlockAndValueMapping mapper;
1660       padTensorOp.getRegion().cloneInto(&newOp.getRegion(), mapper);
1661 
1662       rewriter.replaceOpWithNewOp<tensor::CastOp>(
1663           padTensorOp, padTensorOp.getResultType(), newOp);
1664     }
1665     return success();
1666   }
1667 };
1668 
1669 // Fold CastOp using the result of PadOp back into the latter if it adds
1670 // static information.
1671 struct FoldTargetTensorCast : public OpRewritePattern<PadOp> {
1672   using OpRewritePattern<PadOp>::OpRewritePattern;
1673 
1674   LogicalResult matchAndRewrite(PadOp padTensorOp,
1675                                 PatternRewriter &rewriter) const override {
1676     if (!padTensorOp.result().hasOneUse())
1677       return failure();
1678     auto tensorCastOp =
1679         dyn_cast<tensor::CastOp>(*padTensorOp->getUsers().begin());
1680     if (!tensorCastOp)
1681       return failure();
1682     if (!tensor::preservesStaticInformation(padTensorOp.result().getType(),
1683                                             tensorCastOp.dest().getType()))
1684       return failure();
1685 
1686     auto replacementOp = rewriter.create<PadOp>(
1687         padTensorOp.getLoc(), tensorCastOp.dest().getType(),
1688         padTensorOp.source(), padTensorOp.low(), padTensorOp.high(),
1689         padTensorOp.static_low(), padTensorOp.static_high(),
1690         padTensorOp.nofold());
1691     replacementOp.region().takeBody(padTensorOp.region());
1692 
1693     rewriter.replaceOp(padTensorOp, replacementOp.result());
1694     rewriter.replaceOp(tensorCastOp, replacementOp.result());
1695     return success();
1696   }
1697 };
1698 } // namespace
1699 
1700 void PadOp::getCanonicalizationPatterns(RewritePatternSet &results,
1701                                         MLIRContext *context) {
1702   results
1703       .add<FoldStaticZeroPadding, FoldSourceTensorCast, FoldTargetTensorCast>(
1704           context);
1705 }
1706 
1707 /// Return the padding value of the PadOp if it constant. In this context,
1708 /// "constant" means an actual constant or "defined outside of the block".
1709 ///
1710 /// Values are considered constant in three cases:
1711 ///  - A ConstantLike value.
1712 ///  - A basic block argument from a different block.
1713 ///  - A value defined outside of the block.
1714 ///
1715 /// If the padding value is not constant, an empty Value is returned.
1716 Value PadOp::getConstantPaddingValue() {
1717   auto yieldOp = dyn_cast<YieldOp>(getRegion().front().getTerminator());
1718   if (!yieldOp)
1719     return {};
1720   Value padValue = yieldOp.value();
1721   // Check if yield value is a constant.
1722   if (matchPattern(padValue, m_Constant()))
1723     return padValue;
1724   // Check if yield value is defined inside the PadOp block.
1725   if (padValue.getParentBlock() == &getRegion().front())
1726     return {};
1727   // Else: Yield value defined outside of the PadOp block.
1728   return padValue;
1729 }
1730 
1731 OpFoldResult PadOp::fold(ArrayRef<Attribute>) {
1732   if (getResultType().hasStaticShape() && getResultType() == getSourceType() &&
1733       !nofold())
1734     return source();
1735   return {};
1736 }
1737 
1738 //===----------------------------------------------------------------------===//
1739 // TableGen'd op method definitions
1740 //===----------------------------------------------------------------------===//
1741 
1742 #define GET_OP_CLASSES
1743 #include "mlir/Dialect/Tensor/IR/TensorOps.cpp.inc"
1744