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