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/MemRef/IR/MemRef.h"
10 #include "mlir/Dialect/MemRef/Utils/MemRefUtils.h"
11 #include "mlir/Dialect/StandardOps/IR/Ops.h"
12 #include "mlir/Dialect/StandardOps/Utils/Utils.h"
13 #include "mlir/Dialect/Tensor/IR/Tensor.h"
14 #include "mlir/IR/AffineMap.h"
15 #include "mlir/IR/Builders.h"
16 #include "mlir/IR/BuiltinTypes.h"
17 #include "mlir/IR/Matchers.h"
18 #include "mlir/IR/PatternMatch.h"
19 #include "mlir/IR/TypeUtilities.h"
20 #include "mlir/Interfaces/InferTypeOpInterface.h"
21 #include "mlir/Interfaces/ViewLikeInterface.h"
22 #include "llvm/ADT/STLExtras.h"
23 
24 using namespace mlir;
25 using namespace mlir::memref;
26 
27 /// Materialize a single constant operation from a given attribute value with
28 /// the desired resultant type.
29 Operation *MemRefDialect::materializeConstant(OpBuilder &builder,
30                                               Attribute value, Type type,
31                                               Location loc) {
32   return builder.create<mlir::ConstantOp>(loc, type, value);
33 }
34 
35 /// Extract int64_t values from the assumed ArrayAttr of IntegerAttr.
36 static SmallVector<int64_t, 4> extractFromI64ArrayAttr(Attribute attr) {
37   return llvm::to_vector<4>(
38       llvm::map_range(attr.cast<ArrayAttr>(), [](Attribute a) -> int64_t {
39         return a.cast<IntegerAttr>().getInt();
40       }));
41 }
42 
43 /// Helper function to dispatch an OpFoldResult into either the `dynamicVec` if
44 /// it is a Value or into `staticVec` if it is an IntegerAttr.
45 /// In the case of a Value, a copy of the `sentinel` value is also pushed to
46 /// `staticVec`. This is useful to extract mixed static and dynamic entries that
47 /// come from an AttrSizedOperandSegments trait.
48 static void dispatchIndexOpFoldResult(OpFoldResult ofr,
49                                       SmallVectorImpl<Value> &dynamicVec,
50                                       SmallVectorImpl<int64_t> &staticVec,
51                                       int64_t sentinel) {
52   if (auto v = ofr.dyn_cast<Value>()) {
53     dynamicVec.push_back(v);
54     staticVec.push_back(sentinel);
55     return;
56   }
57   APInt apInt = ofr.dyn_cast<Attribute>().cast<IntegerAttr>().getValue();
58   staticVec.push_back(apInt.getSExtValue());
59 }
60 
61 static void dispatchIndexOpFoldResults(ArrayRef<OpFoldResult> ofrs,
62                                        SmallVectorImpl<Value> &dynamicVec,
63                                        SmallVectorImpl<int64_t> &staticVec,
64                                        int64_t sentinel) {
65   for (auto ofr : ofrs)
66     dispatchIndexOpFoldResult(ofr, dynamicVec, staticVec, sentinel);
67 }
68 
69 //===----------------------------------------------------------------------===//
70 // Common canonicalization pattern support logic
71 //===----------------------------------------------------------------------===//
72 
73 /// This is a common class used for patterns of the form
74 /// "someop(memrefcast) -> someop".  It folds the source of any memref.cast
75 /// into the root operation directly.
76 static LogicalResult foldMemRefCast(Operation *op, Value inner = nullptr) {
77   bool folded = false;
78   for (OpOperand &operand : op->getOpOperands()) {
79     auto cast = operand.get().getDefiningOp<CastOp>();
80     if (cast && operand.get() != inner &&
81         !cast.getOperand().getType().isa<UnrankedMemRefType>()) {
82       operand.set(cast.getOperand());
83       folded = true;
84     }
85   }
86   return success(folded);
87 }
88 
89 //===----------------------------------------------------------------------===//
90 // Helpers for GlobalOp
91 //===----------------------------------------------------------------------===//
92 
93 static Type getTensorTypeFromMemRefType(Type type) {
94   if (auto memref = type.dyn_cast<MemRefType>())
95     return RankedTensorType::get(memref.getShape(), memref.getElementType());
96   if (auto memref = type.dyn_cast<UnrankedMemRefType>())
97     return UnrankedTensorType::get(memref.getElementType());
98   return NoneType::get(type.getContext());
99 }
100 
101 //===----------------------------------------------------------------------===//
102 // AllocOp / AllocaOp
103 //===----------------------------------------------------------------------===//
104 
105 template <typename AllocLikeOp>
106 static LogicalResult verifyAllocLikeOp(AllocLikeOp op) {
107   static_assert(llvm::is_one_of<AllocLikeOp, AllocOp, AllocaOp>::value,
108                 "applies to only alloc or alloca");
109   auto memRefType = op.getResult().getType().template dyn_cast<MemRefType>();
110   if (!memRefType)
111     return op.emitOpError("result must be a memref");
112 
113   if (static_cast<int64_t>(op.dynamicSizes().size()) !=
114       memRefType.getNumDynamicDims())
115     return op.emitOpError("dimension operand count does not equal memref "
116                           "dynamic dimension count");
117 
118   unsigned numSymbols = 0;
119   if (!memRefType.getAffineMaps().empty())
120     numSymbols = memRefType.getAffineMaps().front().getNumSymbols();
121   if (op.symbolOperands().size() != numSymbols)
122     return op.emitOpError(
123         "symbol operand count does not equal memref symbol count");
124 
125   return success();
126 }
127 
128 static LogicalResult verify(AllocOp op) { return verifyAllocLikeOp(op); }
129 
130 static LogicalResult verify(AllocaOp op) {
131   // An alloca op needs to have an ancestor with an allocation scope trait.
132   if (!op->getParentWithTrait<OpTrait::AutomaticAllocationScope>())
133     return op.emitOpError(
134         "requires an ancestor op with AutomaticAllocationScope trait");
135 
136   return verifyAllocLikeOp(op);
137 }
138 
139 namespace {
140 /// Fold constant dimensions into an alloc like operation.
141 template <typename AllocLikeOp>
142 struct SimplifyAllocConst : public OpRewritePattern<AllocLikeOp> {
143   using OpRewritePattern<AllocLikeOp>::OpRewritePattern;
144 
145   LogicalResult matchAndRewrite(AllocLikeOp alloc,
146                                 PatternRewriter &rewriter) const override {
147     // Check to see if any dimensions operands are constants.  If so, we can
148     // substitute and drop them.
149     if (llvm::none_of(alloc.getOperands(), [](Value operand) {
150           return matchPattern(operand, matchConstantIndex());
151         }))
152       return failure();
153 
154     auto memrefType = alloc.getType();
155 
156     // Ok, we have one or more constant operands.  Collect the non-constant ones
157     // and keep track of the resultant memref type to build.
158     SmallVector<int64_t, 4> newShapeConstants;
159     newShapeConstants.reserve(memrefType.getRank());
160     SmallVector<Value, 4> newOperands;
161 
162     unsigned dynamicDimPos = 0;
163     for (unsigned dim = 0, e = memrefType.getRank(); dim < e; ++dim) {
164       int64_t dimSize = memrefType.getDimSize(dim);
165       // If this is already static dimension, keep it.
166       if (dimSize != -1) {
167         newShapeConstants.push_back(dimSize);
168         continue;
169       }
170       auto *defOp = alloc.getOperand(dynamicDimPos).getDefiningOp();
171       if (auto constantIndexOp = dyn_cast_or_null<ConstantIndexOp>(defOp)) {
172         // Dynamic shape dimension will be folded.
173         newShapeConstants.push_back(constantIndexOp.getValue());
174       } else {
175         // Dynamic shape dimension not folded; copy operand from old memref.
176         newShapeConstants.push_back(-1);
177         newOperands.push_back(alloc.getOperand(dynamicDimPos));
178       }
179       dynamicDimPos++;
180     }
181 
182     // Create new memref type (which will have fewer dynamic dimensions).
183     MemRefType newMemRefType =
184         MemRefType::Builder(memrefType).setShape(newShapeConstants);
185     assert(static_cast<int64_t>(newOperands.size()) ==
186            newMemRefType.getNumDynamicDims());
187 
188     // Create and insert the alloc op for the new memref.
189     auto newAlloc = rewriter.create<AllocLikeOp>(
190         alloc.getLoc(), newMemRefType, newOperands, alloc.alignmentAttr());
191     // Insert a cast so we have the same type as the old alloc.
192     auto resultCast =
193         rewriter.create<CastOp>(alloc.getLoc(), newAlloc, alloc.getType());
194 
195     rewriter.replaceOp(alloc, {resultCast});
196     return success();
197   }
198 };
199 
200 /// Fold alloc operations with no users or only store and dealloc uses.
201 template <typename T>
202 struct SimplifyDeadAlloc : public OpRewritePattern<T> {
203   using OpRewritePattern<T>::OpRewritePattern;
204 
205   LogicalResult matchAndRewrite(T alloc,
206                                 PatternRewriter &rewriter) const override {
207     if (llvm::any_of(alloc->getUsers(), [](Operation *op) {
208           return !isa<StoreOp, DeallocOp>(op);
209         }))
210       return failure();
211 
212     for (Operation *user : llvm::make_early_inc_range(alloc->getUsers()))
213       rewriter.eraseOp(user);
214 
215     rewriter.eraseOp(alloc);
216     return success();
217   }
218 };
219 } // end anonymous namespace.
220 
221 void AllocOp::getCanonicalizationPatterns(RewritePatternSet &results,
222                                           MLIRContext *context) {
223   results.add<SimplifyAllocConst<AllocOp>, SimplifyDeadAlloc<AllocOp>>(context);
224 }
225 
226 void AllocaOp::getCanonicalizationPatterns(RewritePatternSet &results,
227                                            MLIRContext *context) {
228   results.add<SimplifyAllocConst<AllocaOp>, SimplifyDeadAlloc<AllocaOp>>(
229       context);
230 }
231 
232 //===----------------------------------------------------------------------===//
233 // AllocaScopeOp
234 //===----------------------------------------------------------------------===//
235 
236 static void print(OpAsmPrinter &p, AllocaScopeOp &op) {
237   bool printBlockTerminators = false;
238 
239   p << AllocaScopeOp::getOperationName() << " ";
240   if (!op.results().empty()) {
241     p << " -> (" << op.getResultTypes() << ")";
242     printBlockTerminators = true;
243   }
244   p.printRegion(op.bodyRegion(),
245                 /*printEntryBlockArgs=*/false,
246                 /*printBlockTerminators=*/printBlockTerminators);
247   p.printOptionalAttrDict(op->getAttrs());
248 }
249 
250 static ParseResult parseAllocaScopeOp(OpAsmParser &parser,
251                                       OperationState &result) {
252   // Create a region for the body.
253   result.regions.reserve(1);
254   Region *bodyRegion = result.addRegion();
255 
256   // Parse optional results type list.
257   if (parser.parseOptionalArrowTypeList(result.types))
258     return failure();
259 
260   // Parse the body region.
261   if (parser.parseRegion(*bodyRegion, /*arguments=*/{}, /*argTypes=*/{}))
262     return failure();
263   AllocaScopeOp::ensureTerminator(*bodyRegion, parser.getBuilder(),
264                                   result.location);
265 
266   // Parse the optional attribute list.
267   if (parser.parseOptionalAttrDict(result.attributes))
268     return failure();
269 
270   return success();
271 }
272 
273 static LogicalResult verify(AllocaScopeOp op) {
274   if (failed(RegionBranchOpInterface::verifyTypes(op)))
275     return failure();
276 
277   return success();
278 }
279 
280 void AllocaScopeOp::getSuccessorRegions(
281     Optional<unsigned> index, ArrayRef<Attribute> operands,
282     SmallVectorImpl<RegionSuccessor> &regions) {
283   if (index.hasValue()) {
284     regions.push_back(RegionSuccessor(getResults()));
285     return;
286   }
287 
288   regions.push_back(RegionSuccessor(&bodyRegion()));
289 }
290 
291 //===----------------------------------------------------------------------===//
292 // AssumeAlignmentOp
293 //===----------------------------------------------------------------------===//
294 
295 static LogicalResult verify(AssumeAlignmentOp op) {
296   unsigned alignment = op.alignment();
297   if (!llvm::isPowerOf2_32(alignment))
298     return op.emitOpError("alignment must be power of 2");
299   return success();
300 }
301 
302 //===----------------------------------------------------------------------===//
303 // BufferCastOp
304 //===----------------------------------------------------------------------===//
305 
306 OpFoldResult BufferCastOp::fold(ArrayRef<Attribute>) {
307   if (auto tensorLoad = tensor().getDefiningOp<TensorLoadOp>())
308     if (tensorLoad.memref().getType() == getType())
309       return tensorLoad.memref();
310   return {};
311 }
312 
313 namespace {
314 /// Replace tensor_cast + buffer_cast by buffer_cast + memref_cast.
315 struct BufferCast : public OpRewritePattern<BufferCastOp> {
316   using OpRewritePattern<BufferCastOp>::OpRewritePattern;
317 
318   LogicalResult matchAndRewrite(BufferCastOp bufferCast,
319                                 PatternRewriter &rewriter) const final {
320     auto tensorCastOperand =
321         bufferCast.getOperand().getDefiningOp<tensor::CastOp>();
322     if (!tensorCastOperand)
323       return failure();
324     auto srcTensorType =
325         tensorCastOperand.getOperand().getType().dyn_cast<RankedTensorType>();
326     if (!srcTensorType)
327       return failure();
328     auto memrefType = MemRefType::get(srcTensorType.getShape(),
329                                       srcTensorType.getElementType());
330     Value memref = rewriter.create<BufferCastOp>(
331         bufferCast.getLoc(), memrefType, tensorCastOperand.getOperand());
332     rewriter.replaceOpWithNewOp<CastOp>(bufferCast, bufferCast.getType(),
333                                         memref);
334     return success();
335   }
336 };
337 
338 /// Canonicalize memref.tensor_load + memref.buffer_cast to memref.cast when
339 /// type mismatches prevent `BufferCastOp::fold` to kick in.
340 struct TensorLoadToMemRef : public OpRewritePattern<BufferCastOp> {
341   using OpRewritePattern<BufferCastOp>::OpRewritePattern;
342 
343   LogicalResult matchAndRewrite(BufferCastOp bufferCast,
344                                 PatternRewriter &rewriter) const final {
345     auto tensorLoad = bufferCast.tensor().getDefiningOp<TensorLoadOp>();
346     // Bail unless we have a tensor_load + memref.buffer_cast with different
347     // types. `BufferCastOp::fold` handles the same type case.
348     if (!tensorLoad || tensorLoad.memref().getType() == bufferCast.getType())
349       return failure();
350     // If types are not cast-compatible, bail.
351     if (!CastOp::areCastCompatible(tensorLoad.memref().getType(),
352                                    bufferCast.getType()))
353       return failure();
354     rewriter.replaceOpWithNewOp<CastOp>(bufferCast, bufferCast.getType(),
355                                         tensorLoad.memref());
356     return success();
357   }
358 };
359 
360 } // namespace
361 
362 void BufferCastOp::getCanonicalizationPatterns(RewritePatternSet &results,
363                                                MLIRContext *context) {
364   results.add<BufferCast, TensorLoadToMemRef>(context);
365 }
366 
367 //===----------------------------------------------------------------------===//
368 // CastOp
369 //===----------------------------------------------------------------------===//
370 
371 /// Determines whether MemRef_CastOp casts to a more dynamic version of the
372 /// source memref. This is useful to to fold a memref.cast into a consuming op
373 /// and implement canonicalization patterns for ops in different dialects that
374 /// may consume the results of memref.cast operations. Such foldable memref.cast
375 /// operations are typically inserted as `view` and `subview` ops are
376 /// canonicalized, to preserve the type compatibility of their uses.
377 ///
378 /// Returns true when all conditions are met:
379 /// 1. source and result are ranked memrefs with strided semantics and same
380 /// element type and rank.
381 /// 2. each of the source's size, offset or stride has more static information
382 /// than the corresponding result's size, offset or stride.
383 ///
384 /// Example 1:
385 /// ```mlir
386 ///   %1 = memref.cast %0 : memref<8x16xf32> to memref<?x?xf32>
387 ///   %2 = consumer %1 ... : memref<?x?xf32> ...
388 /// ```
389 ///
390 /// may fold into:
391 ///
392 /// ```mlir
393 ///   %2 = consumer %0 ... : memref<8x16xf32> ...
394 /// ```
395 ///
396 /// Example 2:
397 /// ```
398 ///   %1 = memref.cast %0 : memref<?x16xf32, affine_map<(i, j)->(16 * i + j)>>
399 ///          to memref<?x?xf32>
400 ///   consumer %1 : memref<?x?xf32> ...
401 /// ```
402 ///
403 /// may fold into:
404 ///
405 /// ```
406 ///   consumer %0 ... : memref<?x16xf32, affine_map<(i, j)->(16 * i + j)>>
407 /// ```
408 bool CastOp::canFoldIntoConsumerOp(CastOp castOp) {
409   MemRefType sourceType = castOp.source().getType().dyn_cast<MemRefType>();
410   MemRefType resultType = castOp.getType().dyn_cast<MemRefType>();
411 
412   // Requires ranked MemRefType.
413   if (!sourceType || !resultType)
414     return false;
415 
416   // Requires same elemental type.
417   if (sourceType.getElementType() != resultType.getElementType())
418     return false;
419 
420   // Requires same rank.
421   if (sourceType.getRank() != resultType.getRank())
422     return false;
423 
424   // Only fold casts between strided memref forms.
425   int64_t sourceOffset, resultOffset;
426   SmallVector<int64_t, 4> sourceStrides, resultStrides;
427   if (failed(getStridesAndOffset(sourceType, sourceStrides, sourceOffset)) ||
428       failed(getStridesAndOffset(resultType, resultStrides, resultOffset)))
429     return false;
430 
431   // If cast is towards more static sizes along any dimension, don't fold.
432   for (auto it : llvm::zip(sourceType.getShape(), resultType.getShape())) {
433     auto ss = std::get<0>(it), st = std::get<1>(it);
434     if (ss != st)
435       if (MemRefType::isDynamic(ss) && !MemRefType::isDynamic(st))
436         return false;
437   }
438 
439   // If cast is towards more static offset along any dimension, don't fold.
440   if (sourceOffset != resultOffset)
441     if (MemRefType::isDynamicStrideOrOffset(sourceOffset) &&
442         !MemRefType::isDynamicStrideOrOffset(resultOffset))
443       return false;
444 
445   // If cast is towards more static strides along any dimension, don't fold.
446   for (auto it : llvm::zip(sourceStrides, resultStrides)) {
447     auto ss = std::get<0>(it), st = std::get<1>(it);
448     if (ss != st)
449       if (MemRefType::isDynamicStrideOrOffset(ss) &&
450           !MemRefType::isDynamicStrideOrOffset(st))
451         return false;
452   }
453 
454   return true;
455 }
456 
457 bool CastOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
458   if (inputs.size() != 1 || outputs.size() != 1)
459     return false;
460   Type a = inputs.front(), b = outputs.front();
461   auto aT = a.dyn_cast<MemRefType>();
462   auto bT = b.dyn_cast<MemRefType>();
463 
464   auto uaT = a.dyn_cast<UnrankedMemRefType>();
465   auto ubT = b.dyn_cast<UnrankedMemRefType>();
466 
467   if (aT && bT) {
468     if (aT.getElementType() != bT.getElementType())
469       return false;
470     if (aT.getAffineMaps() != bT.getAffineMaps()) {
471       int64_t aOffset, bOffset;
472       SmallVector<int64_t, 4> aStrides, bStrides;
473       if (failed(getStridesAndOffset(aT, aStrides, aOffset)) ||
474           failed(getStridesAndOffset(bT, bStrides, bOffset)) ||
475           aStrides.size() != bStrides.size())
476         return false;
477 
478       // Strides along a dimension/offset are compatible if the value in the
479       // source memref is static and the value in the target memref is the
480       // same. They are also compatible if either one is dynamic (see
481       // description of MemRefCastOp for details).
482       auto checkCompatible = [](int64_t a, int64_t b) {
483         return (a == MemRefType::getDynamicStrideOrOffset() ||
484                 b == MemRefType::getDynamicStrideOrOffset() || a == b);
485       };
486       if (!checkCompatible(aOffset, bOffset))
487         return false;
488       for (auto aStride : enumerate(aStrides))
489         if (!checkCompatible(aStride.value(), bStrides[aStride.index()]))
490           return false;
491     }
492     if (aT.getMemorySpace() != bT.getMemorySpace())
493       return false;
494 
495     // They must have the same rank, and any specified dimensions must match.
496     if (aT.getRank() != bT.getRank())
497       return false;
498 
499     for (unsigned i = 0, e = aT.getRank(); i != e; ++i) {
500       int64_t aDim = aT.getDimSize(i), bDim = bT.getDimSize(i);
501       if (aDim != -1 && bDim != -1 && aDim != bDim)
502         return false;
503     }
504     return true;
505   } else {
506     if (!aT && !uaT)
507       return false;
508     if (!bT && !ubT)
509       return false;
510     // Unranked to unranked casting is unsupported
511     if (uaT && ubT)
512       return false;
513 
514     auto aEltType = (aT) ? aT.getElementType() : uaT.getElementType();
515     auto bEltType = (bT) ? bT.getElementType() : ubT.getElementType();
516     if (aEltType != bEltType)
517       return false;
518 
519     auto aMemSpace = (aT) ? aT.getMemorySpace() : uaT.getMemorySpace();
520     auto bMemSpace = (bT) ? bT.getMemorySpace() : ubT.getMemorySpace();
521     if (aMemSpace != bMemSpace)
522       return false;
523 
524     return true;
525   }
526 
527   return false;
528 }
529 
530 OpFoldResult CastOp::fold(ArrayRef<Attribute> operands) {
531   return succeeded(foldMemRefCast(*this)) ? getResult() : Value();
532 }
533 
534 //===----------------------------------------------------------------------===//
535 // CloneOp
536 //===----------------------------------------------------------------------===//
537 
538 void CloneOp::getEffects(
539     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
540         &effects) {
541   effects.emplace_back(MemoryEffects::Read::get(), input(),
542                        SideEffects::DefaultResource::get());
543   effects.emplace_back(MemoryEffects::Write::get(), output(),
544                        SideEffects::DefaultResource::get());
545 }
546 
547 namespace {
548 /// Fold Dealloc operations that are deallocating an AllocOp that is only used
549 /// by other Dealloc operations.
550 struct SimplifyClones : public OpRewritePattern<CloneOp> {
551   using OpRewritePattern<CloneOp>::OpRewritePattern;
552 
553   LogicalResult matchAndRewrite(CloneOp cloneOp,
554                                 PatternRewriter &rewriter) const override {
555     if (cloneOp.use_empty()) {
556       rewriter.eraseOp(cloneOp);
557       return success();
558     }
559 
560     Value source = cloneOp.input();
561 
562     // This only finds dealloc operations for the immediate value. It should
563     // also consider aliases. That would also make the safety check below
564     // redundant.
565     Operation *cloneDeallocOp = findDealloc(cloneOp.output());
566     Operation *sourceDeallocOp = findDealloc(source);
567 
568     // If both are deallocated in the same block, their in-block lifetimes
569     // might not fully overlap, so we cannot decide which one to drop.
570     if (cloneDeallocOp && sourceDeallocOp &&
571         cloneDeallocOp->getBlock() == sourceDeallocOp->getBlock())
572       return failure();
573 
574     Block *currentBlock = cloneOp->getBlock();
575     Operation *redundantDealloc = nullptr;
576     if (cloneDeallocOp && cloneDeallocOp->getBlock() == currentBlock) {
577       redundantDealloc = cloneDeallocOp;
578     } else if (sourceDeallocOp && sourceDeallocOp->getBlock() == currentBlock) {
579       redundantDealloc = sourceDeallocOp;
580     }
581 
582     if (!redundantDealloc)
583       return failure();
584 
585     // Safety check that there are no other deallocations inbetween
586     // cloneOp and redundantDealloc, as otherwise we might deallocate an alias
587     // of source before the uses of the clone. With alias information, we could
588     // restrict this to only fail of the dealloc's operand is an alias
589     // of the source.
590     for (Operation *pos = cloneOp->getNextNode(); pos != redundantDealloc;
591          pos = pos->getNextNode()) {
592       auto effectInterface = dyn_cast<MemoryEffectOpInterface>(pos);
593       if (!effectInterface)
594         continue;
595       if (effectInterface.hasEffect<MemoryEffects::Free>())
596         return failure();
597     }
598 
599     rewriter.replaceOpWithNewOp<memref::CastOp>(cloneOp, cloneOp.getType(),
600                                                 source);
601     rewriter.eraseOp(redundantDealloc);
602     return success();
603   }
604 };
605 
606 } // end anonymous namespace.
607 
608 void CloneOp::getCanonicalizationPatterns(OwningRewritePatternList &results,
609                                           MLIRContext *context) {
610   results.insert<SimplifyClones>(context);
611 }
612 
613 OpFoldResult CloneOp::fold(ArrayRef<Attribute> operands) {
614   return succeeded(foldMemRefCast(*this)) ? getResult() : Value();
615 }
616 
617 //===----------------------------------------------------------------------===//
618 // DeallocOp
619 //===----------------------------------------------------------------------===//
620 
621 LogicalResult DeallocOp::fold(ArrayRef<Attribute> cstOperands,
622                               SmallVectorImpl<OpFoldResult> &results) {
623   /// dealloc(memrefcast) -> dealloc
624   return foldMemRefCast(*this);
625 }
626 
627 //===----------------------------------------------------------------------===//
628 // DimOp
629 //===----------------------------------------------------------------------===//
630 
631 void DimOp::build(OpBuilder &builder, OperationState &result, Value memref,
632                   int64_t index) {
633   auto loc = result.location;
634   Value indexValue = builder.create<ConstantIndexOp>(loc, index);
635   build(builder, result, memref, indexValue);
636 }
637 
638 void DimOp::build(OpBuilder &builder, OperationState &result, Value memref,
639                   Value index) {
640   auto indexTy = builder.getIndexType();
641   build(builder, result, indexTy, memref, index);
642 }
643 
644 Optional<int64_t> DimOp::getConstantIndex() {
645   if (auto constantOp = index().getDefiningOp<ConstantOp>())
646     return constantOp.getValue().cast<IntegerAttr>().getInt();
647   return {};
648 }
649 
650 static LogicalResult verify(DimOp op) {
651   // Assume unknown index to be in range.
652   Optional<int64_t> index = op.getConstantIndex();
653   if (!index.hasValue())
654     return success();
655 
656   // Check that constant index is not knowingly out of range.
657   auto type = op.memrefOrTensor().getType();
658   if (auto memrefType = type.dyn_cast<MemRefType>()) {
659     if (index.getValue() >= memrefType.getRank())
660       return op.emitOpError("index is out of range");
661   } else if (auto tensorType = type.dyn_cast<RankedTensorType>()) {
662     if (index.getValue() >= tensorType.getRank())
663       return op.emitOpError("index is out of range");
664   } else if (type.isa<UnrankedMemRefType>() || type.isa<UnrankedTensorType>()) {
665     // Assume index to be in range.
666   } else {
667     llvm_unreachable("expected operand with memref type");
668   }
669   return success();
670 }
671 
672 OpFoldResult DimOp::fold(ArrayRef<Attribute> operands) {
673   auto index = operands[1].dyn_cast_or_null<IntegerAttr>();
674 
675   // All forms of folding require a known index.
676   if (!index)
677     return {};
678 
679   auto argTy = memrefOrTensor().getType();
680   // Fold if the shape extent along the given index is known.
681   if (auto shapedTy = argTy.dyn_cast<ShapedType>()) {
682     // Folding for unranked types (UnrankedMemRefType) is not supported.
683     if (!shapedTy.hasRank())
684       return {};
685     if (!shapedTy.isDynamicDim(index.getInt())) {
686       Builder builder(getContext());
687       return builder.getIndexAttr(shapedTy.getShape()[index.getInt()]);
688     }
689   }
690 
691   Operation *definingOp = memrefOrTensor().getDefiningOp();
692 
693   // dim(memref.tensor_load(memref)) -> dim(memref)
694   if (auto tensorLoadOp = dyn_cast_or_null<TensorLoadOp>(definingOp)) {
695     setOperand(0, tensorLoadOp.memref());
696     return getResult();
697   }
698 
699   // Fold dim to the operand of tensor.generate.
700   if (auto fromElements = dyn_cast_or_null<tensor::GenerateOp>(definingOp)) {
701     auto resultType =
702         fromElements.getResult().getType().cast<RankedTensorType>();
703     // The case where the type encodes the size of the dimension is handled
704     // above.
705     assert(resultType.getShape()[index.getInt()] ==
706            RankedTensorType::kDynamicSize);
707 
708     // Find the operand of the fromElements that corresponds to this index.
709     auto dynExtents = fromElements.dynamicExtents().begin();
710     for (auto dim : resultType.getShape().take_front(index.getInt()))
711       if (dim == RankedTensorType::kDynamicSize)
712         dynExtents++;
713 
714     return Value{*dynExtents};
715   }
716 
717   // The size at the given index is now known to be a dynamic size.
718   unsigned unsignedIndex = index.getValue().getZExtValue();
719 
720   if (auto subtensor = dyn_cast_or_null<mlir::SubTensorOp>(definingOp)) {
721     assert(subtensor.isDynamicSize(unsignedIndex) &&
722            "Expected dynamic subtensor size");
723     return subtensor.getDynamicSize(unsignedIndex);
724   }
725 
726   // Fold dim to the size argument for an `AllocOp`, `ViewOp`, or `SubViewOp`.
727   auto memrefType = argTy.dyn_cast<MemRefType>();
728   if (!memrefType)
729     return {};
730 
731   if (auto alloc = dyn_cast_or_null<AllocOp>(definingOp))
732     return *(alloc.getDynamicSizes().begin() +
733              memrefType.getDynamicDimIndex(unsignedIndex));
734 
735   if (auto alloca = dyn_cast_or_null<AllocaOp>(definingOp))
736     return *(alloca.getDynamicSizes().begin() +
737              memrefType.getDynamicDimIndex(unsignedIndex));
738 
739   if (auto view = dyn_cast_or_null<ViewOp>(definingOp))
740     return *(view.getDynamicSizes().begin() +
741              memrefType.getDynamicDimIndex(unsignedIndex));
742 
743   if (auto sizeInterface =
744           dyn_cast_or_null<OffsetSizeAndStrideOpInterface>(definingOp)) {
745     assert(sizeInterface.isDynamicSize(unsignedIndex) &&
746            "Expected dynamic subview size");
747     return sizeInterface.getDynamicSize(unsignedIndex);
748   }
749 
750   // dim(memrefcast) -> dim
751   if (succeeded(foldMemRefCast(*this)))
752     return getResult();
753 
754   return {};
755 }
756 
757 namespace {
758 /// Fold dim of a memref reshape operation to a load into the reshape's shape
759 /// operand.
760 struct DimOfMemRefReshape : public OpRewritePattern<DimOp> {
761   using OpRewritePattern<DimOp>::OpRewritePattern;
762 
763   LogicalResult matchAndRewrite(DimOp dim,
764                                 PatternRewriter &rewriter) const override {
765     auto reshape = dim.memrefOrTensor().getDefiningOp<ReshapeOp>();
766 
767     if (!reshape)
768       return failure();
769 
770     // Place the load directly after the reshape to ensure that the shape memref
771     // was not mutated.
772     rewriter.setInsertionPointAfter(reshape);
773     Location loc = dim.getLoc();
774     Value load = rewriter.create<LoadOp>(loc, reshape.shape(), dim.index());
775     if (load.getType() != dim.getType())
776       load = rewriter.create<IndexCastOp>(loc, dim.getType(), load);
777     rewriter.replaceOp(dim, load);
778     return success();
779   }
780 };
781 
782 /// Fold dim of a dim of a cast into the dim of the source of the tensor cast.
783 template <typename CastOpTy>
784 struct DimOfCastOp : public OpRewritePattern<DimOp> {
785   using OpRewritePattern<DimOp>::OpRewritePattern;
786 
787   LogicalResult matchAndRewrite(DimOp dimOp,
788                                 PatternRewriter &rewriter) const override {
789     auto castOp = dimOp.memrefOrTensor().getDefiningOp<CastOpTy>();
790     if (!castOp)
791       return failure();
792     Value newSource = castOp.getOperand();
793     rewriter.replaceOpWithNewOp<DimOp>(dimOp, newSource, dimOp.index());
794     return success();
795   }
796 };
797 } // end anonymous namespace.
798 
799 void DimOp::getCanonicalizationPatterns(RewritePatternSet &results,
800                                         MLIRContext *context) {
801   results.add<DimOfMemRefReshape, DimOfCastOp<BufferCastOp>,
802               DimOfCastOp<tensor::CastOp>>(context);
803 }
804 
805 // ---------------------------------------------------------------------------
806 // DmaStartOp
807 // ---------------------------------------------------------------------------
808 
809 void DmaStartOp::build(OpBuilder &builder, OperationState &result,
810                        Value srcMemRef, ValueRange srcIndices, Value destMemRef,
811                        ValueRange destIndices, Value numElements,
812                        Value tagMemRef, ValueRange tagIndices, Value stride,
813                        Value elementsPerStride) {
814   result.addOperands(srcMemRef);
815   result.addOperands(srcIndices);
816   result.addOperands(destMemRef);
817   result.addOperands(destIndices);
818   result.addOperands({numElements, tagMemRef});
819   result.addOperands(tagIndices);
820   if (stride)
821     result.addOperands({stride, elementsPerStride});
822 }
823 
824 void DmaStartOp::print(OpAsmPrinter &p) {
825   p << getOperationName() << " " << getSrcMemRef() << '[' << getSrcIndices()
826     << "], " << getDstMemRef() << '[' << getDstIndices() << "], "
827     << getNumElements() << ", " << getTagMemRef() << '[' << getTagIndices()
828     << ']';
829   if (isStrided())
830     p << ", " << getStride() << ", " << getNumElementsPerStride();
831 
832   p.printOptionalAttrDict((*this)->getAttrs());
833   p << " : " << getSrcMemRef().getType() << ", " << getDstMemRef().getType()
834     << ", " << getTagMemRef().getType();
835 }
836 
837 // Parse DmaStartOp.
838 // Ex:
839 //   %dma_id = dma_start %src[%i, %j], %dst[%k, %l], %size,
840 //                       %tag[%index], %stride, %num_elt_per_stride :
841 //                     : memref<3076 x f32, 0>,
842 //                       memref<1024 x f32, 2>,
843 //                       memref<1 x i32>
844 //
845 ParseResult DmaStartOp::parse(OpAsmParser &parser, OperationState &result) {
846   OpAsmParser::OperandType srcMemRefInfo;
847   SmallVector<OpAsmParser::OperandType, 4> srcIndexInfos;
848   OpAsmParser::OperandType dstMemRefInfo;
849   SmallVector<OpAsmParser::OperandType, 4> dstIndexInfos;
850   OpAsmParser::OperandType numElementsInfo;
851   OpAsmParser::OperandType tagMemrefInfo;
852   SmallVector<OpAsmParser::OperandType, 4> tagIndexInfos;
853   SmallVector<OpAsmParser::OperandType, 2> strideInfo;
854 
855   SmallVector<Type, 3> types;
856   auto indexType = parser.getBuilder().getIndexType();
857 
858   // Parse and resolve the following list of operands:
859   // *) source memref followed by its indices (in square brackets).
860   // *) destination memref followed by its indices (in square brackets).
861   // *) dma size in KiB.
862   if (parser.parseOperand(srcMemRefInfo) ||
863       parser.parseOperandList(srcIndexInfos, OpAsmParser::Delimiter::Square) ||
864       parser.parseComma() || parser.parseOperand(dstMemRefInfo) ||
865       parser.parseOperandList(dstIndexInfos, OpAsmParser::Delimiter::Square) ||
866       parser.parseComma() || parser.parseOperand(numElementsInfo) ||
867       parser.parseComma() || parser.parseOperand(tagMemrefInfo) ||
868       parser.parseOperandList(tagIndexInfos, OpAsmParser::Delimiter::Square))
869     return failure();
870 
871   // Parse optional stride and elements per stride.
872   if (parser.parseTrailingOperandList(strideInfo))
873     return failure();
874 
875   bool isStrided = strideInfo.size() == 2;
876   if (!strideInfo.empty() && !isStrided) {
877     return parser.emitError(parser.getNameLoc(),
878                             "expected two stride related operands");
879   }
880 
881   if (parser.parseColonTypeList(types))
882     return failure();
883   if (types.size() != 3)
884     return parser.emitError(parser.getNameLoc(), "fewer/more types expected");
885 
886   if (parser.resolveOperand(srcMemRefInfo, types[0], result.operands) ||
887       parser.resolveOperands(srcIndexInfos, indexType, result.operands) ||
888       parser.resolveOperand(dstMemRefInfo, types[1], result.operands) ||
889       parser.resolveOperands(dstIndexInfos, indexType, result.operands) ||
890       // size should be an index.
891       parser.resolveOperand(numElementsInfo, indexType, result.operands) ||
892       parser.resolveOperand(tagMemrefInfo, types[2], result.operands) ||
893       // tag indices should be index.
894       parser.resolveOperands(tagIndexInfos, indexType, result.operands))
895     return failure();
896 
897   if (isStrided) {
898     if (parser.resolveOperands(strideInfo, indexType, result.operands))
899       return failure();
900   }
901 
902   return success();
903 }
904 
905 LogicalResult DmaStartOp::verify() {
906   unsigned numOperands = getNumOperands();
907 
908   // Mandatory non-variadic operands are: src memref, dst memref, tag memref and
909   // the number of elements.
910   if (numOperands < 4)
911     return emitOpError("expected at least 4 operands");
912 
913   // Check types of operands. The order of these calls is important: the later
914   // calls rely on some type properties to compute the operand position.
915   // 1. Source memref.
916   if (!getSrcMemRef().getType().isa<MemRefType>())
917     return emitOpError("expected source to be of memref type");
918   if (numOperands < getSrcMemRefRank() + 4)
919     return emitOpError() << "expected at least " << getSrcMemRefRank() + 4
920                          << " operands";
921   if (!getSrcIndices().empty() &&
922       !llvm::all_of(getSrcIndices().getTypes(),
923                     [](Type t) { return t.isIndex(); }))
924     return emitOpError("expected source indices to be of index type");
925 
926   // 2. Destination memref.
927   if (!getDstMemRef().getType().isa<MemRefType>())
928     return emitOpError("expected destination to be of memref type");
929   unsigned numExpectedOperands = getSrcMemRefRank() + getDstMemRefRank() + 4;
930   if (numOperands < numExpectedOperands)
931     return emitOpError() << "expected at least " << numExpectedOperands
932                          << " operands";
933   if (!getDstIndices().empty() &&
934       !llvm::all_of(getDstIndices().getTypes(),
935                     [](Type t) { return t.isIndex(); }))
936     return emitOpError("expected destination indices to be of index type");
937 
938   // 3. Number of elements.
939   if (!getNumElements().getType().isIndex())
940     return emitOpError("expected num elements to be of index type");
941 
942   // 4. Tag memref.
943   if (!getTagMemRef().getType().isa<MemRefType>())
944     return emitOpError("expected tag to be of memref type");
945   numExpectedOperands += getTagMemRefRank();
946   if (numOperands < numExpectedOperands)
947     return emitOpError() << "expected at least " << numExpectedOperands
948                          << " operands";
949   if (!getTagIndices().empty() &&
950       !llvm::all_of(getTagIndices().getTypes(),
951                     [](Type t) { return t.isIndex(); }))
952     return emitOpError("expected tag indices to be of index type");
953 
954   // Optional stride-related operands must be either both present or both
955   // absent.
956   if (numOperands != numExpectedOperands &&
957       numOperands != numExpectedOperands + 2)
958     return emitOpError("incorrect number of operands");
959 
960   // 5. Strides.
961   if (isStrided()) {
962     if (!getStride().getType().isIndex() ||
963         !getNumElementsPerStride().getType().isIndex())
964       return emitOpError(
965           "expected stride and num elements per stride to be of type index");
966   }
967 
968   return success();
969 }
970 
971 LogicalResult DmaStartOp::fold(ArrayRef<Attribute> cstOperands,
972                                SmallVectorImpl<OpFoldResult> &results) {
973   /// dma_start(memrefcast) -> dma_start
974   return foldMemRefCast(*this);
975 }
976 
977 // ---------------------------------------------------------------------------
978 // DmaWaitOp
979 // ---------------------------------------------------------------------------
980 
981 void DmaWaitOp::build(OpBuilder &builder, OperationState &result,
982                       Value tagMemRef, ValueRange tagIndices,
983                       Value numElements) {
984   result.addOperands(tagMemRef);
985   result.addOperands(tagIndices);
986   result.addOperands(numElements);
987 }
988 
989 void DmaWaitOp::print(OpAsmPrinter &p) {
990   p << getOperationName() << " " << getTagMemRef() << '[' << getTagIndices()
991     << "], " << getNumElements();
992   p.printOptionalAttrDict((*this)->getAttrs());
993   p << " : " << getTagMemRef().getType();
994 }
995 
996 // Parse DmaWaitOp.
997 // Eg:
998 //   dma_wait %tag[%index], %num_elements : memref<1 x i32, (d0) -> (d0), 4>
999 //
1000 ParseResult DmaWaitOp::parse(OpAsmParser &parser, OperationState &result) {
1001   OpAsmParser::OperandType tagMemrefInfo;
1002   SmallVector<OpAsmParser::OperandType, 2> tagIndexInfos;
1003   Type type;
1004   auto indexType = parser.getBuilder().getIndexType();
1005   OpAsmParser::OperandType numElementsInfo;
1006 
1007   // Parse tag memref, its indices, and dma size.
1008   if (parser.parseOperand(tagMemrefInfo) ||
1009       parser.parseOperandList(tagIndexInfos, OpAsmParser::Delimiter::Square) ||
1010       parser.parseComma() || parser.parseOperand(numElementsInfo) ||
1011       parser.parseColonType(type) ||
1012       parser.resolveOperand(tagMemrefInfo, type, result.operands) ||
1013       parser.resolveOperands(tagIndexInfos, indexType, result.operands) ||
1014       parser.resolveOperand(numElementsInfo, indexType, result.operands))
1015     return failure();
1016 
1017   return success();
1018 }
1019 
1020 LogicalResult DmaWaitOp::fold(ArrayRef<Attribute> cstOperands,
1021                               SmallVectorImpl<OpFoldResult> &results) {
1022   /// dma_wait(memrefcast) -> dma_wait
1023   return foldMemRefCast(*this);
1024 }
1025 
1026 LogicalResult DmaWaitOp::verify() {
1027   // Mandatory non-variadic operands are tag and the number of elements.
1028   if (getNumOperands() < 2)
1029     return emitOpError() << "expected at least 2 operands";
1030 
1031   // Check types of operands. The order of these calls is important: the later
1032   // calls rely on some type properties to compute the operand position.
1033   if (!getTagMemRef().getType().isa<MemRefType>())
1034     return emitOpError() << "expected tag to be of memref type";
1035 
1036   if (getNumOperands() != 2 + getTagMemRefRank())
1037     return emitOpError() << "expected " << 2 + getTagMemRefRank()
1038                          << " operands";
1039 
1040   if (!getTagIndices().empty() &&
1041       !llvm::all_of(getTagIndices().getTypes(),
1042                     [](Type t) { return t.isIndex(); }))
1043     return emitOpError() << "expected tag indices to be of index type";
1044 
1045   if (!getNumElements().getType().isIndex())
1046     return emitOpError()
1047            << "expected the number of elements to be of index type";
1048 
1049   return success();
1050 }
1051 
1052 //===----------------------------------------------------------------------===//
1053 // GlobalOp
1054 //===----------------------------------------------------------------------===//
1055 
1056 static void printGlobalMemrefOpTypeAndInitialValue(OpAsmPrinter &p, GlobalOp op,
1057                                                    TypeAttr type,
1058                                                    Attribute initialValue) {
1059   p << type;
1060   if (!op.isExternal()) {
1061     p << " = ";
1062     if (op.isUninitialized())
1063       p << "uninitialized";
1064     else
1065       p.printAttributeWithoutType(initialValue);
1066   }
1067 }
1068 
1069 static ParseResult
1070 parseGlobalMemrefOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr,
1071                                        Attribute &initialValue) {
1072   Type type;
1073   if (parser.parseType(type))
1074     return failure();
1075 
1076   auto memrefType = type.dyn_cast<MemRefType>();
1077   if (!memrefType || !memrefType.hasStaticShape())
1078     return parser.emitError(parser.getNameLoc())
1079            << "type should be static shaped memref, but got " << type;
1080   typeAttr = TypeAttr::get(type);
1081 
1082   if (parser.parseOptionalEqual())
1083     return success();
1084 
1085   if (succeeded(parser.parseOptionalKeyword("uninitialized"))) {
1086     initialValue = UnitAttr::get(parser.getBuilder().getContext());
1087     return success();
1088   }
1089 
1090   Type tensorType = getTensorTypeFromMemRefType(memrefType);
1091   if (parser.parseAttribute(initialValue, tensorType))
1092     return failure();
1093   if (!initialValue.isa<ElementsAttr>())
1094     return parser.emitError(parser.getNameLoc())
1095            << "initial value should be a unit or elements attribute";
1096   return success();
1097 }
1098 
1099 static LogicalResult verify(GlobalOp op) {
1100   auto memrefType = op.type().dyn_cast<MemRefType>();
1101   if (!memrefType || !memrefType.hasStaticShape())
1102     return op.emitOpError("type should be static shaped memref, but got ")
1103            << op.type();
1104 
1105   // Verify that the initial value, if present, is either a unit attribute or
1106   // an elements attribute.
1107   if (op.initial_value().hasValue()) {
1108     Attribute initValue = op.initial_value().getValue();
1109     if (!initValue.isa<UnitAttr>() && !initValue.isa<ElementsAttr>())
1110       return op.emitOpError("initial value should be a unit or elements "
1111                             "attribute, but got ")
1112              << initValue;
1113 
1114     // Check that the type of the initial value is compatible with the type of
1115     // the global variable.
1116     if (initValue.isa<ElementsAttr>()) {
1117       Type initType = initValue.getType();
1118       Type tensorType = getTensorTypeFromMemRefType(memrefType);
1119       if (initType != tensorType)
1120         return op.emitOpError("initial value expected to be of type ")
1121                << tensorType << ", but was of type " << initType;
1122     }
1123   }
1124 
1125   // TODO: verify visibility for declarations.
1126   return success();
1127 }
1128 
1129 //===----------------------------------------------------------------------===//
1130 // GetGlobalOp
1131 //===----------------------------------------------------------------------===//
1132 
1133 LogicalResult
1134 GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1135   // Verify that the result type is same as the type of the referenced
1136   // memref.global op.
1137   auto global =
1138       symbolTable.lookupNearestSymbolFrom<GlobalOp>(*this, nameAttr());
1139   if (!global)
1140     return emitOpError("'")
1141            << name() << "' does not reference a valid global memref";
1142 
1143   Type resultType = result().getType();
1144   if (global.type() != resultType)
1145     return emitOpError("result type ")
1146            << resultType << " does not match type " << global.type()
1147            << " of the global memref @" << name();
1148   return success();
1149 }
1150 
1151 //===----------------------------------------------------------------------===//
1152 // LoadOp
1153 //===----------------------------------------------------------------------===//
1154 
1155 static LogicalResult verify(LoadOp op) {
1156   if (op.getNumOperands() != 1 + op.getMemRefType().getRank())
1157     return op.emitOpError("incorrect number of indices for load");
1158   return success();
1159 }
1160 
1161 OpFoldResult LoadOp::fold(ArrayRef<Attribute> cstOperands) {
1162   /// load(memrefcast) -> load
1163   if (succeeded(foldMemRefCast(*this)))
1164     return getResult();
1165   return OpFoldResult();
1166 }
1167 
1168 namespace {
1169 /// Fold a load on a buffer_cast operation into an tensor.extract on the
1170 /// corresponding tensor.
1171 struct LoadOfBufferCast : public OpRewritePattern<LoadOp> {
1172   using OpRewritePattern<LoadOp>::OpRewritePattern;
1173 
1174   LogicalResult matchAndRewrite(LoadOp load,
1175                                 PatternRewriter &rewriter) const override {
1176     auto buffercast = load.memref().getDefiningOp<BufferCastOp>();
1177     if (!buffercast)
1178       return failure();
1179 
1180     rewriter.replaceOpWithNewOp<tensor::ExtractOp>(load, buffercast.tensor(),
1181                                                    load.indices());
1182     return success();
1183   }
1184 };
1185 } // end anonymous namespace.
1186 
1187 void LoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
1188                                          MLIRContext *context) {
1189   results.add<LoadOfBufferCast>(context);
1190 }
1191 
1192 //===----------------------------------------------------------------------===//
1193 // PrefetchOp
1194 //===----------------------------------------------------------------------===//
1195 
1196 static void print(OpAsmPrinter &p, PrefetchOp op) {
1197   p << PrefetchOp::getOperationName() << " " << op.memref() << '[';
1198   p.printOperands(op.indices());
1199   p << ']' << ", " << (op.isWrite() ? "write" : "read");
1200   p << ", locality<" << op.localityHint();
1201   p << ">, " << (op.isDataCache() ? "data" : "instr");
1202   p.printOptionalAttrDict(
1203       op->getAttrs(),
1204       /*elidedAttrs=*/{"localityHint", "isWrite", "isDataCache"});
1205   p << " : " << op.getMemRefType();
1206 }
1207 
1208 static ParseResult parsePrefetchOp(OpAsmParser &parser,
1209                                    OperationState &result) {
1210   OpAsmParser::OperandType memrefInfo;
1211   SmallVector<OpAsmParser::OperandType, 4> indexInfo;
1212   IntegerAttr localityHint;
1213   MemRefType type;
1214   StringRef readOrWrite, cacheType;
1215 
1216   auto indexTy = parser.getBuilder().getIndexType();
1217   auto i32Type = parser.getBuilder().getIntegerType(32);
1218   if (parser.parseOperand(memrefInfo) ||
1219       parser.parseOperandList(indexInfo, OpAsmParser::Delimiter::Square) ||
1220       parser.parseComma() || parser.parseKeyword(&readOrWrite) ||
1221       parser.parseComma() || parser.parseKeyword("locality") ||
1222       parser.parseLess() ||
1223       parser.parseAttribute(localityHint, i32Type, "localityHint",
1224                             result.attributes) ||
1225       parser.parseGreater() || parser.parseComma() ||
1226       parser.parseKeyword(&cacheType) || parser.parseColonType(type) ||
1227       parser.resolveOperand(memrefInfo, type, result.operands) ||
1228       parser.resolveOperands(indexInfo, indexTy, result.operands))
1229     return failure();
1230 
1231   if (!readOrWrite.equals("read") && !readOrWrite.equals("write"))
1232     return parser.emitError(parser.getNameLoc(),
1233                             "rw specifier has to be 'read' or 'write'");
1234   result.addAttribute(
1235       PrefetchOp::getIsWriteAttrName(),
1236       parser.getBuilder().getBoolAttr(readOrWrite.equals("write")));
1237 
1238   if (!cacheType.equals("data") && !cacheType.equals("instr"))
1239     return parser.emitError(parser.getNameLoc(),
1240                             "cache type has to be 'data' or 'instr'");
1241 
1242   result.addAttribute(
1243       PrefetchOp::getIsDataCacheAttrName(),
1244       parser.getBuilder().getBoolAttr(cacheType.equals("data")));
1245 
1246   return success();
1247 }
1248 
1249 static LogicalResult verify(PrefetchOp op) {
1250   if (op.getNumOperands() != 1 + op.getMemRefType().getRank())
1251     return op.emitOpError("too few indices");
1252 
1253   return success();
1254 }
1255 
1256 LogicalResult PrefetchOp::fold(ArrayRef<Attribute> cstOperands,
1257                                SmallVectorImpl<OpFoldResult> &results) {
1258   // prefetch(memrefcast) -> prefetch
1259   return foldMemRefCast(*this);
1260 }
1261 
1262 //===----------------------------------------------------------------------===//
1263 // ReinterpretCastOp
1264 //===----------------------------------------------------------------------===//
1265 
1266 /// Build a ReinterpretCastOp with all dynamic entries: `staticOffsets`,
1267 /// `staticSizes` and `staticStrides` are automatically filled with
1268 /// source-memref-rank sentinel values that encode dynamic entries.
1269 void ReinterpretCastOp::build(OpBuilder &b, OperationState &result,
1270                               MemRefType resultType, Value source,
1271                               OpFoldResult offset, ArrayRef<OpFoldResult> sizes,
1272                               ArrayRef<OpFoldResult> strides,
1273                               ArrayRef<NamedAttribute> attrs) {
1274   SmallVector<int64_t> staticOffsets, staticSizes, staticStrides;
1275   SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides;
1276   dispatchIndexOpFoldResults(offset, dynamicOffsets, staticOffsets,
1277                              ShapedType::kDynamicStrideOrOffset);
1278   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
1279                              ShapedType::kDynamicSize);
1280   dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides,
1281                              ShapedType::kDynamicStrideOrOffset);
1282   build(b, result, resultType, source, dynamicOffsets, dynamicSizes,
1283         dynamicStrides, b.getI64ArrayAttr(staticOffsets),
1284         b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides));
1285   result.addAttributes(attrs);
1286 }
1287 
1288 void ReinterpretCastOp::build(OpBuilder &b, OperationState &result,
1289                               MemRefType resultType, Value source,
1290                               int64_t offset, ArrayRef<int64_t> sizes,
1291                               ArrayRef<int64_t> strides,
1292                               ArrayRef<NamedAttribute> attrs) {
1293   SmallVector<OpFoldResult> sizeValues =
1294       llvm::to_vector<4>(llvm::map_range(sizes, [&](int64_t v) -> OpFoldResult {
1295         return b.getI64IntegerAttr(v);
1296       }));
1297   SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>(
1298       llvm::map_range(strides, [&](int64_t v) -> OpFoldResult {
1299         return b.getI64IntegerAttr(v);
1300       }));
1301   build(b, result, resultType, source, b.getI64IntegerAttr(offset), sizeValues,
1302         strideValues, attrs);
1303 }
1304 
1305 void ReinterpretCastOp::build(OpBuilder &b, OperationState &result,
1306                               MemRefType resultType, Value source, Value offset,
1307                               ValueRange sizes, ValueRange strides,
1308                               ArrayRef<NamedAttribute> attrs) {
1309   SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>(
1310       llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; }));
1311   SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>(
1312       llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; }));
1313   build(b, result, resultType, source, offset, sizeValues, strideValues, attrs);
1314 }
1315 
1316 // TODO: ponder whether we want to allow missing trailing sizes/strides that are
1317 // completed automatically, like we have for subview and subtensor.
1318 static LogicalResult verify(ReinterpretCastOp op) {
1319   // The source and result memrefs should be in the same memory space.
1320   auto srcType = op.source().getType().cast<BaseMemRefType>();
1321   auto resultType = op.getType().cast<MemRefType>();
1322   if (srcType.getMemorySpace() != resultType.getMemorySpace())
1323     return op.emitError("different memory spaces specified for source type ")
1324            << srcType << " and result memref type " << resultType;
1325   if (srcType.getElementType() != resultType.getElementType())
1326     return op.emitError("different element types specified for source type ")
1327            << srcType << " and result memref type " << resultType;
1328 
1329   // Match sizes in result memref type and in static_sizes attribute.
1330   for (auto &en :
1331        llvm::enumerate(llvm::zip(resultType.getShape(),
1332                                  extractFromI64ArrayAttr(op.static_sizes())))) {
1333     int64_t resultSize = std::get<0>(en.value());
1334     int64_t expectedSize = std::get<1>(en.value());
1335     if (resultSize != expectedSize)
1336       return op.emitError("expected result type with size = ")
1337              << expectedSize << " instead of " << resultSize
1338              << " in dim = " << en.index();
1339   }
1340 
1341   // Match offset and strides in static_offset and static_strides attributes if
1342   // result memref type has an affine map specified.
1343   if (!resultType.getAffineMaps().empty()) {
1344     int64_t resultOffset;
1345     SmallVector<int64_t, 4> resultStrides;
1346     if (failed(getStridesAndOffset(resultType, resultStrides, resultOffset)))
1347       return failure();
1348 
1349     // Match offset in result memref type and in static_offsets attribute.
1350     int64_t expectedOffset =
1351         extractFromI64ArrayAttr(op.static_offsets()).front();
1352     if (resultOffset != expectedOffset)
1353       return op.emitError("expected result type with offset = ")
1354              << resultOffset << " instead of " << expectedOffset;
1355 
1356     // Match strides in result memref type and in static_strides attribute.
1357     for (auto &en : llvm::enumerate(llvm::zip(
1358              resultStrides, extractFromI64ArrayAttr(op.static_strides())))) {
1359       int64_t resultStride = std::get<0>(en.value());
1360       int64_t expectedStride = std::get<1>(en.value());
1361       if (resultStride != expectedStride)
1362         return op.emitError("expected result type with stride = ")
1363                << expectedStride << " instead of " << resultStride
1364                << " in dim = " << en.index();
1365     }
1366   }
1367   return success();
1368 }
1369 
1370 //===----------------------------------------------------------------------===//
1371 // ReshapeOp
1372 //===----------------------------------------------------------------------===//
1373 
1374 static LogicalResult verify(ReshapeOp op) {
1375   Type operandType = op.source().getType();
1376   Type resultType = op.result().getType();
1377 
1378   Type operandElementType = operandType.cast<ShapedType>().getElementType();
1379   Type resultElementType = resultType.cast<ShapedType>().getElementType();
1380   if (operandElementType != resultElementType)
1381     return op.emitOpError("element types of source and destination memref "
1382                           "types should be the same");
1383 
1384   if (auto operandMemRefType = operandType.dyn_cast<MemRefType>())
1385     if (!operandMemRefType.getAffineMaps().empty())
1386       return op.emitOpError(
1387           "source memref type should have identity affine map");
1388 
1389   int64_t shapeSize = op.shape().getType().cast<MemRefType>().getDimSize(0);
1390   auto resultMemRefType = resultType.dyn_cast<MemRefType>();
1391   if (resultMemRefType) {
1392     if (!resultMemRefType.getAffineMaps().empty())
1393       return op.emitOpError(
1394           "result memref type should have identity affine map");
1395     if (shapeSize == ShapedType::kDynamicSize)
1396       return op.emitOpError("cannot use shape operand with dynamic length to "
1397                             "reshape to statically-ranked memref type");
1398     if (shapeSize != resultMemRefType.getRank())
1399       return op.emitOpError(
1400           "length of shape operand differs from the result's memref rank");
1401   }
1402   return success();
1403 }
1404 
1405 //===----------------------------------------------------------------------===//
1406 // StoreOp
1407 //===----------------------------------------------------------------------===//
1408 
1409 static LogicalResult verify(StoreOp op) {
1410   if (op.getNumOperands() != 2 + op.getMemRefType().getRank())
1411     return op.emitOpError("store index operand count not equal to memref rank");
1412 
1413   return success();
1414 }
1415 
1416 LogicalResult StoreOp::fold(ArrayRef<Attribute> cstOperands,
1417                             SmallVectorImpl<OpFoldResult> &results) {
1418   /// store(memrefcast) -> store
1419   return foldMemRefCast(*this, getValueToStore());
1420 }
1421 
1422 //===----------------------------------------------------------------------===//
1423 // SubViewOp
1424 //===----------------------------------------------------------------------===//
1425 
1426 namespace {
1427 /// Helpers to write more idiomatic operations.
1428 namespace saturated_arith {
1429 struct Wrapper {
1430   explicit Wrapper(int64_t v) : v(v) {}
1431   operator int64_t() { return v; }
1432   int64_t v;
1433 };
1434 Wrapper operator+(Wrapper a, int64_t b) {
1435   if (ShapedType::isDynamicStrideOrOffset(a) ||
1436       ShapedType::isDynamicStrideOrOffset(b))
1437     return Wrapper(ShapedType::kDynamicStrideOrOffset);
1438   return Wrapper(a.v + b);
1439 }
1440 Wrapper operator*(Wrapper a, int64_t b) {
1441   if (ShapedType::isDynamicStrideOrOffset(a) ||
1442       ShapedType::isDynamicStrideOrOffset(b))
1443     return Wrapper(ShapedType::kDynamicStrideOrOffset);
1444   return Wrapper(a.v * b);
1445 }
1446 } // end namespace saturated_arith
1447 } // end namespace
1448 
1449 /// A subview result type can be fully inferred from the source type and the
1450 /// static representation of offsets, sizes and strides. Special sentinels
1451 /// encode the dynamic case.
1452 Type SubViewOp::inferResultType(MemRefType sourceMemRefType,
1453                                 ArrayRef<int64_t> leadingStaticOffsets,
1454                                 ArrayRef<int64_t> leadingStaticSizes,
1455                                 ArrayRef<int64_t> leadingStaticStrides) {
1456   // A subview may specify only a leading subset of offset/sizes/strides in
1457   // which case we complete with offset=0, sizes from memref type and strides=1.
1458   unsigned rank = sourceMemRefType.getRank();
1459   assert(leadingStaticOffsets.size() <= rank &&
1460          "unexpected leadingStaticOffsets overflow");
1461   assert(leadingStaticSizes.size() <= rank &&
1462          "unexpected leadingStaticSizes overflow");
1463   assert(leadingStaticStrides.size() <= rank &&
1464          "unexpected leadingStaticStrides overflow");
1465   auto staticOffsets = llvm::to_vector<4>(leadingStaticOffsets);
1466   auto staticSizes = llvm::to_vector<4>(leadingStaticSizes);
1467   auto staticStrides = llvm::to_vector<4>(leadingStaticStrides);
1468   unsigned numTrailingOffsets = rank - staticOffsets.size();
1469   unsigned numTrailingSizes = rank - staticSizes.size();
1470   unsigned numTrailingStrides = rank - staticStrides.size();
1471   staticOffsets.append(numTrailingOffsets, 0);
1472   llvm::append_range(staticSizes,
1473                      sourceMemRefType.getShape().take_back(numTrailingSizes));
1474   staticStrides.append(numTrailingStrides, 1);
1475 
1476   // Extract source offset and strides.
1477   int64_t sourceOffset;
1478   SmallVector<int64_t, 4> sourceStrides;
1479   auto res = getStridesAndOffset(sourceMemRefType, sourceStrides, sourceOffset);
1480   assert(succeeded(res) && "SubViewOp expected strided memref type");
1481   (void)res;
1482 
1483   // Compute target offset whose value is:
1484   //   `sourceOffset + sum_i(staticOffset_i * sourceStrides_i)`.
1485   int64_t targetOffset = sourceOffset;
1486   for (auto it : llvm::zip(staticOffsets, sourceStrides)) {
1487     auto staticOffset = std::get<0>(it), targetStride = std::get<1>(it);
1488     using namespace saturated_arith;
1489     targetOffset = Wrapper(targetOffset) + Wrapper(staticOffset) * targetStride;
1490   }
1491 
1492   // Compute target stride whose value is:
1493   //   `sourceStrides_i * staticStrides_i`.
1494   SmallVector<int64_t, 4> targetStrides;
1495   targetStrides.reserve(staticOffsets.size());
1496   for (auto it : llvm::zip(sourceStrides, staticStrides)) {
1497     auto sourceStride = std::get<0>(it), staticStride = std::get<1>(it);
1498     using namespace saturated_arith;
1499     targetStrides.push_back(Wrapper(sourceStride) * staticStride);
1500   }
1501 
1502   // The type is now known.
1503   return MemRefType::get(
1504       staticSizes, sourceMemRefType.getElementType(),
1505       makeStridedLinearLayoutMap(targetStrides, targetOffset,
1506                                  sourceMemRefType.getContext()),
1507       sourceMemRefType.getMemorySpace());
1508 }
1509 
1510 Type SubViewOp::inferResultType(MemRefType sourceMemRefType,
1511                                 ArrayRef<OpFoldResult> leadingStaticOffsets,
1512                                 ArrayRef<OpFoldResult> leadingStaticSizes,
1513                                 ArrayRef<OpFoldResult> leadingStaticStrides) {
1514   SmallVector<int64_t> staticOffsets, staticSizes, staticStrides;
1515   SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides;
1516   dispatchIndexOpFoldResults(leadingStaticOffsets, dynamicOffsets,
1517                              staticOffsets, ShapedType::kDynamicStrideOrOffset);
1518   dispatchIndexOpFoldResults(leadingStaticSizes, dynamicSizes, staticSizes,
1519                              ShapedType::kDynamicSize);
1520   dispatchIndexOpFoldResults(leadingStaticStrides, dynamicStrides,
1521                              staticStrides, ShapedType::kDynamicStrideOrOffset);
1522   return SubViewOp::inferResultType(sourceMemRefType, staticOffsets,
1523                                     staticSizes, staticStrides)
1524       .cast<MemRefType>();
1525 }
1526 
1527 Type SubViewOp::inferRankReducedResultType(
1528     unsigned resultRank, MemRefType sourceRankedTensorType,
1529     ArrayRef<int64_t> leadingStaticOffsets,
1530     ArrayRef<int64_t> leadingStaticSizes,
1531     ArrayRef<int64_t> leadingStaticStrides) {
1532   auto inferredType =
1533       inferResultType(sourceRankedTensorType, leadingStaticOffsets,
1534                       leadingStaticSizes, leadingStaticStrides)
1535           .cast<MemRefType>();
1536   assert(inferredType.getRank() >= resultRank && "expected ");
1537   int rankDiff = inferredType.getRank() - resultRank;
1538   if (rankDiff > 0) {
1539     auto shape = inferredType.getShape();
1540     llvm::SmallDenseSet<unsigned> dimsToProject;
1541     mlir::getPositionsOfShapeOne(rankDiff, shape, dimsToProject);
1542     SmallVector<int64_t> projectedShape;
1543     for (unsigned pos = 0, e = shape.size(); pos < e; ++pos)
1544       if (!dimsToProject.contains(pos))
1545         projectedShape.push_back(shape[pos]);
1546 
1547     AffineMap map;
1548     auto maps = inferredType.getAffineMaps();
1549     if (!maps.empty() && maps.front())
1550       map = getProjectedMap(maps.front(), dimsToProject);
1551     inferredType =
1552         MemRefType::get(projectedShape, inferredType.getElementType(), map,
1553                         inferredType.getMemorySpace());
1554   }
1555   return inferredType;
1556 }
1557 
1558 Type SubViewOp::inferRankReducedResultType(
1559     unsigned resultRank, MemRefType sourceRankedTensorType,
1560     ArrayRef<OpFoldResult> leadingStaticOffsets,
1561     ArrayRef<OpFoldResult> leadingStaticSizes,
1562     ArrayRef<OpFoldResult> leadingStaticStrides) {
1563   SmallVector<int64_t> staticOffsets, staticSizes, staticStrides;
1564   SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides;
1565   dispatchIndexOpFoldResults(leadingStaticOffsets, dynamicOffsets,
1566                              staticOffsets, ShapedType::kDynamicStrideOrOffset);
1567   dispatchIndexOpFoldResults(leadingStaticSizes, dynamicSizes, staticSizes,
1568                              ShapedType::kDynamicSize);
1569   dispatchIndexOpFoldResults(leadingStaticStrides, dynamicStrides,
1570                              staticStrides, ShapedType::kDynamicStrideOrOffset);
1571   return SubViewOp::inferRankReducedResultType(
1572       resultRank, sourceRankedTensorType, staticOffsets, staticSizes,
1573       staticStrides);
1574 }
1575 // Build a SubViewOp with mixed static and dynamic entries and custom result
1576 // type. If the type passed is nullptr, it is inferred.
1577 void SubViewOp::build(OpBuilder &b, OperationState &result,
1578                       MemRefType resultType, Value source,
1579                       ArrayRef<OpFoldResult> offsets,
1580                       ArrayRef<OpFoldResult> sizes,
1581                       ArrayRef<OpFoldResult> strides,
1582                       ArrayRef<NamedAttribute> attrs) {
1583   SmallVector<int64_t> staticOffsets, staticSizes, staticStrides;
1584   SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides;
1585   dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets,
1586                              ShapedType::kDynamicStrideOrOffset);
1587   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
1588                              ShapedType::kDynamicSize);
1589   dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides,
1590                              ShapedType::kDynamicStrideOrOffset);
1591   auto sourceMemRefType = source.getType().cast<MemRefType>();
1592   // Structuring implementation this way avoids duplication between builders.
1593   if (!resultType) {
1594     resultType = SubViewOp::inferResultType(sourceMemRefType, staticOffsets,
1595                                             staticSizes, staticStrides)
1596                      .cast<MemRefType>();
1597   }
1598   build(b, result, resultType, source, dynamicOffsets, dynamicSizes,
1599         dynamicStrides, b.getI64ArrayAttr(staticOffsets),
1600         b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides));
1601   result.addAttributes(attrs);
1602 }
1603 
1604 // Build a SubViewOp with mixed static and dynamic entries and inferred result
1605 // type.
1606 void SubViewOp::build(OpBuilder &b, OperationState &result, Value source,
1607                       ArrayRef<OpFoldResult> offsets,
1608                       ArrayRef<OpFoldResult> sizes,
1609                       ArrayRef<OpFoldResult> strides,
1610                       ArrayRef<NamedAttribute> attrs) {
1611   build(b, result, MemRefType(), source, offsets, sizes, strides, attrs);
1612 }
1613 
1614 // Build a SubViewOp with static entries and inferred result type.
1615 void SubViewOp::build(OpBuilder &b, OperationState &result, Value source,
1616                       ArrayRef<int64_t> offsets, ArrayRef<int64_t> sizes,
1617                       ArrayRef<int64_t> strides,
1618                       ArrayRef<NamedAttribute> attrs) {
1619   SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>(
1620       llvm::map_range(offsets, [&](int64_t v) -> OpFoldResult {
1621         return b.getI64IntegerAttr(v);
1622       }));
1623   SmallVector<OpFoldResult> sizeValues =
1624       llvm::to_vector<4>(llvm::map_range(sizes, [&](int64_t v) -> OpFoldResult {
1625         return b.getI64IntegerAttr(v);
1626       }));
1627   SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>(
1628       llvm::map_range(strides, [&](int64_t v) -> OpFoldResult {
1629         return b.getI64IntegerAttr(v);
1630       }));
1631   build(b, result, source, offsetValues, sizeValues, strideValues, attrs);
1632 }
1633 
1634 // Build a SubViewOp with dynamic entries and custom result type. If the
1635 // type passed is nullptr, it is inferred.
1636 void SubViewOp::build(OpBuilder &b, OperationState &result,
1637                       MemRefType resultType, Value source,
1638                       ArrayRef<int64_t> offsets, ArrayRef<int64_t> sizes,
1639                       ArrayRef<int64_t> strides,
1640                       ArrayRef<NamedAttribute> attrs) {
1641   SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>(
1642       llvm::map_range(offsets, [&](int64_t v) -> OpFoldResult {
1643         return b.getI64IntegerAttr(v);
1644       }));
1645   SmallVector<OpFoldResult> sizeValues =
1646       llvm::to_vector<4>(llvm::map_range(sizes, [&](int64_t v) -> OpFoldResult {
1647         return b.getI64IntegerAttr(v);
1648       }));
1649   SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>(
1650       llvm::map_range(strides, [&](int64_t v) -> OpFoldResult {
1651         return b.getI64IntegerAttr(v);
1652       }));
1653   build(b, result, resultType, source, offsetValues, sizeValues, strideValues,
1654         attrs);
1655 }
1656 
1657 // Build a SubViewOp with dynamic entries and custom result type. If the type
1658 // passed is nullptr, it is inferred.
1659 void SubViewOp::build(OpBuilder &b, OperationState &result,
1660                       MemRefType resultType, Value source, ValueRange offsets,
1661                       ValueRange sizes, ValueRange strides,
1662                       ArrayRef<NamedAttribute> attrs) {
1663   SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>(
1664       llvm::map_range(offsets, [](Value v) -> OpFoldResult { return v; }));
1665   SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>(
1666       llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; }));
1667   SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>(
1668       llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; }));
1669   build(b, result, resultType, source, offsetValues, sizeValues, strideValues);
1670 }
1671 
1672 // Build a SubViewOp with dynamic entries and inferred result type.
1673 void SubViewOp::build(OpBuilder &b, OperationState &result, Value source,
1674                       ValueRange offsets, ValueRange sizes, ValueRange strides,
1675                       ArrayRef<NamedAttribute> attrs) {
1676   build(b, result, MemRefType(), source, offsets, sizes, strides, attrs);
1677 }
1678 
1679 /// For ViewLikeOpInterface.
1680 Value SubViewOp::getViewSource() { return source(); }
1681 
1682 enum SubViewVerificationResult {
1683   Success,
1684   RankTooLarge,
1685   SizeMismatch,
1686   ElemTypeMismatch,
1687   MemSpaceMismatch,
1688   AffineMapMismatch
1689 };
1690 
1691 /// Checks if `original` Type type can be rank reduced to `reduced` type.
1692 /// This function is slight variant of `is subsequence` algorithm where
1693 /// not matching dimension must be 1.
1694 static SubViewVerificationResult
1695 isRankReducedType(Type originalType, Type candidateReducedType,
1696                   std::string *errMsg = nullptr) {
1697   if (originalType == candidateReducedType)
1698     return SubViewVerificationResult::Success;
1699   if (!originalType.isa<MemRefType>())
1700     return SubViewVerificationResult::Success;
1701   if (originalType.isa<MemRefType>() && !candidateReducedType.isa<MemRefType>())
1702     return SubViewVerificationResult::Success;
1703 
1704   ShapedType originalShapedType = originalType.cast<ShapedType>();
1705   ShapedType candidateReducedShapedType =
1706       candidateReducedType.cast<ShapedType>();
1707 
1708   // Rank and size logic is valid for all ShapedTypes.
1709   ArrayRef<int64_t> originalShape = originalShapedType.getShape();
1710   ArrayRef<int64_t> candidateReducedShape =
1711       candidateReducedShapedType.getShape();
1712   unsigned originalRank = originalShape.size(),
1713            candidateReducedRank = candidateReducedShape.size();
1714   if (candidateReducedRank > originalRank)
1715     return SubViewVerificationResult::RankTooLarge;
1716 
1717   auto optionalUnusedDimsMask =
1718       computeRankReductionMask(originalShape, candidateReducedShape);
1719 
1720   // Sizes cannot be matched in case empty vector is returned.
1721   if (!optionalUnusedDimsMask.hasValue())
1722     return SubViewVerificationResult::SizeMismatch;
1723 
1724   if (originalShapedType.getElementType() !=
1725       candidateReducedShapedType.getElementType())
1726     return SubViewVerificationResult::ElemTypeMismatch;
1727 
1728   // Strided layout logic is relevant for MemRefType only.
1729   MemRefType original = originalType.cast<MemRefType>();
1730   MemRefType candidateReduced = candidateReducedType.cast<MemRefType>();
1731   if (original.getMemorySpace() != candidateReduced.getMemorySpace())
1732     return SubViewVerificationResult::MemSpaceMismatch;
1733 
1734   llvm::SmallDenseSet<unsigned> unusedDims = optionalUnusedDimsMask.getValue();
1735   auto inferredType =
1736       getProjectedMap(getStridedLinearLayoutMap(original), unusedDims);
1737   AffineMap candidateLayout;
1738   if (candidateReduced.getAffineMaps().empty())
1739     candidateLayout = getStridedLinearLayoutMap(candidateReduced);
1740   else
1741     candidateLayout = candidateReduced.getAffineMaps().front();
1742   assert(inferredType.getNumResults() == 1 &&
1743          candidateLayout.getNumResults() == 1);
1744   if (inferredType.getNumSymbols() != candidateLayout.getNumSymbols() ||
1745       inferredType.getNumDims() != candidateLayout.getNumDims()) {
1746     if (errMsg) {
1747       llvm::raw_string_ostream os(*errMsg);
1748       os << "inferred type: " << inferredType;
1749     }
1750     return SubViewVerificationResult::AffineMapMismatch;
1751   }
1752   // Check that the difference of the affine maps simplifies to 0.
1753   AffineExpr diffExpr =
1754       inferredType.getResult(0) - candidateLayout.getResult(0);
1755   diffExpr = simplifyAffineExpr(diffExpr, inferredType.getNumDims(),
1756                                 inferredType.getNumSymbols());
1757   auto cst = diffExpr.dyn_cast<AffineConstantExpr>();
1758   if (!(cst && cst.getValue() == 0)) {
1759     if (errMsg) {
1760       llvm::raw_string_ostream os(*errMsg);
1761       os << "inferred type: " << inferredType;
1762     }
1763     return SubViewVerificationResult::AffineMapMismatch;
1764   }
1765   return SubViewVerificationResult::Success;
1766 }
1767 
1768 template <typename OpTy>
1769 static LogicalResult produceSubViewErrorMsg(SubViewVerificationResult result,
1770                                             OpTy op, Type expectedType,
1771                                             StringRef errMsg = "") {
1772   auto memrefType = expectedType.cast<ShapedType>();
1773   switch (result) {
1774   case SubViewVerificationResult::Success:
1775     return success();
1776   case SubViewVerificationResult::RankTooLarge:
1777     return op.emitError("expected result rank to be smaller or equal to ")
1778            << "the source rank. " << errMsg;
1779   case SubViewVerificationResult::SizeMismatch:
1780     return op.emitError("expected result type to be ")
1781            << expectedType
1782            << " or a rank-reduced version. (mismatch of result sizes) "
1783            << errMsg;
1784   case SubViewVerificationResult::ElemTypeMismatch:
1785     return op.emitError("expected result element type to be ")
1786            << memrefType.getElementType() << errMsg;
1787   case SubViewVerificationResult::MemSpaceMismatch:
1788     return op.emitError("expected result and source memory spaces to match.")
1789            << errMsg;
1790   case SubViewVerificationResult::AffineMapMismatch:
1791     return op.emitError("expected result type to be ")
1792            << expectedType
1793            << " or a rank-reduced version. (mismatch of result affine map) "
1794            << errMsg;
1795   }
1796   llvm_unreachable("unexpected subview verification result");
1797 }
1798 
1799 /// Verifier for SubViewOp.
1800 static LogicalResult verify(SubViewOp op) {
1801   MemRefType baseType = op.getSourceType();
1802   MemRefType subViewType = op.getType();
1803 
1804   // The base memref and the view memref should be in the same memory space.
1805   if (baseType.getMemorySpace() != subViewType.getMemorySpace())
1806     return op.emitError("different memory spaces specified for base memref "
1807                         "type ")
1808            << baseType << " and subview memref type " << subViewType;
1809 
1810   // Verify that the base memref type has a strided layout map.
1811   if (!isStrided(baseType))
1812     return op.emitError("base type ") << baseType << " is not strided";
1813 
1814   // Verify result type against inferred type.
1815   auto expectedType = SubViewOp::inferResultType(
1816       baseType, extractFromI64ArrayAttr(op.static_offsets()),
1817       extractFromI64ArrayAttr(op.static_sizes()),
1818       extractFromI64ArrayAttr(op.static_strides()));
1819 
1820   std::string errMsg;
1821   auto result = isRankReducedType(expectedType, subViewType, &errMsg);
1822   return produceSubViewErrorMsg(result, op, expectedType, errMsg);
1823 }
1824 
1825 raw_ostream &mlir::operator<<(raw_ostream &os, Range &range) {
1826   return os << "range " << range.offset << ":" << range.size << ":"
1827             << range.stride;
1828 }
1829 
1830 /// Return the list of Range (i.e. offset, size, stride). Each Range
1831 /// entry contains either the dynamic value or a ConstantIndexOp constructed
1832 /// with `b` at location `loc`.
1833 SmallVector<Range, 8> mlir::getOrCreateRanges(OffsetSizeAndStrideOpInterface op,
1834                                               OpBuilder &b, Location loc) {
1835   std::array<unsigned, 3> ranks = op.getArrayAttrMaxRanks();
1836   assert(ranks[0] == ranks[1] && "expected offset and sizes of equal ranks");
1837   assert(ranks[1] == ranks[2] && "expected sizes and strides of equal ranks");
1838   SmallVector<Range, 8> res;
1839   unsigned rank = ranks[0];
1840   res.reserve(rank);
1841   for (unsigned idx = 0; idx < rank; ++idx) {
1842     Value offset =
1843         op.isDynamicOffset(idx)
1844             ? op.getDynamicOffset(idx)
1845             : b.create<ConstantIndexOp>(loc, op.getStaticOffset(idx));
1846     Value size = op.isDynamicSize(idx)
1847                      ? op.getDynamicSize(idx)
1848                      : b.create<ConstantIndexOp>(loc, op.getStaticSize(idx));
1849     Value stride =
1850         op.isDynamicStride(idx)
1851             ? op.getDynamicStride(idx)
1852             : b.create<ConstantIndexOp>(loc, op.getStaticStride(idx));
1853     res.emplace_back(Range{offset, size, stride});
1854   }
1855   return res;
1856 }
1857 
1858 /// Infer the canonical type of the result of a subview operation. Returns a
1859 /// type with rank `resultRank` that is either the rank of the rank-reduced
1860 /// type, or the non-rank-reduced type.
1861 static MemRefType
1862 getCanonicalSubViewResultType(unsigned resultRank, MemRefType sourceType,
1863                               ArrayRef<OpFoldResult> mixedOffsets,
1864                               ArrayRef<OpFoldResult> mixedSizes,
1865                               ArrayRef<OpFoldResult> mixedStrides) {
1866   auto resultType =
1867       SubViewOp::inferRankReducedResultType(
1868           resultRank, sourceType, mixedOffsets, mixedSizes, mixedStrides)
1869           .cast<MemRefType>();
1870   if (resultType.getRank() != resultRank) {
1871     resultType = SubViewOp::inferResultType(sourceType, mixedOffsets,
1872                                             mixedSizes, mixedStrides)
1873                      .cast<MemRefType>();
1874   }
1875   return resultType;
1876 }
1877 
1878 namespace {
1879 /// Pattern to rewrite a subview op with MemRefCast arguments.
1880 /// This essentially pushes memref.cast past its consuming subview when
1881 /// `canFoldIntoConsumerOp` is true.
1882 ///
1883 /// Example:
1884 /// ```
1885 ///   %0 = memref.cast %V : memref<16x16xf32> to memref<?x?xf32>
1886 ///   %1 = memref.subview %0[0, 0][3, 4][1, 1] :
1887 ///     memref<?x?xf32> to memref<3x4xf32, offset:?, strides:[?, 1]>
1888 /// ```
1889 /// is rewritten into:
1890 /// ```
1891 ///   %0 = memref.subview %V: memref<16x16xf32> to memref<3x4xf32, #[[map0]]>
1892 ///   %1 = memref.cast %0: memref<3x4xf32, offset:0, strides:[16, 1]> to
1893 ///     memref<3x4xf32, offset:?, strides:[?, 1]>
1894 /// ```
1895 class SubViewOpMemRefCastFolder final : public OpRewritePattern<SubViewOp> {
1896 public:
1897   using OpRewritePattern<SubViewOp>::OpRewritePattern;
1898 
1899   LogicalResult matchAndRewrite(SubViewOp subViewOp,
1900                                 PatternRewriter &rewriter) const override {
1901     // Any constant operand, just return to let SubViewOpConstantFolder kick in.
1902     if (llvm::any_of(subViewOp.getOperands(), [](Value operand) {
1903           return matchPattern(operand, matchConstantIndex());
1904         }))
1905       return failure();
1906 
1907     auto castOp = subViewOp.source().getDefiningOp<CastOp>();
1908     if (!castOp)
1909       return failure();
1910 
1911     if (!CastOp::canFoldIntoConsumerOp(castOp))
1912       return failure();
1913 
1914     /// Deduce the resultType of the SubViewOp using `inferSubViewResultType` on
1915     /// the cast source operand type and the SubViewOp static information. This
1916     /// is the resulting type if the MemRefCastOp were folded.
1917     auto resultType = getCanonicalSubViewResultType(
1918         subViewOp.getType().getRank(),
1919         castOp.source().getType().cast<MemRefType>(),
1920         subViewOp.getMixedOffsets(), subViewOp.getMixedSizes(),
1921         subViewOp.getMixedStrides());
1922     Value newSubView = rewriter.create<SubViewOp>(
1923         subViewOp.getLoc(), resultType, castOp.source(), subViewOp.offsets(),
1924         subViewOp.sizes(), subViewOp.strides(), subViewOp.static_offsets(),
1925         subViewOp.static_sizes(), subViewOp.static_strides());
1926     rewriter.replaceOpWithNewOp<CastOp>(subViewOp, subViewOp.getType(),
1927                                         newSubView);
1928     return success();
1929   }
1930 };
1931 } // namespace
1932 
1933 /// Return the canonical type of the result of a subview.
1934 struct SubViewReturnTypeCanonicalizer {
1935   MemRefType operator()(SubViewOp op, ArrayRef<OpFoldResult> mixedOffsets,
1936                         ArrayRef<OpFoldResult> mixedSizes,
1937                         ArrayRef<OpFoldResult> mixedStrides) {
1938     return getCanonicalSubViewResultType(op.getType().getRank(),
1939                                          op.getSourceType(), mixedOffsets,
1940                                          mixedSizes, mixedStrides);
1941   }
1942 };
1943 
1944 /// A canonicalizer wrapper to replace SubViewOps.
1945 struct SubViewCanonicalizer {
1946   void operator()(PatternRewriter &rewriter, SubViewOp op, SubViewOp newOp) {
1947     rewriter.replaceOpWithNewOp<CastOp>(op, newOp, op.getType());
1948   }
1949 };
1950 
1951 void SubViewOp::getCanonicalizationPatterns(RewritePatternSet &results,
1952                                             MLIRContext *context) {
1953   results
1954       .add<OpWithOffsetSizesAndStridesConstantArgumentFolder<
1955                SubViewOp, SubViewReturnTypeCanonicalizer, SubViewCanonicalizer>,
1956            SubViewOpMemRefCastFolder>(context);
1957 }
1958 
1959 OpFoldResult SubViewOp::fold(ArrayRef<Attribute> operands) {
1960   auto resultShapedType = getResult().getType().cast<ShapedType>();
1961   auto sourceShapedType = source().getType().cast<ShapedType>();
1962 
1963   if (resultShapedType.hasStaticShape() &&
1964       resultShapedType == sourceShapedType) {
1965     return getViewSource();
1966   }
1967 
1968   return {};
1969 }
1970 
1971 //===----------------------------------------------------------------------===//
1972 // TensorLoadOp
1973 //===----------------------------------------------------------------------===//
1974 
1975 OpFoldResult TensorLoadOp::fold(ArrayRef<Attribute>) {
1976   if (auto bufferCast = memref().getDefiningOp<BufferCastOp>())
1977     // Approximate alias analysis by conservatively folding only when no there
1978     // is no interleaved operation.
1979     if (bufferCast->getBlock() == this->getOperation()->getBlock() &&
1980         bufferCast->getNextNode() == this->getOperation())
1981       return bufferCast.tensor();
1982   return {};
1983 }
1984 
1985 //===----------------------------------------------------------------------===//
1986 // TransposeOp
1987 //===----------------------------------------------------------------------===//
1988 
1989 /// Build a strided memref type by applying `permutationMap` tp `memRefType`.
1990 static MemRefType inferTransposeResultType(MemRefType memRefType,
1991                                            AffineMap permutationMap) {
1992   auto rank = memRefType.getRank();
1993   auto originalSizes = memRefType.getShape();
1994   // Compute permuted sizes.
1995   SmallVector<int64_t, 4> sizes(rank, 0);
1996   for (auto en : llvm::enumerate(permutationMap.getResults()))
1997     sizes[en.index()] =
1998         originalSizes[en.value().cast<AffineDimExpr>().getPosition()];
1999 
2000   // Compute permuted strides.
2001   int64_t offset;
2002   SmallVector<int64_t, 4> strides;
2003   auto res = getStridesAndOffset(memRefType, strides, offset);
2004   assert(succeeded(res) && strides.size() == static_cast<unsigned>(rank));
2005   (void)res;
2006   auto map =
2007       makeStridedLinearLayoutMap(strides, offset, memRefType.getContext());
2008   map = permutationMap ? map.compose(permutationMap) : map;
2009   return MemRefType::Builder(memRefType).setShape(sizes).setAffineMaps(map);
2010 }
2011 
2012 void TransposeOp::build(OpBuilder &b, OperationState &result, Value in,
2013                         AffineMapAttr permutation,
2014                         ArrayRef<NamedAttribute> attrs) {
2015   auto permutationMap = permutation.getValue();
2016   assert(permutationMap);
2017 
2018   auto memRefType = in.getType().cast<MemRefType>();
2019   // Compute result type.
2020   MemRefType resultType = inferTransposeResultType(memRefType, permutationMap);
2021 
2022   build(b, result, resultType, in, attrs);
2023   result.addAttribute(TransposeOp::getPermutationAttrName(), permutation);
2024 }
2025 
2026 // transpose $in $permutation attr-dict : type($in) `to` type(results)
2027 static void print(OpAsmPrinter &p, TransposeOp op) {
2028   p << "memref.transpose " << op.in() << " " << op.permutation();
2029   p.printOptionalAttrDict(op->getAttrs(),
2030                           {TransposeOp::getPermutationAttrName()});
2031   p << " : " << op.in().getType() << " to " << op.getType();
2032 }
2033 
2034 static ParseResult parseTransposeOp(OpAsmParser &parser,
2035                                     OperationState &result) {
2036   OpAsmParser::OperandType in;
2037   AffineMap permutation;
2038   MemRefType srcType, dstType;
2039   if (parser.parseOperand(in) || parser.parseAffineMap(permutation) ||
2040       parser.parseOptionalAttrDict(result.attributes) ||
2041       parser.parseColonType(srcType) ||
2042       parser.resolveOperand(in, srcType, result.operands) ||
2043       parser.parseKeywordType("to", dstType) ||
2044       parser.addTypeToList(dstType, result.types))
2045     return failure();
2046 
2047   result.addAttribute(TransposeOp::getPermutationAttrName(),
2048                       AffineMapAttr::get(permutation));
2049   return success();
2050 }
2051 
2052 static LogicalResult verify(TransposeOp op) {
2053   if (!op.permutation().isPermutation())
2054     return op.emitOpError("expected a permutation map");
2055   if (op.permutation().getNumDims() != op.getShapedType().getRank())
2056     return op.emitOpError(
2057         "expected a permutation map of same rank as the input");
2058 
2059   auto srcType = op.in().getType().cast<MemRefType>();
2060   auto dstType = op.getType().cast<MemRefType>();
2061   auto transposedType = inferTransposeResultType(srcType, op.permutation());
2062   if (dstType != transposedType)
2063     return op.emitOpError("output type ")
2064            << dstType << " does not match transposed input type " << srcType
2065            << ", " << transposedType;
2066   return success();
2067 }
2068 
2069 OpFoldResult TransposeOp::fold(ArrayRef<Attribute>) {
2070   if (succeeded(foldMemRefCast(*this)))
2071     return getResult();
2072   return {};
2073 }
2074 
2075 //===----------------------------------------------------------------------===//
2076 // ViewOp
2077 //===----------------------------------------------------------------------===//
2078 
2079 static ParseResult parseViewOp(OpAsmParser &parser, OperationState &result) {
2080   OpAsmParser::OperandType srcInfo;
2081   SmallVector<OpAsmParser::OperandType, 1> offsetInfo;
2082   SmallVector<OpAsmParser::OperandType, 4> sizesInfo;
2083   auto indexType = parser.getBuilder().getIndexType();
2084   Type srcType, dstType;
2085   llvm::SMLoc offsetLoc;
2086   if (parser.parseOperand(srcInfo) || parser.getCurrentLocation(&offsetLoc) ||
2087       parser.parseOperandList(offsetInfo, OpAsmParser::Delimiter::Square))
2088     return failure();
2089 
2090   if (offsetInfo.size() != 1)
2091     return parser.emitError(offsetLoc) << "expects 1 offset operand";
2092 
2093   return failure(
2094       parser.parseOperandList(sizesInfo, OpAsmParser::Delimiter::Square) ||
2095       parser.parseOptionalAttrDict(result.attributes) ||
2096       parser.parseColonType(srcType) ||
2097       parser.resolveOperand(srcInfo, srcType, result.operands) ||
2098       parser.resolveOperands(offsetInfo, indexType, result.operands) ||
2099       parser.resolveOperands(sizesInfo, indexType, result.operands) ||
2100       parser.parseKeywordType("to", dstType) ||
2101       parser.addTypeToList(dstType, result.types));
2102 }
2103 
2104 static void print(OpAsmPrinter &p, ViewOp op) {
2105   p << op.getOperationName() << ' ' << op.getOperand(0) << '[';
2106   p.printOperand(op.byte_shift());
2107   p << "][" << op.sizes() << ']';
2108   p.printOptionalAttrDict(op->getAttrs());
2109   p << " : " << op.getOperand(0).getType() << " to " << op.getType();
2110 }
2111 
2112 static LogicalResult verify(ViewOp op) {
2113   auto baseType = op.getOperand(0).getType().cast<MemRefType>();
2114   auto viewType = op.getType();
2115 
2116   // The base memref should have identity layout map (or none).
2117   if (baseType.getAffineMaps().size() > 1 ||
2118       (baseType.getAffineMaps().size() == 1 &&
2119        !baseType.getAffineMaps()[0].isIdentity()))
2120     return op.emitError("unsupported map for base memref type ") << baseType;
2121 
2122   // The result memref should have identity layout map (or none).
2123   if (viewType.getAffineMaps().size() > 1 ||
2124       (viewType.getAffineMaps().size() == 1 &&
2125        !viewType.getAffineMaps()[0].isIdentity()))
2126     return op.emitError("unsupported map for result memref type ") << viewType;
2127 
2128   // The base memref and the view memref should be in the same memory space.
2129   if (baseType.getMemorySpace() != viewType.getMemorySpace())
2130     return op.emitError("different memory spaces specified for base memref "
2131                         "type ")
2132            << baseType << " and view memref type " << viewType;
2133 
2134   // Verify that we have the correct number of sizes for the result type.
2135   unsigned numDynamicDims = viewType.getNumDynamicDims();
2136   if (op.sizes().size() != numDynamicDims)
2137     return op.emitError("incorrect number of size operands for type ")
2138            << viewType;
2139 
2140   return success();
2141 }
2142 
2143 Value ViewOp::getViewSource() { return source(); }
2144 
2145 namespace {
2146 
2147 struct ViewOpShapeFolder : public OpRewritePattern<ViewOp> {
2148   using OpRewritePattern<ViewOp>::OpRewritePattern;
2149 
2150   LogicalResult matchAndRewrite(ViewOp viewOp,
2151                                 PatternRewriter &rewriter) const override {
2152     // Return if none of the operands are constants.
2153     if (llvm::none_of(viewOp.getOperands(), [](Value operand) {
2154           return matchPattern(operand, matchConstantIndex());
2155         }))
2156       return failure();
2157 
2158     // Get result memref type.
2159     auto memrefType = viewOp.getType();
2160 
2161     // Get offset from old memref view type 'memRefType'.
2162     int64_t oldOffset;
2163     SmallVector<int64_t, 4> oldStrides;
2164     if (failed(getStridesAndOffset(memrefType, oldStrides, oldOffset)))
2165       return failure();
2166     assert(oldOffset == 0 && "Expected 0 offset");
2167 
2168     SmallVector<Value, 4> newOperands;
2169 
2170     // Offset cannot be folded into result type.
2171 
2172     // Fold any dynamic dim operands which are produced by a constant.
2173     SmallVector<int64_t, 4> newShapeConstants;
2174     newShapeConstants.reserve(memrefType.getRank());
2175 
2176     unsigned dynamicDimPos = 0;
2177     unsigned rank = memrefType.getRank();
2178     for (unsigned dim = 0, e = rank; dim < e; ++dim) {
2179       int64_t dimSize = memrefType.getDimSize(dim);
2180       // If this is already static dimension, keep it.
2181       if (!ShapedType::isDynamic(dimSize)) {
2182         newShapeConstants.push_back(dimSize);
2183         continue;
2184       }
2185       auto *defOp = viewOp.sizes()[dynamicDimPos].getDefiningOp();
2186       if (auto constantIndexOp = dyn_cast_or_null<ConstantIndexOp>(defOp)) {
2187         // Dynamic shape dimension will be folded.
2188         newShapeConstants.push_back(constantIndexOp.getValue());
2189       } else {
2190         // Dynamic shape dimension not folded; copy operand from old memref.
2191         newShapeConstants.push_back(dimSize);
2192         newOperands.push_back(viewOp.sizes()[dynamicDimPos]);
2193       }
2194       dynamicDimPos++;
2195     }
2196 
2197     // Create new memref type with constant folded dims.
2198     MemRefType newMemRefType =
2199         MemRefType::Builder(memrefType).setShape(newShapeConstants);
2200     // Nothing new, don't fold.
2201     if (newMemRefType == memrefType)
2202       return failure();
2203 
2204     // Create new ViewOp.
2205     auto newViewOp = rewriter.create<ViewOp>(viewOp.getLoc(), newMemRefType,
2206                                              viewOp.getOperand(0),
2207                                              viewOp.byte_shift(), newOperands);
2208     // Insert a cast so we have the same type as the old memref type.
2209     rewriter.replaceOpWithNewOp<CastOp>(viewOp, newViewOp, viewOp.getType());
2210     return success();
2211   }
2212 };
2213 
2214 struct ViewOpMemrefCastFolder : public OpRewritePattern<ViewOp> {
2215   using OpRewritePattern<ViewOp>::OpRewritePattern;
2216 
2217   LogicalResult matchAndRewrite(ViewOp viewOp,
2218                                 PatternRewriter &rewriter) const override {
2219     Value memrefOperand = viewOp.getOperand(0);
2220     CastOp memrefCastOp = memrefOperand.getDefiningOp<CastOp>();
2221     if (!memrefCastOp)
2222       return failure();
2223     Value allocOperand = memrefCastOp.getOperand();
2224     AllocOp allocOp = allocOperand.getDefiningOp<AllocOp>();
2225     if (!allocOp)
2226       return failure();
2227     rewriter.replaceOpWithNewOp<ViewOp>(viewOp, viewOp.getType(), allocOperand,
2228                                         viewOp.byte_shift(), viewOp.sizes());
2229     return success();
2230   }
2231 };
2232 
2233 } // end anonymous namespace
2234 
2235 void ViewOp::getCanonicalizationPatterns(RewritePatternSet &results,
2236                                          MLIRContext *context) {
2237   results.add<ViewOpShapeFolder, ViewOpMemrefCastFolder>(context);
2238 }
2239 
2240 //===----------------------------------------------------------------------===//
2241 // TableGen'd op method definitions
2242 //===----------------------------------------------------------------------===//
2243 
2244 #define GET_OP_CLASSES
2245 #include "mlir/Dialect/MemRef/IR/MemRefOps.cpp.inc"
2246