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