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