149e37000SMatthias Springer //===- BufferizableOpInterfaceImpl.cpp - Impl. of BufferizableOpInterface -===//
249e37000SMatthias Springer //
349e37000SMatthias Springer // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
449e37000SMatthias Springer // See https://llvm.org/LICENSE.txt for license information.
549e37000SMatthias Springer // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
649e37000SMatthias Springer //
749e37000SMatthias Springer //===----------------------------------------------------------------------===//
849e37000SMatthias Springer 
949e37000SMatthias Springer #include "mlir/Dialect/Tensor/Transforms/BufferizableOpInterfaceImpl.h"
10eda6f907SRiver Riddle #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
1149e37000SMatthias Springer #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
12b3ebe3beSMatthias Springer #include "mlir/Dialect/Bufferization/IR/Bufferization.h"
1349e37000SMatthias Springer #include "mlir/Dialect/MemRef/IR/MemRef.h"
148b68da2cSAlex Zinenko #include "mlir/Dialect/SCF/IR/SCF.h"
1549e37000SMatthias Springer #include "mlir/Dialect/Tensor/IR/Tensor.h"
1649e37000SMatthias Springer #include "mlir/IR/Dialect.h"
1749e37000SMatthias Springer #include "mlir/IR/Operation.h"
1849e37000SMatthias Springer 
1949e37000SMatthias Springer using namespace mlir;
2049e37000SMatthias Springer using namespace mlir::bufferization;
2149e37000SMatthias Springer using namespace mlir::tensor;
2249e37000SMatthias Springer 
2349e37000SMatthias Springer namespace mlir {
2449e37000SMatthias Springer namespace tensor {
2549e37000SMatthias Springer namespace {
2649e37000SMatthias Springer 
2749e37000SMatthias Springer struct CastOpInterface
2849e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<CastOpInterface,
2949e37000SMatthias Springer                                                     tensor::CastOp> {
3049e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
319597b16aSMatthias Springer                               const AnalysisState &state) const {
3249e37000SMatthias Springer     return false;
3349e37000SMatthias Springer   }
3449e37000SMatthias Springer 
3549e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
369597b16aSMatthias Springer                                const AnalysisState &state) const {
3749e37000SMatthias Springer     return false;
3849e37000SMatthias Springer   }
3949e37000SMatthias Springer 
409597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
419597b16aSMatthias Springer                                             const AnalysisState &state) const {
42585a8a32SMatthias Springer     return {op->getResult(0)};
4349e37000SMatthias Springer   }
4449e37000SMatthias Springer 
4549e37000SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
469597b16aSMatthias Springer                                 const AnalysisState &state) const {
4749e37000SMatthias Springer     return BufferRelation::Equivalent;
4849e37000SMatthias Springer   }
4949e37000SMatthias Springer 
5049e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
51b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
5249e37000SMatthias Springer     auto castOp = cast<tensor::CastOp>(op);
5349e37000SMatthias Springer 
5449e37000SMatthias Springer     // The result buffer still has the old (pre-cast) type.
555d50f51cSMatthias Springer     FailureOr<Value> resultBuffer =
565d50f51cSMatthias Springer         getBuffer(rewriter, castOp.getSource(), options);
575d50f51cSMatthias Springer     if (failed(resultBuffer))
585d50f51cSMatthias Springer       return failure();
595d50f51cSMatthias Springer     auto sourceMemRefType = resultBuffer->getType().cast<BaseMemRefType>();
6049e37000SMatthias Springer     TensorType resultTensorType =
6149e37000SMatthias Springer         castOp.getResult().getType().cast<TensorType>();
6249e37000SMatthias Springer     MemRefLayoutAttrInterface layout;
6349e37000SMatthias Springer 
6449e37000SMatthias Springer     if (auto rankedMemRefType = sourceMemRefType.dyn_cast<MemRefType>())
6549e37000SMatthias Springer       if (resultTensorType.isa<RankedTensorType>())
6649e37000SMatthias Springer         layout = rankedMemRefType.getLayout();
6749e37000SMatthias Springer 
6849e37000SMatthias Springer     // Compute the new memref type.
69b55d55ecSMatthias Springer     Type resultMemRefType =
70b06614e2SMatthias Springer         getMemRefType(resultTensorType, options, layout,
71b06614e2SMatthias Springer                       sourceMemRefType.getMemorySpaceAsInt());
7249e37000SMatthias Springer 
7349e37000SMatthias Springer     // Replace the op with a memref.cast.
745d50f51cSMatthias Springer     assert(memref::CastOp::areCastCompatible(resultBuffer->getType(),
7549e37000SMatthias Springer                                              resultMemRefType) &&
7649e37000SMatthias Springer            "CallOp::bufferize: cast incompatible");
7749e37000SMatthias Springer     replaceOpWithNewBufferizedOp<memref::CastOp>(rewriter, op, resultMemRefType,
785d50f51cSMatthias Springer                                                  *resultBuffer);
7949e37000SMatthias Springer 
8049e37000SMatthias Springer     return success();
8149e37000SMatthias Springer   }
8249e37000SMatthias Springer };
8349e37000SMatthias Springer 
84e6f69161SMatthias Springer /// Bufferization of tensor.collapse_shape. Replace with memref.collapse_shape.
85e6f69161SMatthias Springer struct CollapseShapeOpInterface
86e6f69161SMatthias Springer     : public BufferizableOpInterface::ExternalModel<CollapseShapeOpInterface,
87e6f69161SMatthias Springer                                                     tensor::CollapseShapeOp> {
88e6f69161SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
899597b16aSMatthias Springer                               const AnalysisState &state) const {
90e6f69161SMatthias Springer     return false;
91e6f69161SMatthias Springer   }
92e6f69161SMatthias Springer 
93e6f69161SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
949597b16aSMatthias Springer                                const AnalysisState &state) const {
95e6f69161SMatthias Springer     return false;
96e6f69161SMatthias Springer   }
97e6f69161SMatthias Springer 
989597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
999597b16aSMatthias Springer                                             const AnalysisState &state) const {
100e6f69161SMatthias Springer     if (&opOperand == &op->getOpOperand(0) /*src*/)
101e6f69161SMatthias Springer       return {op->getOpResult(0)};
102e6f69161SMatthias Springer     return {};
103e6f69161SMatthias Springer   }
104e6f69161SMatthias Springer 
105e6f69161SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
1069597b16aSMatthias Springer                                 const AnalysisState &state) const {
107e6f69161SMatthias Springer     return BufferRelation::Equivalent;
108e6f69161SMatthias Springer   }
109e6f69161SMatthias Springer 
110e6f69161SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
111b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
112e6f69161SMatthias Springer     auto collapseShapeOp = cast<tensor::CollapseShapeOp>(op);
11351df6238SMatthias Springer     RankedTensorType tensorResultType = collapseShapeOp.getResultType();
1145d50f51cSMatthias Springer     FailureOr<Value> maybeBuffer =
1155d50f51cSMatthias Springer         getBuffer(rewriter, collapseShapeOp.getSrc(), options);
1165d50f51cSMatthias Springer     if (failed(maybeBuffer))
1175d50f51cSMatthias Springer       return failure();
1185d50f51cSMatthias Springer     Value buffer = *maybeBuffer;
119b3ebe3beSMatthias Springer     auto bufferType = buffer.getType().cast<MemRefType>();
12051df6238SMatthias Springer 
12151df6238SMatthias Springer     if (tensorResultType.getRank() == 0) {
12251df6238SMatthias Springer       // 0-d collapses must go through a different op builder.
12373c0333dSMatthias Springer       MemRefType resultType;
12473c0333dSMatthias Springer 
12573c0333dSMatthias Springer       if (bufferType.getLayout().isIdentity()) {
12673c0333dSMatthias Springer         // Standard layout: result type has no offset.
12751df6238SMatthias Springer         MemRefLayoutAttrInterface layout;
12873c0333dSMatthias Springer         resultType = MemRefType::get({}, tensorResultType.getElementType(),
12951df6238SMatthias Springer                                      layout, bufferType.getMemorySpace());
13073c0333dSMatthias Springer       } else {
13173c0333dSMatthias Springer         // Source memref has a layout map: result type has the same offset as
13273c0333dSMatthias Springer         // the source type.
13373c0333dSMatthias Springer         SmallVector<int64_t> strides;
13473c0333dSMatthias Springer         int64_t offset;
13573c0333dSMatthias Springer         if (failed(getStridesAndOffset(bufferType, strides, offset)))
13673c0333dSMatthias Springer           return failure();
13773c0333dSMatthias Springer         AffineMap resultLayout =
13873c0333dSMatthias Springer             makeStridedLinearLayoutMap({}, offset, op->getContext());
13973c0333dSMatthias Springer         resultType =
14073c0333dSMatthias Springer             MemRefType::get({}, tensorResultType.getElementType(), resultLayout,
14173c0333dSMatthias Springer                             bufferType.getMemorySpaceAsInt());
14273c0333dSMatthias Springer       }
14373c0333dSMatthias Springer 
144e6f69161SMatthias Springer       replaceOpWithNewBufferizedOp<memref::CollapseShapeOp>(
1458df54a6aSJacques Pienaar           rewriter, op, resultType, buffer, collapseShapeOp.getReassociation());
146e6f69161SMatthias Springer       return success();
147e6f69161SMatthias Springer     }
14851df6238SMatthias Springer 
149d7a9bf91SMatthias Springer     // If the dims are not collapsible (due to an incompatible source layout
150d7a9bf91SMatthias Springer     // map), force an out-of-place bufferization, i.e., a buffer copy. This
151d7a9bf91SMatthias Springer     // newly allocated buffer will have no layout map and thus be collapsible.
152a74e5a89SAdrian Kuegel     bool canBeCollapsed = memref::CollapseShapeOp::isGuaranteedCollapsible(
153d7a9bf91SMatthias Springer         bufferType, collapseShapeOp.getReassociationIndices());
154b3ebe3beSMatthias Springer     if (!canBeCollapsed) {
155b3ebe3beSMatthias Springer       // TODO: Create alloc_tensor ops during TensorCopyInsertion.
156b55d55ecSMatthias Springer       AnalysisState analysisState(options);
157*45b995cdSMatthias Springer       FailureOr<Value> tensorAlloc = allocateTensorForShapedValue(
1588df54a6aSJacques Pienaar           rewriter, op->getLoc(), collapseShapeOp.getSrc(),
159*45b995cdSMatthias Springer           analysisState.isTensorYielded(collapseShapeOp.getResult()), options);
160*45b995cdSMatthias Springer       if (failed(tensorAlloc))
161*45b995cdSMatthias Springer         return failure();
162b3ebe3beSMatthias Springer       auto memrefType =
163b3ebe3beSMatthias Springer           MemRefType::get(collapseShapeOp.getSrcType().getShape(),
164b3ebe3beSMatthias Springer                           collapseShapeOp.getSrcType().getElementType(),
165b3ebe3beSMatthias Springer                           AffineMap(), bufferType.getMemorySpaceAsInt());
166b3ebe3beSMatthias Springer       buffer = rewriter.create<bufferization::ToMemrefOp>(
167*45b995cdSMatthias Springer           op->getLoc(), memrefType, *tensorAlloc);
168b3ebe3beSMatthias Springer     }
169d7a9bf91SMatthias Springer 
17051df6238SMatthias Springer     // Result type is inferred by the builder.
17151df6238SMatthias Springer     replaceOpWithNewBufferizedOp<memref::CollapseShapeOp>(
172b3ebe3beSMatthias Springer         rewriter, op, buffer, collapseShapeOp.getReassociationIndices());
17351df6238SMatthias Springer     return success();
17451df6238SMatthias Springer   }
175e6f69161SMatthias Springer };
176e6f69161SMatthias Springer 
17749e37000SMatthias Springer /// Bufferization of tensor.dim. Replace with memref.dim.
17849e37000SMatthias Springer struct DimOpInterface
17949e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<DimOpInterface,
18049e37000SMatthias Springer                                                     tensor::DimOp> {
18149e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
1829597b16aSMatthias Springer                               const AnalysisState &state) const {
18349e37000SMatthias Springer     return true;
18449e37000SMatthias Springer   }
18549e37000SMatthias Springer 
18649e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
1879597b16aSMatthias Springer                                const AnalysisState &state) const {
18849e37000SMatthias Springer     return false;
18949e37000SMatthias Springer   }
19049e37000SMatthias Springer 
1919597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
1929597b16aSMatthias Springer                                             const AnalysisState &state) const {
193585a8a32SMatthias Springer     return {};
19449e37000SMatthias Springer   }
19549e37000SMatthias Springer 
19649e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
197b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
19849e37000SMatthias Springer     auto dimOp = cast<tensor::DimOp>(op);
1995d50f51cSMatthias Springer     FailureOr<Value> v = getBuffer(rewriter, dimOp.getSource(), options);
2005d50f51cSMatthias Springer     if (failed(v))
2015d50f51cSMatthias Springer       return failure();
2025d50f51cSMatthias Springer     replaceOpWithNewBufferizedOp<memref::DimOp>(rewriter, op, *v,
2035d50f51cSMatthias Springer                                                 dimOp.index());
20449e37000SMatthias Springer     return success();
20549e37000SMatthias Springer   }
20649e37000SMatthias Springer };
20749e37000SMatthias Springer 
208e6f69161SMatthias Springer /// Bufferization of tensor.expand_shape. Replace with memref.expand_shape.
209e6f69161SMatthias Springer struct ExpandShapeOpInterface
210e6f69161SMatthias Springer     : public BufferizableOpInterface::ExternalModel<ExpandShapeOpInterface,
211e6f69161SMatthias Springer                                                     tensor::ExpandShapeOp> {
212e6f69161SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
2139597b16aSMatthias Springer                               const AnalysisState &state) const {
214e6f69161SMatthias Springer     return false;
215e6f69161SMatthias Springer   }
216e6f69161SMatthias Springer 
217e6f69161SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
2189597b16aSMatthias Springer                                const AnalysisState &state) const {
219e6f69161SMatthias Springer     return false;
220e6f69161SMatthias Springer   }
221e6f69161SMatthias Springer 
2229597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
2239597b16aSMatthias Springer                                             const AnalysisState &state) const {
224e6f69161SMatthias Springer     if (&opOperand == &op->getOpOperand(0) /*src*/)
225e6f69161SMatthias Springer       return {op->getOpResult(0)};
226e6f69161SMatthias Springer     return {};
227e6f69161SMatthias Springer   }
228e6f69161SMatthias Springer 
229e6f69161SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
2309597b16aSMatthias Springer                                 const AnalysisState &state) const {
231e6f69161SMatthias Springer     return BufferRelation::Equivalent;
232e6f69161SMatthias Springer   }
233e6f69161SMatthias Springer 
234e6f69161SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
235b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
236e6f69161SMatthias Springer     auto expandShapeOp = cast<tensor::ExpandShapeOp>(op);
23751df6238SMatthias Springer     auto tensorResultType = expandShapeOp.getResultType();
2385d50f51cSMatthias Springer     FailureOr<Value> buffer =
2395d50f51cSMatthias Springer         getBuffer(rewriter, expandShapeOp.getSrc(), options);
2405d50f51cSMatthias Springer     if (failed(buffer))
2415d50f51cSMatthias Springer       return failure();
24251df6238SMatthias Springer 
24351df6238SMatthias Springer     // Memref result type is inferred by the builder based on reassociation
24451df6238SMatthias Springer     // indices and result shape.
245e6f69161SMatthias Springer     replaceOpWithNewBufferizedOp<memref::ExpandShapeOp>(
2465d50f51cSMatthias Springer         rewriter, op, tensorResultType.getShape(), *buffer,
24751df6238SMatthias Springer         expandShapeOp.getReassociationIndices());
248e6f69161SMatthias Springer     return success();
249e6f69161SMatthias Springer   }
250e6f69161SMatthias Springer };
251e6f69161SMatthias Springer 
25249e37000SMatthias Springer /// Bufferization of tensor.extract_slice. Replace with memref.subview.
25349e37000SMatthias Springer struct ExtractSliceOpInterface
25449e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<ExtractSliceOpInterface,
25549e37000SMatthias Springer                                                     tensor::ExtractSliceOp> {
25649e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
2579597b16aSMatthias Springer                               const AnalysisState &state) const {
25849e37000SMatthias Springer     return false;
25949e37000SMatthias Springer   }
26049e37000SMatthias Springer 
26149e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
2629597b16aSMatthias Springer                                const AnalysisState &state) const {
26349e37000SMatthias Springer     return false;
26449e37000SMatthias Springer   }
26549e37000SMatthias Springer 
2669597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
2679597b16aSMatthias Springer                                             const AnalysisState &state) const {
268585a8a32SMatthias Springer     if (&opOperand == &op->getOpOperand(0) /*source*/)
269585a8a32SMatthias Springer       return {op->getOpResult(0)};
270585a8a32SMatthias Springer     return {};
27149e37000SMatthias Springer   }
27249e37000SMatthias Springer 
27349e37000SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
2749597b16aSMatthias Springer                                 const AnalysisState &state) const {
27549e37000SMatthias Springer     return BufferRelation::None;
27649e37000SMatthias Springer   }
27749e37000SMatthias Springer 
27849e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
279b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
28049e37000SMatthias Springer     auto extractSliceOp = cast<tensor::ExtractSliceOp>(op);
28149e37000SMatthias Springer     Location loc = extractSliceOp.getLoc();
282d7a9bf91SMatthias Springer 
283d7a9bf91SMatthias Springer     // Even if this op was decided to bufferize out-of-place, do not insert the
284d7a9bf91SMatthias Springer     // buffer copy yet. This is done later in this function.
2855d50f51cSMatthias Springer     FailureOr<Value> srcMemref =
2865d50f51cSMatthias Springer         getBuffer(rewriter, extractSliceOp.getSource(), options);
2875d50f51cSMatthias Springer     if (failed(srcMemref))
2885d50f51cSMatthias Springer       return failure();
2895d50f51cSMatthias Springer     auto srcMemrefType = srcMemref->getType().cast<MemRefType>();
29049e37000SMatthias Springer     auto dstTensorType =
2918df54a6aSJacques Pienaar         extractSliceOp.getResult().getType().cast<RankedTensorType>();
29249e37000SMatthias Springer 
29349e37000SMatthias Springer     // Expand offsets, sizes and strides to the full rank to handle the
29449e37000SMatthias Springer     // rank-reducing case.
29549e37000SMatthias Springer     SmallVector<OpFoldResult> mixedOffsets = extractSliceOp.getMixedOffsets();
29649e37000SMatthias Springer     SmallVector<OpFoldResult> mixedSizes = extractSliceOp.getMixedSizes();
29749e37000SMatthias Springer     SmallVector<OpFoldResult> mixedStrides = extractSliceOp.getMixedStrides();
29849e37000SMatthias Springer     OffsetSizeAndStrideOpInterface::expandToRank(
2995d50f51cSMatthias Springer         *srcMemref, mixedOffsets, mixedSizes, mixedStrides,
30049e37000SMatthias Springer         [&](Value target, int64_t dim) -> OpFoldResult {
30149e37000SMatthias Springer           auto shapedType = target.getType().cast<ShapedType>();
30249e37000SMatthias Springer           if (shapedType.isDynamicDim(dim))
30349e37000SMatthias Springer             return rewriter.create<memref::DimOp>(loc, target, dim).result();
30449e37000SMatthias Springer           return rewriter.getIndexAttr(shapedType.getDimSize(dim));
30549e37000SMatthias Springer         });
30649e37000SMatthias Springer     // Bufferize to subview.
30749e37000SMatthias Springer     auto subviewMemRefType = memref::SubViewOp::inferRankReducedResultType(
30849e37000SMatthias Springer                                  dstTensorType.getRank(), srcMemrefType,
30949e37000SMatthias Springer                                  mixedOffsets, mixedSizes, mixedStrides)
31049e37000SMatthias Springer                                  .cast<MemRefType>();
31149e37000SMatthias Springer     Value subView = rewriter.create<memref::SubViewOp>(
3125d50f51cSMatthias Springer         loc, subviewMemRefType, *srcMemref, mixedOffsets, mixedSizes,
31349e37000SMatthias Springer         mixedStrides);
31449e37000SMatthias Springer 
31549e37000SMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, subView);
31649e37000SMatthias Springer     return success();
31749e37000SMatthias Springer   }
31849e37000SMatthias Springer };
31949e37000SMatthias Springer 
32049e37000SMatthias Springer /// Bufferization of tensor.extract. Replace with memref.load.
32149e37000SMatthias Springer struct ExtractOpInterface
32249e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<ExtractOpInterface,
32349e37000SMatthias Springer                                                     tensor::ExtractOp> {
32449e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
3259597b16aSMatthias Springer                               const AnalysisState &state) const {
32649e37000SMatthias Springer     return true;
32749e37000SMatthias Springer   }
32849e37000SMatthias Springer 
32949e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
3309597b16aSMatthias Springer                                const AnalysisState &state) const {
33149e37000SMatthias Springer     return false;
33249e37000SMatthias Springer   }
33349e37000SMatthias Springer 
3349597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
3359597b16aSMatthias Springer                                             const AnalysisState &state) const {
336585a8a32SMatthias Springer     return {};
33749e37000SMatthias Springer   }
33849e37000SMatthias Springer 
33949e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
340b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
34149e37000SMatthias Springer     auto extractOp = cast<tensor::ExtractOp>(op);
3425d50f51cSMatthias Springer     FailureOr<Value> srcMemref =
3435d50f51cSMatthias Springer         getBuffer(rewriter, extractOp.getTensor(), options);
3445d50f51cSMatthias Springer     if (failed(srcMemref))
3455d50f51cSMatthias Springer       return failure();
3465d50f51cSMatthias Springer     replaceOpWithNewBufferizedOp<memref::LoadOp>(rewriter, op, *srcMemref,
3475d50f51cSMatthias Springer                                                  extractOp.indices());
34849e37000SMatthias Springer     return success();
34949e37000SMatthias Springer   }
35049e37000SMatthias Springer };
35149e37000SMatthias Springer 
352d581c94dSMatthias Springer // Implements backtracking to traverse indices of the output buffer while
353d581c94dSMatthias Springer // iterating over op.elements().
354d581c94dSMatthias Springer static void createStores(RewriterBase &rewriter, Location loc, int dim,
355d581c94dSMatthias Springer                          Value buffer, ArrayRef<int64_t> shape,
356d581c94dSMatthias Springer                          ArrayRef<Value> constants,
357d581c94dSMatthias Springer                          OperandRange::iterator &elementIt,
358d581c94dSMatthias Springer                          SmallVectorImpl<Value> &indices) {
359d581c94dSMatthias Springer   if (dim == static_cast<int>(shape.size()) - 1) {
360d581c94dSMatthias Springer     for (int i = 0; i < shape.back(); ++i) {
361d581c94dSMatthias Springer       indices.back() = constants[i];
362d581c94dSMatthias Springer       rewriter.create<memref::StoreOp>(loc, *elementIt, buffer, indices);
363d581c94dSMatthias Springer       ++elementIt;
364d581c94dSMatthias Springer     }
365d581c94dSMatthias Springer     return;
366d581c94dSMatthias Springer   }
367d581c94dSMatthias Springer   for (int i = 0; i < shape[dim]; ++i) {
368d581c94dSMatthias Springer     indices[dim] = constants[i];
369d581c94dSMatthias Springer     createStores(rewriter, loc, dim + 1, buffer, shape, constants, elementIt,
370d581c94dSMatthias Springer                  indices);
371d581c94dSMatthias Springer   }
372d581c94dSMatthias Springer }
373d581c94dSMatthias Springer 
374d581c94dSMatthias Springer /// Bufferization of tensor.from_elements.
375d581c94dSMatthias Springer struct FromElementsOpInterface
376d581c94dSMatthias Springer     : public BufferizableOpInterface::ExternalModel<FromElementsOpInterface,
377d581c94dSMatthias Springer                                                     tensor::FromElementsOp> {
378d581c94dSMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
379b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
380d581c94dSMatthias Springer     auto fromElementsOp = cast<tensor::FromElementsOp>(op);
381d581c94dSMatthias Springer 
382d581c94dSMatthias Springer     // Allocate a buffer for the result.
383d581c94dSMatthias Springer     Location loc = op->getLoc();
384d581c94dSMatthias Springer     auto tensorType = fromElementsOp.getType().cast<RankedTensorType>();
385d581c94dSMatthias Springer     auto shape = tensorType.getShape();
386b3ebe3beSMatthias Springer     // TODO: Create alloc_tensor ops during TensorCopyInsertion.
387b55d55ecSMatthias Springer     AnalysisState analysisState(options);
388*45b995cdSMatthias Springer     FailureOr<Value> tensorAlloc = allocateTensorForShapedValue(
3898df54a6aSJacques Pienaar         rewriter, loc, fromElementsOp.getResult(),
390*45b995cdSMatthias Springer         analysisState.isTensorYielded(fromElementsOp.getResult()), options,
391b3ebe3beSMatthias Springer         /*copy=*/false);
392*45b995cdSMatthias Springer     if (failed(tensorAlloc))
393*45b995cdSMatthias Springer       return failure();
394b3ebe3beSMatthias Springer     auto memrefType =
395b3ebe3beSMatthias Springer         MemRefType::get(tensorType.getShape(), tensorType.getElementType());
396b3ebe3beSMatthias Springer     Value buffer = rewriter.create<bufferization::ToMemrefOp>(
397*45b995cdSMatthias Springer         op->getLoc(), memrefType, *tensorAlloc);
398d581c94dSMatthias Springer 
399d581c94dSMatthias Springer     // Case: tensor<0xelem_type>.
4008df54a6aSJacques Pienaar     if (fromElementsOp.getElements().empty()) {
401d581c94dSMatthias Springer       replaceOpWithBufferizedValues(rewriter, op, buffer);
402d581c94dSMatthias Springer       return success();
403d581c94dSMatthias Springer     }
404d581c94dSMatthias Springer 
405d581c94dSMatthias Springer     // Case: tensor<elem_type>.
406d581c94dSMatthias Springer     if (shape.empty()) {
4078df54a6aSJacques Pienaar       rewriter.create<memref::StoreOp>(
4088df54a6aSJacques Pienaar           loc, fromElementsOp.getElements().front(), buffer);
409d581c94dSMatthias Springer       replaceOpWithBufferizedValues(rewriter, op, buffer);
410d581c94dSMatthias Springer       return success();
411d581c94dSMatthias Springer     }
412d581c94dSMatthias Springer 
413d581c94dSMatthias Springer     // Create constants for the range of possible indices [0, max{shape_i}).
414d581c94dSMatthias Springer     auto maxDim = *std::max_element(shape.begin(), shape.end());
415d581c94dSMatthias Springer     SmallVector<Value, 2> constants;
416d581c94dSMatthias Springer     constants.reserve(maxDim);
417d581c94dSMatthias Springer     for (int i = 0; i < maxDim; ++i)
418d581c94dSMatthias Springer       constants.push_back(rewriter.create<arith::ConstantIndexOp>(loc, i));
419d581c94dSMatthias Springer 
420d581c94dSMatthias Springer     // Traverse all `elements` and create `memref.store` ops.
4218df54a6aSJacques Pienaar     auto elementIt = fromElementsOp.getElements().begin();
422d581c94dSMatthias Springer     SmallVector<Value, 2> indices(tensorType.getRank(), constants[0]);
423d581c94dSMatthias Springer     createStores(rewriter, loc, /*dim=*/0, buffer, shape, constants, elementIt,
424d581c94dSMatthias Springer                  indices);
425d581c94dSMatthias Springer 
426d581c94dSMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, buffer);
427d581c94dSMatthias Springer     return success();
428d581c94dSMatthias Springer   }
429d581c94dSMatthias Springer };
430d581c94dSMatthias Springer 
43171bbb78bSMatthias Springer /// Bufferization of tensor.generate.
43271bbb78bSMatthias Springer struct GenerateOpInterface
43371bbb78bSMatthias Springer     : public BufferizableOpInterface::ExternalModel<GenerateOpInterface,
43471bbb78bSMatthias Springer                                                     tensor::GenerateOp> {
43571bbb78bSMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
436b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
43771bbb78bSMatthias Springer     auto generateOp = cast<tensor::GenerateOp>(op);
438b3ebe3beSMatthias Springer     auto tensorType = generateOp.getType().cast<RankedTensorType>();
43971bbb78bSMatthias Springer     // Allocate memory.
44071bbb78bSMatthias Springer     Location loc = op->getLoc();
441b3ebe3beSMatthias Springer     // TODO: Create alloc_tensor ops during TensorCopyInsertion.
442b55d55ecSMatthias Springer     AnalysisState analysisState(options);
443*45b995cdSMatthias Springer     FailureOr<Value> tensorAlloc = allocateTensorForShapedValue(
4448df54a6aSJacques Pienaar         rewriter, loc, generateOp.getResult(),
445*45b995cdSMatthias Springer         analysisState.isTensorYielded(generateOp.getResult()), options,
446b3ebe3beSMatthias Springer         /*copy=*/false);
447*45b995cdSMatthias Springer     if (failed(tensorAlloc))
448*45b995cdSMatthias Springer       return failure();
449b3ebe3beSMatthias Springer     auto memrefType =
450b3ebe3beSMatthias Springer         MemRefType::get(tensorType.getShape(), tensorType.getElementType());
451b3ebe3beSMatthias Springer     Value buffer = rewriter.create<bufferization::ToMemrefOp>(
452*45b995cdSMatthias Springer         op->getLoc(), memrefType, *tensorAlloc);
45371bbb78bSMatthias Springer 
45471bbb78bSMatthias Springer     // Collect loop bounds.
45571bbb78bSMatthias Springer     int64_t rank = memrefType.getRank();
45671bbb78bSMatthias Springer     Value zero = rewriter.create<arith::ConstantIndexOp>(loc, 0);
45771bbb78bSMatthias Springer     Value one = rewriter.create<arith::ConstantIndexOp>(loc, 1);
45871bbb78bSMatthias Springer     SmallVector<Value, 4> lowerBounds(rank, zero);
45971bbb78bSMatthias Springer     SmallVector<Value, 4> steps(rank, one);
46071bbb78bSMatthias Springer     SmallVector<Value, 4> upperBounds;
46171bbb78bSMatthias Springer     int nextDynamicIndex = 0;
46271bbb78bSMatthias Springer     for (int i = 0; i < rank; i++) {
4638df54a6aSJacques Pienaar       Value upperBound =
4648df54a6aSJacques Pienaar           memrefType.isDynamicDim(i)
4658df54a6aSJacques Pienaar               ? generateOp.getDynamicExtents()[nextDynamicIndex++]
46671bbb78bSMatthias Springer               : rewriter.create<arith::ConstantIndexOp>(
46771bbb78bSMatthias Springer                     loc, memrefType.getDimSize(i));
46871bbb78bSMatthias Springer       upperBounds.push_back(upperBound);
46971bbb78bSMatthias Springer     }
47071bbb78bSMatthias Springer 
47171bbb78bSMatthias Springer     // Generate tensor elements with a parallel loop that stores into
47271bbb78bSMatthias Springer     // each element of the resulting memref. We use mergeBlockBefore to "move"
47371bbb78bSMatthias Springer     // this op's body into the scf.parallel's body.
47471bbb78bSMatthias Springer     auto parallel =
47571bbb78bSMatthias Springer         rewriter.create<scf::ParallelOp>(loc, lowerBounds, upperBounds, steps);
47671bbb78bSMatthias Springer     Block *parallelBody = parallel.getBody();
477eca86cb2SJacques Pienaar     rewriter.mergeBlockBefore(&generateOp.getBody().front(),
47871bbb78bSMatthias Springer                               parallelBody->getTerminator(),
47971bbb78bSMatthias Springer                               parallelBody->getArguments());
48071bbb78bSMatthias Springer     // Replace the inlined yield op with a store op. The scf.parallel's builder
48171bbb78bSMatthias Springer     // already populated an scf.yield at the end, so we don't need to worry
48271bbb78bSMatthias Springer     // about creating that.
48371bbb78bSMatthias Springer     Operation *elementYield = parallelBody->getTerminator()->getPrevNode();
48471bbb78bSMatthias Springer     rewriter.setInsertionPointAfter(elementYield);
48571bbb78bSMatthias Springer     rewriter.replaceOpWithNewOp<memref::StoreOp>(
486b3ebe3beSMatthias Springer         elementYield, elementYield->getOperands()[0], buffer,
48771bbb78bSMatthias Springer         parallelBody->getArguments());
48871bbb78bSMatthias Springer 
489b3ebe3beSMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, buffer);
49071bbb78bSMatthias Springer     return success();
49171bbb78bSMatthias Springer   }
49271bbb78bSMatthias Springer };
49371bbb78bSMatthias Springer 
49449e37000SMatthias Springer /// Bufferization of tensor.insert. Replace with memref.store.
49549e37000SMatthias Springer struct InsertOpInterface
49649e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<InsertOpInterface,
49749e37000SMatthias Springer                                                     tensor::InsertOp> {
49849e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
4999597b16aSMatthias Springer                               const AnalysisState &state) const {
50049e37000SMatthias Springer     return true;
50149e37000SMatthias Springer   }
50249e37000SMatthias Springer 
50349e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
5049597b16aSMatthias Springer                                const AnalysisState &state) const {
50549e37000SMatthias Springer     return true;
50649e37000SMatthias Springer   }
50749e37000SMatthias Springer 
5089597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
5099597b16aSMatthias Springer                                             const AnalysisState &state) const {
51049e37000SMatthias Springer     assert(&opOperand == &op->getOpOperand(1) /*dest*/ &&
51149e37000SMatthias Springer            "expected dest OpOperand");
512585a8a32SMatthias Springer     return {op->getOpResult(0)};
51349e37000SMatthias Springer   }
51449e37000SMatthias Springer 
51549e37000SMatthias Springer   SmallVector<OpOperand *>
51649e37000SMatthias Springer   getAliasingOpOperand(Operation *op, OpResult opResult,
5179597b16aSMatthias Springer                        const AnalysisState &state) const {
51849e37000SMatthias Springer     return {&op->getOpOperand(1) /*dest*/};
51949e37000SMatthias Springer   }
52049e37000SMatthias Springer 
52149e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
522b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
52349e37000SMatthias Springer     auto insertOp = cast<tensor::InsertOp>(op);
5245d50f51cSMatthias Springer     FailureOr<Value> destMemref =
5255d50f51cSMatthias Springer         getBuffer(rewriter, insertOp.getDest(), options);
5265d50f51cSMatthias Springer     if (failed(destMemref))
5275d50f51cSMatthias Springer       return failure();
5288df54a6aSJacques Pienaar     rewriter.create<memref::StoreOp>(insertOp.getLoc(), insertOp.getScalar(),
5295d50f51cSMatthias Springer                                      *destMemref, insertOp.getIndices());
5305d50f51cSMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, *destMemref);
53149e37000SMatthias Springer     return success();
53249e37000SMatthias Springer   }
53349e37000SMatthias Springer 
53449e37000SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
5359597b16aSMatthias Springer                                 const AnalysisState &state) const {
53649e37000SMatthias Springer     return BufferRelation::Equivalent;
53749e37000SMatthias Springer   }
53849e37000SMatthias Springer };
53949e37000SMatthias Springer 
54049e37000SMatthias Springer /// Return true if the (ExtractSliceOp, InsertSliceOp) pair match (i.e.
54149e37000SMatthias Springer /// equivalent operand / result and same offset/sizes/strides specification).
54249e37000SMatthias Springer ///
54349e37000SMatthias Springer /// This is one particular type of relationship between ops on tensors that
54449e37000SMatthias Springer /// reduce to an equivalence on buffers. This should be generalized and
54549e37000SMatthias Springer /// exposed as interfaces on the proper types.
5469597b16aSMatthias Springer static bool areEquivalentExtractSliceOps(const AnalysisState &state,
54749e37000SMatthias Springer                                          ExtractSliceOp st, InsertSliceOp sti) {
54849e37000SMatthias Springer   if (!st || !sti)
54949e37000SMatthias Springer     return false;
55049e37000SMatthias Springer   if (sti != sti &&
5518df54a6aSJacques Pienaar       !state.areEquivalentBufferizedValues(st.getSource(), sti.getDest()))
55249e37000SMatthias Springer     return false;
55349e37000SMatthias Springer   if (!sameOffsetsSizesAndStrides(st, sti, isEqualConstantIntOrValue))
55449e37000SMatthias Springer     return false;
55549e37000SMatthias Springer   return true;
55649e37000SMatthias Springer }
55749e37000SMatthias Springer 
55849e37000SMatthias Springer /// Return true if `value` is originating from an ExtractSliceOp that matches
55949e37000SMatthias Springer /// the given InsertSliceOp.
5609597b16aSMatthias Springer static bool hasMatchingExtractSliceOp(const AnalysisState &state, Value value,
5619597b16aSMatthias Springer                                       InsertSliceOp insertOp) {
56249e37000SMatthias Springer   auto condition = [&](Value val) {
56349e37000SMatthias Springer     if (auto extractOp = val.getDefiningOp<ExtractSliceOp>())
56449e37000SMatthias Springer       if (areEquivalentExtractSliceOps(state, extractOp, insertOp))
56549e37000SMatthias Springer         return true;
56649e37000SMatthias Springer     return false;
56749e37000SMatthias Springer   };
56849e37000SMatthias Springer 
56949e37000SMatthias Springer   return llvm::all_of(state.findValueInReverseUseDefChain(value, condition),
57049e37000SMatthias Springer                       condition);
57149e37000SMatthias Springer }
57249e37000SMatthias Springer 
57349e37000SMatthias Springer /// Bufferization of tensor.insert_slice. Replace with a memory copy. Under
57449e37000SMatthias Springer /// certain circumstances, this op can also be a no-op.
57549e37000SMatthias Springer struct InsertSliceOpInterface
57649e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<InsertSliceOpInterface,
57749e37000SMatthias Springer                                                     tensor::InsertSliceOp> {
57849e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
5799597b16aSMatthias Springer                               const AnalysisState &state) const {
58049e37000SMatthias Springer     return true;
58149e37000SMatthias Springer   }
58249e37000SMatthias Springer 
58349e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
5849597b16aSMatthias Springer                                const AnalysisState &state) const {
58549e37000SMatthias Springer     return &opOperand == &op->getOpOperand(1) /*dest*/;
58649e37000SMatthias Springer   }
58749e37000SMatthias Springer 
5889597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
5899597b16aSMatthias Springer                                             const AnalysisState &state) const {
590585a8a32SMatthias Springer     if (&opOperand == &op->getOpOperand(1) /*dest*/)
591585a8a32SMatthias Springer       return {op->getResult(0)};
592585a8a32SMatthias Springer     return {};
59349e37000SMatthias Springer   }
59449e37000SMatthias Springer 
59549e37000SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
5969597b16aSMatthias Springer                                 const AnalysisState &state) const {
59749e37000SMatthias Springer     return BufferRelation::Equivalent;
59849e37000SMatthias Springer   }
59949e37000SMatthias Springer 
60049e37000SMatthias Springer   bool isNotConflicting(Operation *op, OpOperand *uRead,
60149e37000SMatthias Springer                         OpOperand *uConflictingWrite,
6029597b16aSMatthias Springer                         const AnalysisState &state) const {
60349e37000SMatthias Springer     Operation *readingOp = uRead->getOwner();
60449e37000SMatthias Springer     Operation *conflictingWritingOp = uConflictingWrite->getOwner();
60549e37000SMatthias Springer 
60649e37000SMatthias Springer     // Special rules for matching ExtractSliceOp/InsertSliceOp pairs. If
60749e37000SMatthias Springer     // uRead is an InsertSliceOp...
60849e37000SMatthias Springer     if (auto insertSliceOp = dyn_cast<InsertSliceOp>(readingOp)) {
60949e37000SMatthias Springer       // As an example, consider the following IR.
61049e37000SMatthias Springer       //
61149e37000SMatthias Springer       // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
61249e37000SMatthias Springer       // %1 = linalg.fill %cst, %0 {inplace= [true] }
61349e37000SMatthias Springer       // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
61449e37000SMatthias Springer       //     {inplace= [true] }
61549e37000SMatthias Springer 
61649e37000SMatthias Springer       // TODO: Use insertSliceOp.getDestOpOperand etc. when available.
61749e37000SMatthias Springer       if (uRead == &insertSliceOp->getOpOperand(1) /*dest*/ &&
61849e37000SMatthias Springer           hasMatchingExtractSliceOp(state, uConflictingWrite->get(),
61949e37000SMatthias Springer                                     insertSliceOp))
62049e37000SMatthias Springer         // Case 1: The main insight is that InsertSliceOp reads only part of
62149e37000SMatthias Springer         // the destination tensor. The overwritten area is not read. If
62249e37000SMatthias Springer         // uConflictingWrite writes into exactly the memory location that is
62349e37000SMatthias Springer         // being read by uRead, this is not a conflict.
62449e37000SMatthias Springer         //
62549e37000SMatthias Springer         // In the above example:
62649e37000SMatthias Springer         // uRead             = OpOperand 1 (%t) of tensor.insert_slice
62749e37000SMatthias Springer         // uConflictingWrite = OpOperand 1 (%0) of linalg.fill
62849e37000SMatthias Springer         //
62949e37000SMatthias Springer         // The read of %t does not conflict with the write of the FillOp
63049e37000SMatthias Springer         // (same aliases!) because the area that the FillOp operates on is
63149e37000SMatthias Springer         // exactly the one that is *not* read via %t.
63249e37000SMatthias Springer         return true;
63349e37000SMatthias Springer 
63449e37000SMatthias Springer       if (uRead == &insertSliceOp->getOpOperand(0) /*source*/ &&
63549e37000SMatthias Springer           uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ &&
63649e37000SMatthias Springer           hasMatchingExtractSliceOp(state, uRead->get(), insertSliceOp))
63749e37000SMatthias Springer         // Case 2: The read of the source tensor and the write to the dest
63849e37000SMatthias Springer         // tensor via an InsertSliceOp is not a conflict if the read is
63949e37000SMatthias Springer         // reading exactly that part of an equivalent tensor that the
64049e37000SMatthias Springer         // InsertSliceOp is writing.
64149e37000SMatthias Springer         //
64249e37000SMatthias Springer         // In the above example:
64349e37000SMatthias Springer         // uRead             = OpOperand 0 (%1) of tensor.insert_slice
64449e37000SMatthias Springer         // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
64549e37000SMatthias Springer         return true;
64649e37000SMatthias Springer     }
64749e37000SMatthias Springer 
64849e37000SMatthias Springer     // If uConflictingWrite is an InsertSliceOp...
64949e37000SMatthias Springer     if (auto insertSliceOp = dyn_cast<InsertSliceOp>(conflictingWritingOp))
65049e37000SMatthias Springer       // As an example, consider the following IR.
65149e37000SMatthias Springer       //
65249e37000SMatthias Springer       // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
65349e37000SMatthias Springer       // %1 = linalg.fill %cst, %0 {inplace= [true] }
65449e37000SMatthias Springer       // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
65549e37000SMatthias Springer       //     {inplace= [true] }
65649e37000SMatthias Springer       // %3 = vector.transfer_read %1, %cst
65749e37000SMatthias Springer       //
65849e37000SMatthias Springer       // In the above example:
65949e37000SMatthias Springer       // uRead             = OpOperand 0 (%1) of vector.transfer_read
66049e37000SMatthias Springer       // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
66149e37000SMatthias Springer       // lastWrite         = %1
66249e37000SMatthias Springer       //
66349e37000SMatthias Springer       // This is not a conflict because the InsertSliceOp overwrites the
66449e37000SMatthias Springer       // memory segment of %1 with the exact same data. (Effectively, there
66549e37000SMatthias Springer       // is no memory write here.)
66649e37000SMatthias Springer       if (uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ &&
66749e37000SMatthias Springer           state.areEquivalentBufferizedValues(uRead->get(),
6688df54a6aSJacques Pienaar                                               insertSliceOp.getSource()) &&
6698df54a6aSJacques Pienaar           hasMatchingExtractSliceOp(state, insertSliceOp.getSource(),
67049e37000SMatthias Springer                                     insertSliceOp))
67149e37000SMatthias Springer         return true;
67249e37000SMatthias Springer 
67349e37000SMatthias Springer     return false;
67449e37000SMatthias Springer   }
67549e37000SMatthias Springer 
67649e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
677b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
67849e37000SMatthias Springer     // insert_slice ops arise from tiling and bufferizing them out-of-place is
67949e37000SMatthias Springer     // generally a deal breaker. When used with loops, this ends up cloning the
68049e37000SMatthias Springer     // whole tensor on every single iteration and is a symptom of a
68149e37000SMatthias Springer     // catastrophically bad scheduling decision.
68249e37000SMatthias Springer     // TODO: be very loud about it or even consider failing the pass.
68349e37000SMatthias Springer     auto insertSliceOp = cast<tensor::InsertSliceOp>(op);
68449e37000SMatthias Springer     Location loc = insertSliceOp.getLoc();
6855d50f51cSMatthias Springer     FailureOr<Value> dstMemref =
6865d50f51cSMatthias Springer         getBuffer(rewriter, insertSliceOp.getDest(), options);
6875d50f51cSMatthias Springer     if (failed(dstMemref))
6885d50f51cSMatthias Springer       return failure();
68949e37000SMatthias Springer 
69049e37000SMatthias Springer     // Expand offsets, sizes and strides to the full rank to handle the
69149e37000SMatthias Springer     // rank-reducing case.
69249e37000SMatthias Springer     SmallVector<OpFoldResult> mixedOffsets = insertSliceOp.getMixedOffsets();
69349e37000SMatthias Springer     SmallVector<OpFoldResult> mixedSizes = insertSliceOp.getMixedSizes();
69449e37000SMatthias Springer     SmallVector<OpFoldResult> mixedStrides = insertSliceOp.getMixedStrides();
69549e37000SMatthias Springer     OffsetSizeAndStrideOpInterface::expandToRank(
6965d50f51cSMatthias Springer         *dstMemref, mixedOffsets, mixedSizes, mixedStrides,
69749e37000SMatthias Springer         [&](Value target, int64_t dim) -> OpFoldResult {
69849e37000SMatthias Springer           auto shapedType = target.getType().cast<ShapedType>();
69949e37000SMatthias Springer           if (shapedType.isDynamicDim(dim))
70049e37000SMatthias Springer             return rewriter.create<memref::DimOp>(loc, target, dim).result();
70149e37000SMatthias Springer           return rewriter.getIndexAttr(shapedType.getDimSize(dim));
70249e37000SMatthias Springer         });
70349e37000SMatthias Springer     // Take a subview of the dst.
7045d50f51cSMatthias Springer     auto dstMemrefType = dstMemref->getType().cast<MemRefType>();
70549e37000SMatthias Springer     auto subviewMemRefType =
70649e37000SMatthias Springer         memref::SubViewOp::inferRankReducedResultType(
70749e37000SMatthias Springer             insertSliceOp.getSourceType().getRank(), dstMemrefType,
70849e37000SMatthias Springer             mixedOffsets, mixedSizes, mixedStrides)
70949e37000SMatthias Springer             .cast<MemRefType>();
71049e37000SMatthias Springer     Value subView = rewriter.create<memref::SubViewOp>(
7115d50f51cSMatthias Springer         loc, subviewMemRefType, *dstMemref, mixedOffsets, mixedSizes,
71249e37000SMatthias Springer         mixedStrides);
71349e37000SMatthias Springer 
71449e37000SMatthias Springer     // Copy tensor. If this tensor.insert_slice has a matching
71549e37000SMatthias Springer     // tensor.extract_slice, the copy operation will eventually fold away.
7165d50f51cSMatthias Springer     FailureOr<Value> srcMemref =
7175d50f51cSMatthias Springer         getBuffer(rewriter, insertSliceOp.getSource(), options);
7185d50f51cSMatthias Springer     if (failed(srcMemref))
7195d50f51cSMatthias Springer       return failure();
7205d50f51cSMatthias Springer     if (failed(options.createMemCpy(rewriter, loc, *srcMemref, subView)))
72149e37000SMatthias Springer       return failure();
72249e37000SMatthias Springer 
7235d50f51cSMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, *dstMemref);
72449e37000SMatthias Springer     return success();
72549e37000SMatthias Springer   }
72649e37000SMatthias Springer };
72749e37000SMatthias Springer 
728fc08d1c2SMatthias Springer /// Bufferization of tensor.rank. Replace with memref.rank.
729fc08d1c2SMatthias Springer struct RankOpInterface
730fc08d1c2SMatthias Springer     : public BufferizableOpInterface::ExternalModel<RankOpInterface,
731fc08d1c2SMatthias Springer                                                     tensor::RankOp> {
732fc08d1c2SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
7339597b16aSMatthias Springer                               const AnalysisState &state) const {
734fc08d1c2SMatthias Springer     return true;
735fc08d1c2SMatthias Springer   }
736fc08d1c2SMatthias Springer 
737fc08d1c2SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
7389597b16aSMatthias Springer                                const AnalysisState &state) const {
739fc08d1c2SMatthias Springer     return false;
740fc08d1c2SMatthias Springer   }
741fc08d1c2SMatthias Springer 
7429597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
7439597b16aSMatthias Springer                                             const AnalysisState &state) const {
744585a8a32SMatthias Springer     return {};
745fc08d1c2SMatthias Springer   }
746fc08d1c2SMatthias Springer 
747fc08d1c2SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
748b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
749fc08d1c2SMatthias Springer     auto rankOp = cast<tensor::RankOp>(op);
7505d50f51cSMatthias Springer     FailureOr<Value> v = getBuffer(rewriter, rankOp.getTensor(), options);
7515d50f51cSMatthias Springer     if (failed(v))
7525d50f51cSMatthias Springer       return failure();
753fc08d1c2SMatthias Springer     replaceOpWithNewBufferizedOp<memref::RankOp>(rewriter, op, rankOp.getType(),
7545d50f51cSMatthias Springer                                                  *v);
755fc08d1c2SMatthias Springer     return success();
756fc08d1c2SMatthias Springer   }
757fc08d1c2SMatthias Springer };
758fc08d1c2SMatthias Springer 
759e287d647SAshay Rane /// Bufferization of tensor.reshape. Replace with memref.reshape.
760e287d647SAshay Rane struct ReshapeOpInterface
761e287d647SAshay Rane     : public BufferizableOpInterface::ExternalModel<ReshapeOpInterface,
762e287d647SAshay Rane                                                     tensor::ReshapeOp> {
763e287d647SAshay Rane   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
764e287d647SAshay Rane                               const AnalysisState &state) const {
765e287d647SAshay Rane     if (&opOperand == &op->getOpOperand(1) /* shape */)
766e287d647SAshay Rane       return true;
767e287d647SAshay Rane     return false;
768e287d647SAshay Rane   }
769e287d647SAshay Rane 
770e287d647SAshay Rane   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
771e287d647SAshay Rane                                const AnalysisState &state) const {
772e287d647SAshay Rane     return false;
773e287d647SAshay Rane   }
774e287d647SAshay Rane 
775e287d647SAshay Rane   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
776e287d647SAshay Rane                                             const AnalysisState &state) const {
777e287d647SAshay Rane     return {op->getOpResult(0)};
778e287d647SAshay Rane   }
779e287d647SAshay Rane 
780e287d647SAshay Rane   BufferRelation bufferRelation(Operation *op, OpResult opResult,
781e287d647SAshay Rane                                 const AnalysisState &state) const {
782e287d647SAshay Rane     return BufferRelation::Equivalent;
783e287d647SAshay Rane   }
784e287d647SAshay Rane 
785e287d647SAshay Rane   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
786b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
787e287d647SAshay Rane     auto reshapeOp = cast<tensor::ReshapeOp>(op);
7885d50f51cSMatthias Springer     FailureOr<Value> srcBuffer =
7895d50f51cSMatthias Springer         getBuffer(rewriter, reshapeOp.getSource(), options);
7905d50f51cSMatthias Springer     FailureOr<Value> shapeBuffer =
7915d50f51cSMatthias Springer         getBuffer(rewriter, reshapeOp.getShape(), options);
7925d50f51cSMatthias Springer     if (failed(srcBuffer) || failed(shapeBuffer))
7935d50f51cSMatthias Springer       return failure();
794e287d647SAshay Rane     auto resultTensorType = reshapeOp.getResult().getType().cast<TensorType>();
795b55d55ecSMatthias Springer     auto resultMemRefType = getMemRefType(resultTensorType, options);
796e287d647SAshay Rane     replaceOpWithNewBufferizedOp<memref::ReshapeOp>(
7975d50f51cSMatthias Springer         rewriter, op, resultMemRefType, *srcBuffer, *shapeBuffer);
798e287d647SAshay Rane     return success();
799e287d647SAshay Rane   }
800e287d647SAshay Rane };
801e287d647SAshay Rane 
80249e37000SMatthias Springer } // namespace
80349e37000SMatthias Springer } // namespace tensor
80449e37000SMatthias Springer } // namespace mlir
80549e37000SMatthias Springer 
80649e37000SMatthias Springer void mlir::tensor::registerBufferizableOpInterfaceExternalModels(
80749e37000SMatthias Springer     DialectRegistry &registry) {
80877eee579SRiver Riddle   registry.addExtension(+[](MLIRContext *ctx, tensor::TensorDialect *dialect) {
80977eee579SRiver Riddle     CastOp::attachInterface<CastOpInterface>(*ctx);
81077eee579SRiver Riddle     CollapseShapeOp::attachInterface<CollapseShapeOpInterface>(*ctx);
81177eee579SRiver Riddle     DimOp::attachInterface<DimOpInterface>(*ctx);
81277eee579SRiver Riddle     ExpandShapeOp::attachInterface<ExpandShapeOpInterface>(*ctx);
81377eee579SRiver Riddle     ExtractSliceOp::attachInterface<ExtractSliceOpInterface>(*ctx);
81477eee579SRiver Riddle     ExtractOp::attachInterface<ExtractOpInterface>(*ctx);
81577eee579SRiver Riddle     FromElementsOp::attachInterface<FromElementsOpInterface>(*ctx);
81677eee579SRiver Riddle     GenerateOp::attachInterface<GenerateOpInterface>(*ctx);
81777eee579SRiver Riddle     InsertOp::attachInterface<InsertOpInterface>(*ctx);
81877eee579SRiver Riddle     InsertSliceOp::attachInterface<InsertSliceOpInterface>(*ctx);
81977eee579SRiver Riddle     RankOp::attachInterface<RankOpInterface>(*ctx);
820e287d647SAshay Rane     ReshapeOp::attachInterface<ReshapeOpInterface>(*ctx);
82177eee579SRiver Riddle   });
82249e37000SMatthias Springer }
823