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