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::verify() {
529   // Ensure that the tensor type has as many dynamic dimensions as are specified
530   // by the operands.
531   RankedTensorType resultTy = getType().cast<RankedTensorType>();
532   if (getNumOperands() != resultTy.getNumDynamicDims())
533     return emitError("must have as many index operands as dynamic extents "
534                      "in the result type");
535 
536   return success();
537 }
538 
539 LogicalResult GenerateOp::verifyRegions() {
540   RankedTensorType resultTy = getType().cast<RankedTensorType>();
541   // Ensure that region arguments span the index space.
542   if (!llvm::all_of(body().getArgumentTypes(),
543                     [](Type ty) { return ty.isIndex(); }))
544     return emitError("all body arguments must be index");
545   if (body().getNumArguments() != resultTy.getRank())
546     return emitError("must have one body argument per input dimension");
547 
548   // Ensure that the region yields an element of the right type.
549   auto yieldOp = cast<YieldOp>(body().getBlocks().front().getTerminator());
550 
551   if (yieldOp.value().getType() != resultTy.getElementType())
552     return emitOpError(
553         "body must be terminated with a `yield` operation of the tensor "
554         "element type");
555 
556   return success();
557 }
558 
559 void GenerateOp::build(
560     OpBuilder &b, OperationState &result, Type resultTy,
561     ValueRange dynamicExtents,
562     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilder) {
563   build(b, result, resultTy, dynamicExtents);
564 
565   // Build and populate body.
566   OpBuilder::InsertionGuard guard(b);
567   Region *bodyRegion = result.regions.front().get();
568   auto rank = resultTy.cast<RankedTensorType>().getRank();
569   SmallVector<Type, 2> argumentTypes(rank, b.getIndexType());
570   SmallVector<Location, 2> argumentLocs(rank, result.location);
571   Block *bodyBlock =
572       b.createBlock(bodyRegion, bodyRegion->end(), argumentTypes, argumentLocs);
573   bodyBuilder(b, result.location, bodyBlock->getArguments());
574 }
575 
576 namespace {
577 
578 /// Canonicalizes tensor.generate operations with a constant
579 /// operand into the equivalent operation with the operand expressed in the
580 /// result type, instead. We also insert a type cast to make sure that the
581 /// resulting IR is still well-typed.
582 struct StaticTensorGenerate : public OpRewritePattern<GenerateOp> {
583   using OpRewritePattern<GenerateOp>::OpRewritePattern;
584 
585   LogicalResult matchAndRewrite(GenerateOp tensorFromElements,
586                                 PatternRewriter &rewriter) const final {
587     auto resultType =
588         tensorFromElements.getResult().getType().cast<RankedTensorType>();
589 
590     if (resultType.hasStaticShape())
591       return failure();
592 
593     SmallVector<Value, 4> newOperands;
594     SmallVector<int64_t, 4> newShape;
595     auto operandsIt = tensorFromElements.dynamicExtents().begin();
596 
597     for (int64_t dim : resultType.getShape()) {
598       if (!ShapedType::isDynamic(dim)) {
599         newShape.push_back(dim);
600         continue;
601       }
602       APInt index;
603       if (!matchPattern(*operandsIt, m_ConstantInt(&index))) {
604         newShape.push_back(ShapedType::kDynamicSize);
605         newOperands.push_back(*operandsIt++);
606         continue;
607       }
608       newShape.push_back(index.getSExtValue());
609       operandsIt++;
610     }
611 
612     if (newOperands.size() == tensorFromElements.dynamicExtents().size())
613       return failure();
614 
615     auto loc = tensorFromElements.getLoc();
616     auto newOp = rewriter.create<GenerateOp>(
617         loc, RankedTensorType::get(newShape, resultType.getElementType()),
618         newOperands);
619     rewriter.inlineRegionBefore(tensorFromElements.body(), newOp.body(),
620                                 newOp.body().begin());
621     rewriter.replaceOpWithNewOp<tensor::CastOp>(tensorFromElements, resultType,
622                                                 newOp);
623     return success();
624   }
625 };
626 
627 /// Canonicalizes the pattern of the form
628 ///
629 /// %tensor = tensor.generate %x {
630 ///   ^bb0(%arg0: index):
631 ///   <computation>
632 ///   yield %1 : index
633 /// } : tensor<?xindex>
634 /// %extracted_element = tensor.extract %tensor[%c0] : tensor<?xi32>
635 ///
636 /// to just <computation> with %arg0 replaced by %c0. We only do this if the
637 /// tensor.generate operation has no side-effects.
638 struct ExtractFromTensorGenerate : public OpRewritePattern<tensor::ExtractOp> {
639   using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern;
640 
641   LogicalResult matchAndRewrite(tensor::ExtractOp extract,
642                                 PatternRewriter &rewriter) const final {
643     auto tensorFromElements = extract.tensor().getDefiningOp<GenerateOp>();
644     if (!tensorFromElements || !wouldOpBeTriviallyDead(tensorFromElements))
645       return failure();
646 
647     BlockAndValueMapping mapping;
648     Block *body = tensorFromElements.getBody();
649     mapping.map(body->getArguments(), extract.indices());
650     for (auto &op : body->without_terminator())
651       rewriter.clone(op, mapping);
652 
653     auto yield = cast<YieldOp>(body->getTerminator());
654 
655     rewriter.replaceOp(extract, mapping.lookupOrDefault(yield.value()));
656     return success();
657   }
658 };
659 
660 /// Canonicalizes the pattern of the form
661 ///
662 /// %val = tensor.cast %source : : tensor<?xi32> to tensor<2xi32>
663 /// %extracted_element = tensor.extract %val[%c0] : tensor<2xi32>
664 ///
665 /// to
666 ///
667 /// %extracted_element = tensor.extract %source[%c0] : tensor<?xi32>
668 struct ExtractFromTensorCast : public OpRewritePattern<tensor::ExtractOp> {
669   using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern;
670 
671   LogicalResult matchAndRewrite(tensor::ExtractOp extract,
672                                 PatternRewriter &rewriter) const final {
673     auto tensorCast = extract.tensor().getDefiningOp<tensor::CastOp>();
674     if (!tensorCast)
675       return failure();
676 
677     rewriter.replaceOpWithNewOp<tensor::ExtractOp>(extract, tensorCast.source(),
678                                                    extract.indices());
679     return success();
680   }
681 };
682 
683 } // namespace
684 
685 void GenerateOp::getCanonicalizationPatterns(RewritePatternSet &results,
686                                              MLIRContext *context) {
687   // TODO: Move extract patterns to tensor::ExtractOp.
688   results.add<ExtractFromTensorGenerate, ExtractFromTensorCast,
689               StaticTensorGenerate>(context);
690 }
691 
692 //===----------------------------------------------------------------------===//
693 // RankOp
694 //===----------------------------------------------------------------------===//
695 
696 OpFoldResult RankOp::fold(ArrayRef<Attribute> operands) {
697   // Constant fold rank when the rank of the operand is known.
698   auto type = getOperand().getType();
699   auto shapedType = type.dyn_cast<ShapedType>();
700   if (shapedType && shapedType.hasRank())
701     return IntegerAttr::get(IndexType::get(getContext()), shapedType.getRank());
702   return IntegerAttr();
703 }
704 
705 //===----------------------------------------------------------------------===//
706 // ReshapeOp
707 //===----------------------------------------------------------------------===//
708 
709 static int64_t getNumElements(ShapedType type) {
710   int64_t numElements = 1;
711   for (auto dim : type.getShape())
712     numElements *= dim;
713   return numElements;
714 }
715 
716 LogicalResult ReshapeOp::verify() {
717   TensorType operandType = source().getType().cast<TensorType>();
718   TensorType resultType = result().getType().cast<TensorType>();
719 
720   if (operandType.getElementType() != resultType.getElementType())
721     return emitOpError("element types of source and destination tensor "
722                        "types should be the same");
723 
724   int64_t shapeSize = shape().getType().cast<RankedTensorType>().getDimSize(0);
725   auto resultRankedType = resultType.dyn_cast<RankedTensorType>();
726   auto operandRankedType = operandType.dyn_cast<RankedTensorType>();
727 
728   if (resultRankedType) {
729     if (operandRankedType && resultRankedType.hasStaticShape() &&
730         operandRankedType.hasStaticShape()) {
731       if (getNumElements(operandRankedType) != getNumElements(resultRankedType))
732         return emitOpError("source and destination tensor should have the "
733                            "same number of elements");
734     }
735     if (ShapedType::isDynamic(shapeSize))
736       return emitOpError("cannot use shape operand with dynamic length to "
737                          "reshape to statically-ranked tensor type");
738     if (shapeSize != resultRankedType.getRank())
739       return emitOpError(
740           "length of shape operand differs from the result's tensor rank");
741   }
742   return success();
743 }
744 
745 //===----------------------------------------------------------------------===//
746 // Reassociative reshape ops
747 //===----------------------------------------------------------------------===//
748 
749 SmallVector<AffineMap, 4> CollapseShapeOp::getReassociationMaps() {
750   return getSymbolLessAffineMaps(getReassociationExprs());
751 }
752 SmallVector<ReassociationExprs, 4> CollapseShapeOp::getReassociationExprs() {
753   return convertReassociationIndicesToExprs(getContext(),
754                                             getReassociationIndices());
755 }
756 
757 SmallVector<AffineMap, 4> ExpandShapeOp::getReassociationMaps() {
758   return getSymbolLessAffineMaps(getReassociationExprs());
759 }
760 SmallVector<ReassociationExprs, 4> ExpandShapeOp::getReassociationExprs() {
761   return convertReassociationIndicesToExprs(getContext(),
762                                             getReassociationIndices());
763 }
764 
765 /// Compute the RankedTensorType obtained by applying `reassociation` to `type`.
766 static RankedTensorType
767 computeTensorReshapeCollapsedType(RankedTensorType type,
768                                   ArrayRef<AffineMap> reassociation) {
769   auto shape = type.getShape();
770   SmallVector<int64_t, 4> newShape;
771   newShape.reserve(reassociation.size());
772 
773   // Use the fact that reassociation is valid to simplify the logic: only use
774   // each map's rank.
775   assert(isReassociationValid(reassociation) && "invalid reassociation");
776   unsigned currentDim = 0;
777   for (AffineMap m : reassociation) {
778     unsigned dim = m.getNumResults();
779     auto band = shape.slice(currentDim, dim);
780     int64_t size = 1;
781     if (llvm::is_contained(band, ShapedType::kDynamicSize))
782       size = ShapedType::kDynamicSize;
783     else
784       for (unsigned d = 0; d < dim; ++d)
785         size *= shape[currentDim + d];
786     newShape.push_back(size);
787     currentDim += dim;
788   }
789 
790   return RankedTensorType::get(newShape, type.getElementType());
791 }
792 
793 void CollapseShapeOp::build(OpBuilder &b, OperationState &result, Value src,
794                             ArrayRef<ReassociationIndices> reassociation,
795                             ArrayRef<NamedAttribute> attrs) {
796   auto resultType = computeTensorReshapeCollapsedType(
797       src.getType().cast<RankedTensorType>(),
798       getSymbolLessAffineMaps(
799           convertReassociationIndicesToExprs(b.getContext(), reassociation)));
800   build(b, result, resultType, src, attrs);
801   result.addAttribute(getReassociationAttrName(),
802                       getReassociationIndicesAttribute(b, reassociation));
803 }
804 
805 void ExpandShapeOp::build(OpBuilder &b, OperationState &result, Value src,
806                           ArrayRef<ReassociationIndices> reassociation,
807                           ArrayRef<NamedAttribute> attrs) {
808   auto resultType = computeTensorReshapeCollapsedType(
809       src.getType().cast<RankedTensorType>(),
810       getSymbolLessAffineMaps(
811           convertReassociationIndicesToExprs(b.getContext(), reassociation)));
812   build(b, result, resultType, src, attrs);
813   result.addAttribute(getReassociationAttrName(),
814                       getReassociationIndicesAttribute(b, reassociation));
815 }
816 
817 template <typename TensorReshapeOp, bool isExpansion = std::is_same<
818                                         TensorReshapeOp, ExpandShapeOp>::value>
819 static LogicalResult verifyTensorReshapeOp(TensorReshapeOp op,
820                                            RankedTensorType expandedType,
821                                            RankedTensorType collapsedType) {
822   if (failed(
823           verifyReshapeLikeTypes(op, expandedType, collapsedType, isExpansion)))
824     return failure();
825 
826   auto maps = op.getReassociationMaps();
827   RankedTensorType expectedType =
828       computeTensorReshapeCollapsedType(expandedType, maps);
829   if (collapsedType != expectedType)
830     return op.emitOpError("expected collapsed type to be ")
831            << expectedType << ", but got " << collapsedType;
832   return success();
833 }
834 
835 LogicalResult ExpandShapeOp::verify() {
836   return verifyTensorReshapeOp(*this, getResultType(), getSrcType());
837 }
838 
839 LogicalResult CollapseShapeOp::verify() {
840   return verifyTensorReshapeOp(*this, getSrcType(), getResultType());
841 }
842 
843 namespace {
844 /// Reshape of a splat constant can be replaced with a constant of the result
845 /// type.
846 template <typename TensorReshapeOp>
847 struct FoldReshapeWithConstant : OpRewritePattern<TensorReshapeOp> {
848   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
849   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
850                                 PatternRewriter &rewriter) const override {
851     DenseElementsAttr attr;
852     if (!matchPattern(reshapeOp.src(), m_Constant(&attr)))
853       return failure();
854     if (!attr || !attr.isSplat())
855       return failure();
856     DenseElementsAttr newAttr = DenseElementsAttr::getFromRawBuffer(
857         reshapeOp.getResultType(), attr.getRawData(), true);
858     rewriter.replaceOpWithNewOp<arith::ConstantOp>(reshapeOp, newAttr);
859     return success();
860   }
861 };
862 
863 /// Reshape of a FromElements can be replaced with a FromElements of the result
864 /// type
865 template <typename TensorReshapeOp>
866 struct FoldReshapeWithFromElements : OpRewritePattern<TensorReshapeOp> {
867   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
868   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
869                                 PatternRewriter &rewriter) const override {
870     auto fromElements =
871         reshapeOp.src().template getDefiningOp<FromElementsOp>();
872     if (!fromElements)
873       return failure();
874 
875     auto shapedTy = reshapeOp.getType().template cast<ShapedType>();
876 
877     if (!shapedTy.hasStaticShape())
878       return failure();
879 
880     rewriter.replaceOpWithNewOp<FromElementsOp>(reshapeOp, reshapeOp.getType(),
881                                                 fromElements.elements());
882     return success();
883   }
884 };
885 
886 } // namespace
887 
888 void ExpandShapeOp::getCanonicalizationPatterns(RewritePatternSet &results,
889                                                 MLIRContext *context) {
890   results.add<CollapseReshapeOps<ExpandShapeOp>,
891               CollapseMixedReshapeOps<ExpandShapeOp, CollapseShapeOp>,
892               FoldReshapeWithConstant<ExpandShapeOp>,
893               FoldReshapeWithFromElements<ExpandShapeOp>>(context);
894 }
895 
896 void CollapseShapeOp::getCanonicalizationPatterns(RewritePatternSet &results,
897                                                   MLIRContext *context) {
898   results.add<CollapseReshapeOps<CollapseShapeOp>,
899               CollapseMixedReshapeOps<CollapseShapeOp, ExpandShapeOp>,
900               FoldReshapeWithConstant<CollapseShapeOp>,
901               FoldReshapeWithFromElements<CollapseShapeOp>>(context);
902 }
903 
904 OpFoldResult ExpandShapeOp::fold(ArrayRef<Attribute> operands) {
905   return foldReshapeOp<ExpandShapeOp, CollapseShapeOp>(*this, operands);
906 }
907 OpFoldResult CollapseShapeOp::fold(ArrayRef<Attribute> operands) {
908   return foldReshapeOp<CollapseShapeOp, ExpandShapeOp>(*this, operands);
909 }
910 
911 //===----------------------------------------------------------------------===//
912 // ExtractSliceOp
913 //===----------------------------------------------------------------------===//
914 
915 /// An extract_slice op result type can be fully inferred from the source type
916 /// and the static representation of offsets, sizes and strides. Special
917 /// sentinels encode the dynamic case.
918 RankedTensorType ExtractSliceOp::inferResultType(
919     RankedTensorType sourceRankedTensorType, ArrayRef<int64_t> staticOffsets,
920     ArrayRef<int64_t> staticSizes, ArrayRef<int64_t> staticStrides) {
921   // An extract_slice op may specify only a leading subset of offset/sizes/
922   // strides in which case we complete with offset=0, sizes from memref type and
923   // strides=1.
924   unsigned rank = sourceRankedTensorType.getRank();
925   (void)rank;
926   assert(staticSizes.size() == rank &&
927          "unexpected staticSizes not equal to rank of source");
928   return RankedTensorType::get(staticSizes,
929                                sourceRankedTensorType.getElementType());
930 }
931 
932 RankedTensorType ExtractSliceOp::inferResultType(
933     RankedTensorType sourceRankedTensorType, ArrayRef<OpFoldResult> offsets,
934     ArrayRef<OpFoldResult> sizes, ArrayRef<OpFoldResult> strides) {
935   SmallVector<int64_t> staticOffsets, staticSizes, staticStrides;
936   SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides;
937   dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets,
938                              ShapedType::kDynamicStrideOrOffset);
939   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
940                              ShapedType::kDynamicSize);
941   dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides,
942                              ShapedType::kDynamicStrideOrOffset);
943   return ExtractSliceOp::inferResultType(sourceRankedTensorType, staticOffsets,
944                                          staticSizes, staticStrides);
945 }
946 
947 /// An extract_slice op result type can be fully inferred from the source type
948 /// and the static representation of offsets, sizes and strides. Special
949 /// sentinels encode the dynamic case.
950 RankedTensorType ExtractSliceOp::inferRankReducedResultType(
951     unsigned resultRank, RankedTensorType sourceRankedTensorType,
952     ArrayRef<int64_t> offsets, ArrayRef<int64_t> sizes,
953     ArrayRef<int64_t> strides) {
954   auto inferredType =
955       inferResultType(sourceRankedTensorType, offsets, sizes, strides)
956           .cast<RankedTensorType>();
957   int rankDiff = inferredType.getRank() - resultRank;
958   if (rankDiff > 0) {
959     auto shape = inferredType.getShape();
960     llvm::SmallBitVector dimsToProject =
961         getPositionsOfShapeOne(rankDiff, shape);
962     SmallVector<int64_t> projectedShape;
963     for (unsigned pos = 0, e = shape.size(); pos < e; ++pos)
964       if (!dimsToProject.test(pos))
965         projectedShape.push_back(shape[pos]);
966     inferredType =
967         RankedTensorType::get(projectedShape, inferredType.getElementType());
968   }
969   return inferredType;
970 }
971 
972 RankedTensorType ExtractSliceOp::inferRankReducedResultType(
973     unsigned resultRank, RankedTensorType sourceRankedTensorType,
974     ArrayRef<OpFoldResult> offsets, ArrayRef<OpFoldResult> sizes,
975     ArrayRef<OpFoldResult> strides) {
976   SmallVector<int64_t> staticOffsets, staticSizes, staticStrides;
977   SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides;
978   dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets,
979                              ShapedType::kDynamicStrideOrOffset);
980   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
981                              ShapedType::kDynamicSize);
982   dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides,
983                              ShapedType::kDynamicStrideOrOffset);
984   return ExtractSliceOp::inferRankReducedResultType(
985       resultRank, sourceRankedTensorType, staticOffsets, staticSizes,
986       staticStrides);
987 }
988 
989 /// Build an ExtractSliceOp with mixed static and dynamic entries and custom
990 /// result type. If the type passed is nullptr, it is inferred.
991 void ExtractSliceOp::build(OpBuilder &b, OperationState &result,
992                            RankedTensorType resultType, Value source,
993                            ArrayRef<OpFoldResult> offsets,
994                            ArrayRef<OpFoldResult> sizes,
995                            ArrayRef<OpFoldResult> strides,
996                            ArrayRef<NamedAttribute> attrs) {
997   SmallVector<int64_t> staticOffsets, staticSizes, staticStrides;
998   SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides;
999   dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets,
1000                              ShapedType::kDynamicStrideOrOffset);
1001   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
1002                              ShapedType::kDynamicSize);
1003   dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides,
1004                              ShapedType::kDynamicStrideOrOffset);
1005   auto sourceRankedTensorType = source.getType().cast<RankedTensorType>();
1006   // Structuring implementation this way avoids duplication between builders.
1007   if (!resultType) {
1008     resultType =
1009         ExtractSliceOp::inferResultType(sourceRankedTensorType, staticOffsets,
1010                                         staticSizes, staticStrides)
1011             .cast<RankedTensorType>();
1012   }
1013   build(b, result, resultType, source, dynamicOffsets, dynamicSizes,
1014         dynamicStrides, b.getI64ArrayAttr(staticOffsets),
1015         b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides));
1016   result.addAttributes(attrs);
1017 }
1018 
1019 /// Build an ExtractSliceOp with mixed static and dynamic entries and inferred
1020 /// result type.
1021 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, Value source,
1022                            ArrayRef<OpFoldResult> offsets,
1023                            ArrayRef<OpFoldResult> sizes,
1024                            ArrayRef<OpFoldResult> strides,
1025                            ArrayRef<NamedAttribute> attrs) {
1026   build(b, result, RankedTensorType(), source, offsets, sizes, strides, attrs);
1027 }
1028 
1029 /// Build an ExtractSliceOp with dynamic entries and custom result type. If the
1030 /// type passed is nullptr, it is inferred.
1031 void ExtractSliceOp::build(OpBuilder &b, OperationState &result,
1032                            RankedTensorType resultType, Value source,
1033                            ValueRange offsets, ValueRange sizes,
1034                            ValueRange strides, ArrayRef<NamedAttribute> attrs) {
1035   SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>(
1036       llvm::map_range(offsets, [](Value v) -> OpFoldResult { return v; }));
1037   SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>(
1038       llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; }));
1039   SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>(
1040       llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; }));
1041   build(b, result, resultType, source, offsetValues, sizeValues, strideValues);
1042 }
1043 
1044 /// Build an ExtractSliceOp with dynamic entries and inferred result type.
1045 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, Value source,
1046                            ValueRange offsets, ValueRange sizes,
1047                            ValueRange strides, ArrayRef<NamedAttribute> attrs) {
1048   build(b, result, RankedTensorType(), source, offsets, sizes, strides, attrs);
1049 }
1050 
1051 template <typename OpTy>
1052 static LogicalResult produceSliceErrorMsg(SliceVerificationResult result,
1053                                           OpTy op, Type expectedType) {
1054   auto memrefType = expectedType.cast<ShapedType>();
1055   switch (result) {
1056   case SliceVerificationResult::Success:
1057     return success();
1058   case SliceVerificationResult::RankTooLarge:
1059     return op.emitError("expected rank to be smaller or equal to ")
1060            << "the other rank. ";
1061   case SliceVerificationResult::SizeMismatch:
1062     return op.emitError("expected type to be ")
1063            << expectedType << " or a rank-reduced version. (size mismatch) ";
1064   case SliceVerificationResult::ElemTypeMismatch:
1065     return op.emitError("expected element type to be ")
1066            << memrefType.getElementType();
1067   default:
1068     llvm_unreachable("unexpected extract_slice op verification result");
1069   }
1070 }
1071 
1072 /// Verifier for ExtractSliceOp.
1073 LogicalResult ExtractSliceOp::verify() {
1074   // Verify result type against inferred type.
1075   auto expectedType = ExtractSliceOp::inferResultType(
1076       getSourceType(), getMixedOffsets(), getMixedSizes(), getMixedStrides());
1077   auto result = isRankReducedType(expectedType.cast<ShapedType>(), getType());
1078   return produceSliceErrorMsg(result, *this, expectedType);
1079 }
1080 
1081 /// Infer the canonical type of the result of an extract_slice op. Returns a
1082 /// type with rank `resultRank` that is either the rank of the rank-reduced
1083 /// type, or the non-rank-reduced type.
1084 static RankedTensorType
1085 getCanonicalSliceResultType(unsigned resultRank, RankedTensorType sourceType,
1086                             ArrayRef<OpFoldResult> mixedOffsets,
1087                             ArrayRef<OpFoldResult> mixedSizes,
1088                             ArrayRef<OpFoldResult> mixedStrides) {
1089   auto resultType =
1090       ExtractSliceOp::inferRankReducedResultType(
1091           resultRank, sourceType, mixedOffsets, mixedSizes, mixedStrides)
1092           .cast<RankedTensorType>();
1093   if (resultType.getRank() != resultRank) {
1094     resultType = ExtractSliceOp::inferResultType(sourceType, mixedOffsets,
1095                                                  mixedSizes, mixedStrides)
1096                      .cast<RankedTensorType>();
1097   }
1098   return resultType;
1099 }
1100 
1101 llvm::SmallBitVector ExtractSliceOp::getDroppedDims() {
1102   ArrayRef<int64_t> resultShape = getType().getShape();
1103   SmallVector<OpFoldResult> mixedSizes = getMixedSizes();
1104   llvm::SmallBitVector droppedDims(mixedSizes.size());
1105   unsigned shapePos = 0;
1106   for (const auto &size : enumerate(mixedSizes)) {
1107     Optional<int64_t> sizeVal = getConstantIntValue(size.value());
1108     // If the size is not 1, or if the current matched dimension of the result
1109     // is the same static shape as the size value (which is 1), then the
1110     // dimension is preserved.
1111     if (!sizeVal || sizeVal.getValue() != 1 ||
1112         (shapePos < resultShape.size() && resultShape[shapePos] == 1)) {
1113       shapePos++;
1114       continue;
1115     }
1116     droppedDims.set(size.index());
1117   }
1118   return droppedDims;
1119 }
1120 
1121 LogicalResult ExtractSliceOp::reifyResultShapes(
1122     OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) {
1123   reifiedReturnShapes.resize(1);
1124   reifiedReturnShapes[0].reserve(getType().getRank());
1125   SmallVector<OpFoldResult> mixedSizes = getMixedSizes();
1126   llvm::SmallBitVector droppedDims = getDroppedDims();
1127   Location loc = getLoc();
1128   for (const auto &size : enumerate(mixedSizes)) {
1129     if (droppedDims.test(size.index()))
1130       continue;
1131     if (auto attr = size.value().dyn_cast<Attribute>()) {
1132       reifiedReturnShapes[0].push_back(builder.create<arith::ConstantIndexOp>(
1133           loc, attr.cast<IntegerAttr>().getInt()));
1134       continue;
1135     }
1136     reifiedReturnShapes[0].push_back(size.value().get<Value>());
1137   }
1138   return success();
1139 }
1140 
1141 namespace {
1142 /// Pattern to rewrite an extract_slice op with tensor::Cast arguments.
1143 /// This essentially pushes memref_cast past its consuming slice when
1144 /// `canFoldIntoConsumerOp` is true.
1145 ///
1146 /// Example:
1147 /// ```
1148 ///   %0 = tensor.cast %V : tensor<16x16xf32> to tensor<?x?xf32>
1149 ///   %1 = tensor.extract_slice %0[0, 0][3, 4][1, 1] : tensor<?x?xf32> to
1150 ///   tensor<3x4xf32>
1151 /// ```
1152 /// is rewritten into:
1153 /// ```
1154 ///   %0 = tensor.extract_slice %V[0, 0][3, 4][1, 1] : tensor<16x16xf32> to
1155 ///   tensor<3x4xf32> %1 = tensor.cast %0: tensor<3x4xf32> to tensor<3x4xf32>
1156 /// ```
1157 class ExtractSliceOpCastFolder final : public OpRewritePattern<ExtractSliceOp> {
1158 public:
1159   using OpRewritePattern<ExtractSliceOp>::OpRewritePattern;
1160 
1161   LogicalResult matchAndRewrite(ExtractSliceOp sliceOp,
1162                                 PatternRewriter &rewriter) const override {
1163     // Any constant operand, just return to let SubViewOpConstantFolder kick in.
1164     if (llvm::any_of(sliceOp.getOperands(), [](Value operand) {
1165           return matchPattern(operand, matchConstantIndex());
1166         }))
1167       return failure();
1168 
1169     auto castOp = sliceOp.source().getDefiningOp<tensor::CastOp>();
1170     if (!castOp)
1171       return failure();
1172 
1173     if (!canFoldIntoConsumerOp(castOp))
1174       return failure();
1175 
1176     /// Deduce the type of the result to use for the canonicalized operation.
1177     RankedTensorType resultType = getCanonicalSliceResultType(
1178         sliceOp.getType().getRank(), sliceOp.getSourceType(),
1179         sliceOp.getMixedOffsets(), sliceOp.getMixedSizes(),
1180         sliceOp.getMixedStrides());
1181     Value newSlice = rewriter.create<ExtractSliceOp>(
1182         sliceOp.getLoc(), resultType, castOp.source(), sliceOp.offsets(),
1183         sliceOp.sizes(), sliceOp.strides(), sliceOp.static_offsets(),
1184         sliceOp.static_sizes(), sliceOp.static_strides());
1185     rewriter.replaceOpWithNewOp<tensor::CastOp>(sliceOp, sliceOp.getType(),
1186                                                 newSlice);
1187     return success();
1188   }
1189 };
1190 
1191 /// Slice elements from `values` into `outValues`. `counts` represents the
1192 /// numbers of elements to stride in the original values for each dimension.
1193 /// The output values can be used to construct a DenseElementsAttr.
1194 template <typename IterTy, typename ElemTy>
1195 static void sliceElements(IterTy values, ArrayRef<int64_t> counts,
1196                           ArrayRef<int64_t> offsets, ArrayRef<int64_t> sizes,
1197                           ArrayRef<int64_t> strides,
1198                           llvm::SmallVectorImpl<ElemTy> *outValues) {
1199   assert(offsets.size() == sizes.size());
1200   assert(offsets.size() == strides.size());
1201   if (offsets.empty())
1202     return;
1203 
1204   int64_t offset = offsets.front();
1205   int64_t size = sizes.front();
1206   int64_t stride = strides.front();
1207   if (offsets.size() == 1) {
1208     for (int64_t i = 0; i < size; ++i, offset += stride)
1209       outValues->push_back(*(values + offset));
1210 
1211     return;
1212   }
1213 
1214   for (int64_t i = 0; i < size; ++i, offset += stride) {
1215     auto begin = values + offset * counts.front();
1216     sliceElements<IterTy, ElemTy>(begin, counts.drop_front(),
1217                                   offsets.drop_front(), sizes.drop_front(),
1218                                   strides.drop_front(), outValues);
1219   }
1220 }
1221 
1222 /// Fold arith.constant and tensor.extract_slice into arith.constant. The folded
1223 /// operation might introduce more constant data; Users can control their
1224 /// heuristics by the control function.
1225 class ConstantOpExtractSliceFolder final
1226     : public OpRewritePattern<ExtractSliceOp> {
1227 public:
1228   using OpRewritePattern<ExtractSliceOp>::OpRewritePattern;
1229 
1230   ConstantOpExtractSliceFolder(MLIRContext *context,
1231                                ControlConstantExtractSliceFusionFn controlFn)
1232       : OpRewritePattern<ExtractSliceOp>(context),
1233         controlFn(std::move(controlFn)) {}
1234 
1235   LogicalResult matchAndRewrite(ExtractSliceOp op,
1236                                 PatternRewriter &rewriter) const override {
1237     DenseElementsAttr attr;
1238     if (!matchPattern(op.source(), m_Constant(&attr)))
1239       return failure();
1240 
1241     // A constant splat is handled by fold().
1242     if (attr.isSplat())
1243       return failure();
1244 
1245     // Dynamic result shape is not supported.
1246     auto sourceType = op.source().getType().cast<ShapedType>();
1247     auto resultType = op.result().getType().cast<ShapedType>();
1248     if (!sourceType.hasStaticShape() || !resultType.hasStaticShape())
1249       return failure();
1250 
1251     // Customized control over the folding.
1252     if (!controlFn(op))
1253       return failure();
1254 
1255     int64_t count = sourceType.getNumElements();
1256     if (count == 0)
1257       return failure();
1258 
1259     // Check if there are any dynamic parts, which are not supported.
1260     auto offsets = extractFromI64ArrayAttr(op.static_offsets());
1261     if (llvm::is_contained(offsets, ShapedType::kDynamicStrideOrOffset))
1262       return failure();
1263     auto sizes = extractFromI64ArrayAttr(op.static_sizes());
1264     if (llvm::is_contained(sizes, ShapedType::kDynamicSize))
1265       return failure();
1266     auto strides = extractFromI64ArrayAttr(op.static_strides());
1267     if (llvm::is_contained(strides, ShapedType::kDynamicStrideOrOffset))
1268       return failure();
1269 
1270     // Compute the stride for each dimension.
1271     SmallVector<int64_t> counts;
1272     ArrayRef<int64_t> shape = sourceType.getShape();
1273     counts.reserve(shape.size());
1274     for (int64_t v : shape) {
1275       count = count / v;
1276       counts.push_back(count);
1277     }
1278 
1279     // New attribute constructed by the sliced values.
1280     DenseElementsAttr newAttr;
1281 
1282     if (auto elems = attr.dyn_cast<DenseIntElementsAttr>()) {
1283       SmallVector<APInt> outValues;
1284       outValues.reserve(sourceType.getNumElements());
1285       sliceElements<DenseElementsAttr::IntElementIterator, APInt>(
1286           elems.begin(), counts, offsets, sizes, strides, &outValues);
1287       newAttr = DenseElementsAttr::get(resultType, outValues);
1288     } else if (auto elems = attr.dyn_cast<DenseFPElementsAttr>()) {
1289       SmallVector<APFloat> outValues;
1290       outValues.reserve(sourceType.getNumElements());
1291       sliceElements<DenseElementsAttr::FloatElementIterator, APFloat>(
1292           elems.begin(), counts, offsets, sizes, strides, &outValues);
1293       newAttr = DenseElementsAttr::get(resultType, outValues);
1294     }
1295 
1296     if (newAttr) {
1297       rewriter.replaceOpWithNewOp<arith::ConstantOp>(op, resultType, newAttr);
1298       return success();
1299     }
1300 
1301     return failure();
1302   }
1303 
1304 private:
1305   /// This additionally controls whether the fold happens or not. Users can
1306   /// impose their heuristics in the function.
1307   ControlConstantExtractSliceFusionFn controlFn;
1308 };
1309 
1310 } // namespace
1311 
1312 void mlir::tensor::populateFoldConstantExtractSlicePatterns(
1313     RewritePatternSet &patterns,
1314     const ControlConstantExtractSliceFusionFn &controlFn) {
1315   patterns.add<ConstantOpExtractSliceFolder>(patterns.getContext(), controlFn);
1316 }
1317 
1318 /// Return the canonical type of the result of an extract_slice op.
1319 struct SliceReturnTypeCanonicalizer {
1320   RankedTensorType operator()(ExtractSliceOp op,
1321                               ArrayRef<OpFoldResult> mixedOffsets,
1322                               ArrayRef<OpFoldResult> mixedSizes,
1323                               ArrayRef<OpFoldResult> mixedStrides) {
1324     return getCanonicalSliceResultType(op.getType().getRank(),
1325                                        op.getSourceType(), mixedOffsets,
1326                                        mixedSizes, mixedStrides);
1327   }
1328 };
1329 
1330 /// A canonicalizer wrapper to replace ExtractSliceOps.
1331 struct SliceCanonicalizer {
1332   void operator()(PatternRewriter &rewriter, ExtractSliceOp op,
1333                   ExtractSliceOp newOp) {
1334     Value replacement = newOp.getResult();
1335     if (replacement.getType() != op.getType())
1336       replacement = rewriter.create<tensor::CastOp>(op.getLoc(), op.getType(),
1337                                                     replacement);
1338     rewriter.replaceOp(op, replacement);
1339   }
1340 };
1341 
1342 void ExtractSliceOp::getCanonicalizationPatterns(RewritePatternSet &results,
1343                                                  MLIRContext *context) {
1344   results.add<
1345       OpWithOffsetSizesAndStridesConstantArgumentFolder<
1346           ExtractSliceOp, SliceReturnTypeCanonicalizer, SliceCanonicalizer>,
1347       ExtractSliceOpCastFolder>(context);
1348 }
1349 
1350 //
1351 static LogicalResult
1352 foldIdentityOffsetSizeAndStrideOpInterface(OffsetSizeAndStrideOpInterface op,
1353                                            ShapedType shapedType) {
1354   OpBuilder b(op.getContext());
1355   for (OpFoldResult ofr : op.getMixedOffsets())
1356     if (getConstantIntValue(ofr) != static_cast<int64_t>(0))
1357       return failure();
1358   // Rank-reducing noops only need to inspect the leading dimensions: llvm::zip
1359   // is appropriate.
1360   auto shape = shapedType.getShape();
1361   for (auto it : llvm::zip(op.getMixedSizes(), shape))
1362     if (getConstantIntValue(std::get<0>(it)) != std::get<1>(it))
1363       return failure();
1364   for (OpFoldResult ofr : op.getMixedStrides())
1365     if (getConstantIntValue(ofr) != static_cast<int64_t>(1))
1366       return failure();
1367   return success();
1368 }
1369 
1370 /// If we have an ExtractSliceOp consuming an InsertSliceOp with the same slice,
1371 /// we can return the InsertSliceOp's source directly.
1372 // TODO: This only checks the immediate producer; extend to go up the
1373 // insert/extract chain if the slices are disjoint.
1374 static Value foldExtractAfterInsertSlice(ExtractSliceOp extractOp) {
1375   auto insertOp = extractOp.source().getDefiningOp<InsertSliceOp>();
1376 
1377   auto isSame = [](OpFoldResult a, OpFoldResult b) { return a == b; };
1378   if (insertOp && insertOp.source().getType() == extractOp.getType() &&
1379       insertOp.isSameAs(extractOp, isSame))
1380     return insertOp.source();
1381 
1382   return {};
1383 }
1384 
1385 OpFoldResult ExtractSliceOp::fold(ArrayRef<Attribute> operands) {
1386   if (auto splat = operands[0].dyn_cast_or_null<SplatElementsAttr>()) {
1387     auto resultType = result().getType().cast<ShapedType>();
1388     if (resultType.hasStaticShape())
1389       return splat.resizeSplat(resultType);
1390   }
1391   if (getSourceType() == getType() &&
1392       succeeded(foldIdentityOffsetSizeAndStrideOpInterface(*this, getType())))
1393     return this->source();
1394   if (Value slice = foldExtractAfterInsertSlice(*this))
1395     return slice;
1396 
1397   return OpFoldResult();
1398 }
1399 
1400 Value mlir::tensor::createCanonicalRankReducingExtractSliceOp(
1401     OpBuilder &b, Location loc, Value tensor, RankedTensorType targetType) {
1402   auto rankedTensorType = tensor.getType().cast<RankedTensorType>();
1403   unsigned rank = rankedTensorType.getRank();
1404   auto shape = rankedTensorType.getShape();
1405   SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0));
1406   SmallVector<OpFoldResult> sizes;
1407   for (unsigned i = 0, e = rank; i < e; ++i) {
1408     OpFoldResult dim;
1409     if (rankedTensorType.isDynamicDim(i))
1410       dim = b.createOrFold<tensor::DimOp>(
1411           loc, tensor, b.create<arith::ConstantIndexOp>(loc, i));
1412     else
1413       dim = b.getIndexAttr(shape[i]);
1414     sizes.push_back(dim);
1415   }
1416   SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1));
1417   return b.createOrFold<tensor::ExtractSliceOp>(loc, targetType, tensor,
1418                                                 offsets, sizes, strides);
1419 }
1420 
1421 //===----------------------------------------------------------------------===//
1422 // InsertSliceOp
1423 //===----------------------------------------------------------------------===//
1424 
1425 // Build a InsertSliceOp with mixed static and dynamic entries.
1426 void InsertSliceOp::build(OpBuilder &b, OperationState &result, Value source,
1427                           Value dest, ArrayRef<OpFoldResult> offsets,
1428                           ArrayRef<OpFoldResult> sizes,
1429                           ArrayRef<OpFoldResult> strides,
1430                           ArrayRef<NamedAttribute> attrs) {
1431   SmallVector<int64_t> staticOffsets, staticSizes, staticStrides;
1432   SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides;
1433   dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets,
1434                              ShapedType::kDynamicStrideOrOffset);
1435   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
1436                              ShapedType::kDynamicSize);
1437   dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides,
1438                              ShapedType::kDynamicStrideOrOffset);
1439   build(b, result, dest.getType(), source, dest, dynamicOffsets, dynamicSizes,
1440         dynamicStrides, b.getI64ArrayAttr(staticOffsets),
1441         b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides));
1442   result.addAttributes(attrs);
1443 }
1444 
1445 // Build a InsertSliceOp with dynamic entries.
1446 void InsertSliceOp::build(OpBuilder &b, OperationState &result, Value source,
1447                           Value dest, ValueRange offsets, ValueRange sizes,
1448                           ValueRange strides, ArrayRef<NamedAttribute> attrs) {
1449   SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>(
1450       llvm::map_range(offsets, [](Value v) -> OpFoldResult { return v; }));
1451   SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>(
1452       llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; }));
1453   SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>(
1454       llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; }));
1455   build(b, result, source, dest, offsetValues, sizeValues, strideValues);
1456 }
1457 
1458 static SliceVerificationResult
1459 verifyInsertSliceOp(ShapedType srcType, ShapedType dstType,
1460                     ArrayAttr staticOffsets, ArrayAttr staticSizes,
1461                     ArrayAttr staticStrides,
1462                     ShapedType *expectedType = nullptr) {
1463   // insert_slice is the inverse of extract_slice, use the same type inference.
1464   auto expected = ExtractSliceOp::inferRankReducedResultType(
1465                       srcType.getRank(), dstType.cast<RankedTensorType>(),
1466                       extractFromI64ArrayAttr(staticOffsets),
1467                       extractFromI64ArrayAttr(staticSizes),
1468                       extractFromI64ArrayAttr(staticStrides))
1469                       .cast<ShapedType>();
1470   if (expectedType)
1471     *expectedType = expected;
1472   return isRankReducedType(expected, srcType);
1473 }
1474 
1475 /// Verifier for InsertSliceOp.
1476 LogicalResult InsertSliceOp::verify() {
1477   ShapedType expectedType;
1478   auto result =
1479       verifyInsertSliceOp(getSourceType(), getType(), static_offsets(),
1480                           static_sizes(), static_strides(), &expectedType);
1481   return produceSliceErrorMsg(result, *this, expectedType);
1482 }
1483 
1484 /// If we have two consecutive InsertSliceOp writing to the same slice, we
1485 /// can mutate the second InsertSliceOp's destination to the first one's.
1486 ///
1487 /// Example:
1488 ///
1489 /// ```mlir
1490 ///   %0 = tensor.insert_slice %slice0 into %input[0, 0] [64, 64] [1, 1]
1491 ///   %1 = tensor.insert_slice %slice1 into %0[0, 0] [64, 64] [1, 1]
1492 /// ```
1493 ///
1494 /// folds into:
1495 ///
1496 /// ```mlir
1497 ///   %1 = tensor.insert_slice %slice1 into %input[0, 0] [64, 64] [1, 1]
1498 /// ```
1499 static LogicalResult foldInsertAfterInsertSlice(InsertSliceOp insertOp) {
1500   auto prevInsertOp = insertOp.dest().getDefiningOp<InsertSliceOp>();
1501 
1502   auto isSame = [](OpFoldResult a, OpFoldResult b) { return a == b; };
1503   if (!prevInsertOp ||
1504       prevInsertOp.source().getType() != insertOp.source().getType() ||
1505       !prevInsertOp.isSameAs(insertOp, isSame))
1506     return failure();
1507 
1508   insertOp.destMutable().assign(prevInsertOp.dest());
1509   return success();
1510 }
1511 
1512 OpFoldResult InsertSliceOp::fold(ArrayRef<Attribute>) {
1513   if (getSourceType().hasStaticShape() && getType().hasStaticShape() &&
1514       getSourceType() == getType() &&
1515       succeeded(foldIdentityOffsetSizeAndStrideOpInterface(*this, getType())))
1516     return this->source();
1517   if (succeeded(foldInsertAfterInsertSlice(*this)))
1518     return getResult();
1519   return OpFoldResult();
1520 }
1521 
1522 LogicalResult InsertSliceOp::reifyResultShapes(
1523     OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) {
1524   reifiedReturnShapes.resize(1, SmallVector<Value>(getType().getRank()));
1525   for (auto dim : llvm::seq<int64_t>(0, getType().getRank())) {
1526     reifiedReturnShapes[0][dim] =
1527         builder.createOrFold<tensor::DimOp>(getLoc(), dest(), dim);
1528   }
1529   return success();
1530 }
1531 
1532 namespace {
1533 /// Pattern to rewrite a insert_slice op with constant arguments.
1534 class InsertSliceOpConstantArgumentFolder final
1535     : public OpRewritePattern<InsertSliceOp> {
1536 public:
1537   using OpRewritePattern<InsertSliceOp>::OpRewritePattern;
1538 
1539   LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp,
1540                                 PatternRewriter &rewriter) const override {
1541     // No constant operand, just return.
1542     if (llvm::none_of(insertSliceOp.getOperands(), [](Value operand) {
1543           return matchPattern(operand, matchConstantIndex());
1544         }))
1545       return failure();
1546 
1547     // At least one of offsets/sizes/strides is a new constant.
1548     // Form the new list of operands and constant attributes from the
1549     // existing.
1550     SmallVector<OpFoldResult> mixedOffsets(insertSliceOp.getMixedOffsets());
1551     SmallVector<OpFoldResult> mixedSizes(insertSliceOp.getMixedSizes());
1552     SmallVector<OpFoldResult> mixedStrides(insertSliceOp.getMixedStrides());
1553     canonicalizeSubViewPart(mixedOffsets, ShapedType::isDynamicStrideOrOffset);
1554     canonicalizeSubViewPart(mixedSizes, ShapedType::isDynamic);
1555     canonicalizeSubViewPart(mixedStrides, ShapedType::isDynamicStrideOrOffset);
1556 
1557     // Create the new op in canonical form.
1558     auto sourceType = ExtractSliceOp::inferRankReducedResultType(
1559         insertSliceOp.getSourceType().getRank(), insertSliceOp.getType(),
1560         mixedOffsets, mixedSizes, mixedStrides);
1561     Value toInsert = insertSliceOp.source();
1562     if (sourceType != insertSliceOp.getSourceType())
1563       toInsert = rewriter.create<tensor::CastOp>(insertSliceOp.getLoc(),
1564                                                  sourceType, toInsert);
1565     rewriter.replaceOpWithNewOp<InsertSliceOp>(
1566         insertSliceOp, toInsert, insertSliceOp.dest(), mixedOffsets, mixedSizes,
1567         mixedStrides);
1568     return success();
1569   }
1570 };
1571 
1572 /// Fold tensor_casts with insert_slice operations. If the source or destination
1573 /// tensor is a tensor_cast that removes static type information, the cast is
1574 /// folded into the insert_slice operation. E.g.:
1575 ///
1576 /// ```mlir
1577 ///   %1 = tensor.cast %0 : tensor<8x16xf32> to tensor<?x?xf32>
1578 ///   %2 = tensor.insert_slice %1 into ... : tensor<?x?xf32> into ...
1579 /// ```
1580 ///
1581 /// folds into:
1582 ///
1583 /// ```mlir
1584 ///   %2 = tensor.insert_slice %0 into ... : tensor<8x16xf32> into ...
1585 /// ```
1586 ///
1587 /// Note: When folding a cast on the destination tensor, the result of the
1588 /// insert_slice operation is casted to ensure that the type of the result did
1589 /// not change.
1590 struct InsertSliceOpCastFolder final : public OpRewritePattern<InsertSliceOp> {
1591   using OpRewritePattern<InsertSliceOp>::OpRewritePattern;
1592 
1593   LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp,
1594                                 PatternRewriter &rewriter) const override {
1595     if (llvm::any_of(insertSliceOp.getOperands(), [](Value operand) {
1596           return matchPattern(operand, matchConstantIndex());
1597         }))
1598       return failure();
1599 
1600     auto getSourceOfCastOp = [](Value v) -> Optional<Value> {
1601       auto castOp = v.getDefiningOp<tensor::CastOp>();
1602       if (!castOp || !canFoldIntoConsumerOp(castOp))
1603         return llvm::None;
1604       return castOp.source();
1605     };
1606     Optional<Value> sourceCastSource =
1607         getSourceOfCastOp(insertSliceOp.source());
1608     Optional<Value> destCastSource = getSourceOfCastOp(insertSliceOp.dest());
1609     if (!sourceCastSource && !destCastSource)
1610       return failure();
1611 
1612     auto src = (sourceCastSource ? *sourceCastSource : insertSliceOp.source());
1613     auto dst = (destCastSource ? *destCastSource : insertSliceOp.dest());
1614 
1615     auto srcType = src.getType().cast<ShapedType>();
1616     auto dstType = dst.getType().cast<ShapedType>();
1617     if (verifyInsertSliceOp(srcType, dstType, insertSliceOp.static_offsets(),
1618                             insertSliceOp.static_sizes(),
1619                             insertSliceOp.static_strides()) !=
1620         SliceVerificationResult::Success)
1621       return failure();
1622 
1623     Value replacement = rewriter.create<InsertSliceOp>(
1624         insertSliceOp.getLoc(), src, dst, insertSliceOp.getMixedOffsets(),
1625         insertSliceOp.getMixedSizes(), insertSliceOp.getMixedStrides());
1626 
1627     if (replacement.getType() != insertSliceOp.getType()) {
1628       replacement = rewriter.create<tensor::CastOp>(
1629           insertSliceOp.getLoc(), insertSliceOp.getType(), replacement);
1630     }
1631     rewriter.replaceOp(insertSliceOp, replacement);
1632     return success();
1633   }
1634 };
1635 
1636 /// If additional static type information can be deduced from a insert_slice's
1637 /// size operands, insert an explicit cast of the op's source operand. This
1638 /// enables other canonicalization patterns that are matching for tensor_cast
1639 /// ops such as `ForOpTensorCastFolder` in SCF.
1640 ///
1641 /// Example:
1642 ///
1643 /// ```mlir
1644 ///   %r = tensor.insert_slice %0 into %1[...] [64, 64] [1, 1]
1645 ///       : tensor<?x?xf32> into ...
1646 /// ```
1647 ///
1648 /// folds into:
1649 ///
1650 /// ```mlir
1651 ///   %tmp = tensor.cast %0 : tensor<?x?xf32> to tensor<64x64xf32>
1652 ///   %r = tensor.insert_slice %tmp into %1[...] [64, 64] [1, 1]
1653 ///       : tensor<64x64xf32> into ...
1654 /// ```
1655 struct InsertSliceOpSourceCastInserter final
1656     : public OpRewritePattern<InsertSliceOp> {
1657   using OpRewritePattern<InsertSliceOp>::OpRewritePattern;
1658 
1659   LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp,
1660                                 PatternRewriter &rewriter) const override {
1661     RankedTensorType srcType = insertSliceOp.getSourceType();
1662     if (srcType.getRank() != insertSliceOp.getType().getRank())
1663       return failure();
1664     SmallVector<int64_t> newSrcShape(srcType.getShape().begin(),
1665                                      srcType.getShape().end());
1666     for (int64_t i = 0; i < srcType.getRank(); ++i) {
1667       if (Optional<int64_t> constInt =
1668               getConstantIntValue(insertSliceOp.getMixedSizes()[i]))
1669         newSrcShape[i] = *constInt;
1670     }
1671 
1672     RankedTensorType newSrcType =
1673         RankedTensorType::get(newSrcShape, srcType.getElementType());
1674     if (srcType == newSrcType ||
1675         !preservesStaticInformation(srcType, newSrcType) ||
1676         !tensor::CastOp::areCastCompatible(srcType, newSrcType))
1677       return failure();
1678 
1679     // newSrcType is:
1680     //   1) Different from srcType.
1681     //   2) "More static" than srcType.
1682     //   3) Cast-compatible with srcType.
1683     // Insert the cast.
1684     Value cast = rewriter.create<tensor::CastOp>(
1685         insertSliceOp.getLoc(), newSrcType, insertSliceOp.source());
1686     rewriter.replaceOpWithNewOp<InsertSliceOp>(
1687         insertSliceOp, cast, insertSliceOp.dest(),
1688         insertSliceOp.getMixedOffsets(), insertSliceOp.getMixedSizes(),
1689         insertSliceOp.getMixedStrides());
1690     return success();
1691   }
1692 };
1693 } // namespace
1694 
1695 void InsertSliceOp::getCanonicalizationPatterns(RewritePatternSet &results,
1696                                                 MLIRContext *context) {
1697   results.add<InsertSliceOpConstantArgumentFolder, InsertSliceOpCastFolder,
1698               InsertSliceOpSourceCastInserter>(context);
1699 }
1700 
1701 Value mlir::tensor::createCanonicalRankReducingInsertSliceOp(OpBuilder &b,
1702                                                              Location loc,
1703                                                              Value tensor,
1704                                                              Value dest) {
1705   auto rankedTensorType = dest.getType().cast<RankedTensorType>();
1706   unsigned rank = rankedTensorType.getRank();
1707   auto shape = rankedTensorType.getShape();
1708   SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0));
1709   SmallVector<OpFoldResult> sizes;
1710   for (unsigned i = 0, e = rank; i < e; ++i) {
1711     OpFoldResult dim;
1712     if (rankedTensorType.isDynamicDim(i))
1713       dim = b.createOrFold<tensor::DimOp>(
1714           loc, dest, b.create<arith::ConstantIndexOp>(loc, i));
1715     else
1716       dim = b.getIndexAttr(shape[i]);
1717     sizes.push_back(dim);
1718   }
1719   SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1));
1720   return b.createOrFold<tensor::InsertSliceOp>(loc, tensor, dest, offsets,
1721                                                sizes, strides);
1722 }
1723 
1724 //===----------------------------------------------------------------------===//
1725 // PadOp
1726 //===----------------------------------------------------------------------===//
1727 
1728 // TODO: Replace custom<InferType> directive with AllTypesMatch as soon as it
1729 // supports optional types.
1730 void printInferType(OpAsmPrinter &printer, Operation *op, Value optOperand,
1731                     Type typeToInfer, Type typeToInferFrom) {}
1732 
1733 ParseResult parseInferType(OpAsmParser &parser,
1734                            Optional<OpAsmParser::OperandType> optOperand,
1735                            Type &typeToInfer, Type typeToInferFrom) {
1736   if (optOperand)
1737     typeToInfer = typeToInferFrom;
1738   return success();
1739 }
1740 
1741 LogicalResult PadOp::verify() {
1742   auto sourceType = source().getType().cast<RankedTensorType>();
1743   auto resultType = result().getType().cast<RankedTensorType>();
1744   auto expectedType =
1745       PadOp::inferResultType(sourceType, extractFromI64ArrayAttr(static_low()),
1746                              extractFromI64ArrayAttr(static_high()));
1747   for (int i = 0, e = sourceType.getRank(); i < e; ++i) {
1748     if (resultType.getDimSize(i) == expectedType.getDimSize(i))
1749       continue;
1750     if (expectedType.isDynamicDim(i))
1751       continue;
1752     return emitError("specified type ")
1753            << resultType << " does not match the inferred type "
1754            << expectedType;
1755   }
1756 
1757   return success();
1758 }
1759 
1760 LogicalResult PadOp::verifyRegions() {
1761   auto &region = getRegion();
1762   unsigned rank = result().getType().cast<RankedTensorType>().getRank();
1763   Block &block = region.front();
1764   if (block.getNumArguments() != rank)
1765     return emitError("expected the block to have ") << rank << " arguments";
1766 
1767   // Note: the number and type of yield values are checked in the YieldOp.
1768   for (const auto &en : llvm::enumerate(block.getArgumentTypes())) {
1769     if (!en.value().isIndex())
1770       return emitOpError("expected block argument ")
1771              << (en.index() + 1) << " to be an index";
1772   }
1773 
1774   // Ensure that the region yields an element of the right type.
1775   auto yieldOp = llvm::cast<YieldOp>(block.getTerminator());
1776   if (yieldOp.value().getType() !=
1777       getType().cast<ShapedType>().getElementType())
1778     return emitOpError("expected yield type to match shape element type");
1779 
1780   return success();
1781 }
1782 
1783 RankedTensorType PadOp::inferResultType(RankedTensorType sourceType,
1784                                         ArrayRef<int64_t> staticLow,
1785                                         ArrayRef<int64_t> staticHigh,
1786                                         ArrayRef<int64_t> resultShape) {
1787   unsigned rank = sourceType.getRank();
1788   assert(staticLow.size() == rank && "unexpected staticLow size mismatch");
1789   assert(staticHigh.size() == rank && "unexpected staticHigh size mismatch");
1790   assert((resultShape.empty() || resultShape.size() == rank) &&
1791          "unexpected resultShape size mismatch");
1792 
1793   SmallVector<int64_t, 4> inferredShape;
1794   for (auto i : llvm::seq<unsigned>(0, rank)) {
1795     if (sourceType.isDynamicDim(i) ||
1796         staticLow[i] == ShapedType::kDynamicSize ||
1797         staticHigh[i] == ShapedType::kDynamicSize) {
1798       inferredShape.push_back(resultShape.empty() ? ShapedType::kDynamicSize
1799                                                   : resultShape[i]);
1800     } else {
1801       int64_t size = sourceType.getDimSize(i) + staticLow[i] + staticHigh[i];
1802       assert((resultShape.empty() || size == resultShape[i] ||
1803               resultShape[i] == ShapedType::kDynamicSize) &&
1804              "mismatch between inferred shape and result shape");
1805       inferredShape.push_back(size);
1806     }
1807   }
1808 
1809   return RankedTensorType::get(inferredShape, sourceType.getElementType());
1810 }
1811 
1812 void PadOp::build(OpBuilder &b, OperationState &result, Value source,
1813                   ArrayRef<int64_t> staticLow, ArrayRef<int64_t> staticHigh,
1814                   ValueRange low, ValueRange high, bool nofold,
1815                   ArrayRef<NamedAttribute> attrs) {
1816   auto sourceType = source.getType().cast<RankedTensorType>();
1817   auto resultType = inferResultType(sourceType, staticLow, staticHigh);
1818   build(b, result, resultType, source, low, high, b.getI64ArrayAttr(staticLow),
1819         b.getI64ArrayAttr(staticHigh), nofold ? b.getUnitAttr() : UnitAttr());
1820   result.addAttributes(attrs);
1821 }
1822 
1823 void PadOp::build(OpBuilder &b, OperationState &result, Value source,
1824                   ValueRange low, ValueRange high, bool nofold,
1825                   ArrayRef<NamedAttribute> attrs) {
1826   auto sourceType = source.getType().cast<RankedTensorType>();
1827   unsigned rank = sourceType.getRank();
1828   SmallVector<int64_t, 4> staticVector(rank, ShapedType::kDynamicSize);
1829   build(b, result, source, staticVector, staticVector, low, high, nofold,
1830         attrs);
1831 }
1832 
1833 void PadOp::build(OpBuilder &b, OperationState &result, Type resultType,
1834                   Value source, ArrayRef<OpFoldResult> low,
1835                   ArrayRef<OpFoldResult> high, bool nofold,
1836                   ArrayRef<NamedAttribute> attrs) {
1837   assert(resultType.isa<RankedTensorType>());
1838   auto sourceType = source.getType().cast<RankedTensorType>();
1839   SmallVector<Value, 4> dynamicLow, dynamicHigh;
1840   SmallVector<int64_t, 4> staticLow, staticHigh;
1841   // staticLow and staticHigh have full information of the padding config.
1842   // This will grow staticLow and staticHigh with 1 value. If the config is
1843   // dynamic (ie not a constant), dynamicLow and dynamicHigh will grow with 1
1844   // value as well.
1845   dispatchIndexOpFoldResults(low, dynamicLow, staticLow,
1846                              ShapedType::kDynamicSize);
1847   dispatchIndexOpFoldResults(high, dynamicHigh, staticHigh,
1848                              ShapedType::kDynamicSize);
1849   if (!resultType) {
1850     resultType = PadOp::inferResultType(sourceType, staticLow, staticHigh);
1851   }
1852   build(b, result, resultType, source, dynamicLow, dynamicHigh,
1853         b.getI64ArrayAttr(staticLow), b.getI64ArrayAttr(staticHigh),
1854         nofold ? b.getUnitAttr() : UnitAttr());
1855   result.addAttributes(attrs);
1856 }
1857 
1858 namespace {
1859 // Folds tensor.pad when padding is static zeros and the attribute
1860 // doesn't request otherwise.
1861 struct FoldStaticZeroPadding : public OpRewritePattern<PadOp> {
1862   using OpRewritePattern<PadOp>::OpRewritePattern;
1863 
1864   LogicalResult matchAndRewrite(PadOp padTensorOp,
1865                                 PatternRewriter &rewriter) const override {
1866     if (!padTensorOp.hasZeroLowPad() || !padTensorOp.hasZeroHighPad())
1867       return failure();
1868     if (padTensorOp.nofold())
1869       return failure();
1870     rewriter.replaceOpWithNewOp<tensor::CastOp>(
1871         padTensorOp, padTensorOp.result().getType(), padTensorOp.source());
1872     return success();
1873   }
1874 };
1875 
1876 // Fold CastOp into PadOp when adding static information.
1877 struct FoldSourceTensorCast : public OpRewritePattern<PadOp> {
1878   using OpRewritePattern<PadOp>::OpRewritePattern;
1879 
1880   LogicalResult matchAndRewrite(PadOp padTensorOp,
1881                                 PatternRewriter &rewriter) const override {
1882     auto castOp = padTensorOp.source().getDefiningOp<tensor::CastOp>();
1883     if (!tensor::canFoldIntoConsumerOp(castOp))
1884       return failure();
1885 
1886     auto newResultType = PadOp::inferResultType(
1887         castOp.source().getType().cast<RankedTensorType>(),
1888         extractFromI64ArrayAttr(padTensorOp.static_low()),
1889         extractFromI64ArrayAttr(padTensorOp.static_high()),
1890         padTensorOp.getResultType().getShape());
1891 
1892     if (newResultType == padTensorOp.getResultType()) {
1893       rewriter.updateRootInPlace(padTensorOp, [&]() {
1894         padTensorOp.sourceMutable().assign(castOp.source());
1895       });
1896     } else {
1897       auto newOp = rewriter.create<PadOp>(
1898           padTensorOp->getLoc(), newResultType, padTensorOp.source(),
1899           padTensorOp.low(), padTensorOp.high(), padTensorOp.static_low(),
1900           padTensorOp.static_high(), padTensorOp.nofold());
1901       BlockAndValueMapping mapper;
1902       padTensorOp.getRegion().cloneInto(&newOp.getRegion(), mapper);
1903 
1904       rewriter.replaceOpWithNewOp<tensor::CastOp>(
1905           padTensorOp, padTensorOp.getResultType(), newOp);
1906     }
1907     return success();
1908   }
1909 };
1910 
1911 // Fold CastOp using the result of PadOp back into the latter if it adds
1912 // static information.
1913 struct FoldTargetTensorCast : public OpRewritePattern<PadOp> {
1914   using OpRewritePattern<PadOp>::OpRewritePattern;
1915 
1916   LogicalResult matchAndRewrite(PadOp padTensorOp,
1917                                 PatternRewriter &rewriter) const override {
1918     if (!padTensorOp.result().hasOneUse())
1919       return failure();
1920     auto tensorCastOp =
1921         dyn_cast<tensor::CastOp>(*padTensorOp->getUsers().begin());
1922     if (!tensorCastOp)
1923       return failure();
1924     if (!tensor::preservesStaticInformation(padTensorOp.result().getType(),
1925                                             tensorCastOp.dest().getType()))
1926       return failure();
1927 
1928     auto replacementOp = rewriter.create<PadOp>(
1929         padTensorOp.getLoc(), tensorCastOp.dest().getType(),
1930         padTensorOp.source(), padTensorOp.low(), padTensorOp.high(),
1931         padTensorOp.static_low(), padTensorOp.static_high(),
1932         padTensorOp.nofold());
1933     replacementOp.region().takeBody(padTensorOp.region());
1934 
1935     rewriter.replaceOp(padTensorOp, replacementOp.result());
1936     rewriter.replaceOp(tensorCastOp, replacementOp.result());
1937     return success();
1938   }
1939 };
1940 } // namespace
1941 
1942 void PadOp::getCanonicalizationPatterns(RewritePatternSet &results,
1943                                         MLIRContext *context) {
1944   results
1945       .add<FoldStaticZeroPadding, FoldSourceTensorCast, FoldTargetTensorCast>(
1946           context);
1947 }
1948 
1949 /// Return the padding value of the PadOp if it constant. In this context,
1950 /// "constant" means an actual constant or "defined outside of the block".
1951 ///
1952 /// Values are considered constant in three cases:
1953 ///  - A ConstantLike value.
1954 ///  - A basic block argument from a different block.
1955 ///  - A value defined outside of the block.
1956 ///
1957 /// If the padding value is not constant, an empty Value is returned.
1958 Value PadOp::getConstantPaddingValue() {
1959   auto yieldOp = dyn_cast<YieldOp>(getRegion().front().getTerminator());
1960   if (!yieldOp)
1961     return {};
1962   Value padValue = yieldOp.value();
1963   // Check if yield value is a constant.
1964   if (matchPattern(padValue, m_Constant()))
1965     return padValue;
1966   // Check if yield value is defined inside the PadOp block.
1967   if (padValue.getParentBlock() == &getRegion().front())
1968     return {};
1969   // Else: Yield value defined outside of the PadOp block.
1970   return padValue;
1971 }
1972 
1973 OpFoldResult PadOp::fold(ArrayRef<Attribute>) {
1974   if (getResultType().hasStaticShape() && getResultType() == getSourceType() &&
1975       !nofold())
1976     return source();
1977   return {};
1978 }
1979 
1980 //===----------------------------------------------------------------------===//
1981 // SplatOp
1982 //===----------------------------------------------------------------------===//
1983 
1984 OpFoldResult SplatOp::fold(ArrayRef<Attribute> operands) {
1985   auto constOperand = operands.front();
1986   if (!constOperand.isa_and_nonnull<IntegerAttr, FloatAttr>())
1987     return {};
1988 
1989   // SplatElementsAttr::get treats single value for second arg as being a splat.
1990   return SplatElementsAttr::get(getType(), {constOperand});
1991 }
1992 
1993 //===----------------------------------------------------------------------===//
1994 // TableGen'd op method definitions
1995 //===----------------------------------------------------------------------===//
1996 
1997 #define GET_OP_CLASSES
1998 #include "mlir/Dialect/Tensor/IR/TensorOps.cpp.inc"
1999