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