1 //===- BufferizableOpInterfaceImpl.cpp - Impl. of BufferizableOpInterface -===//
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/SCF/BufferizableOpInterfaceImpl.h"
10 
11 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
12 #include "mlir/Dialect/Bufferization/IR/Bufferization.h"
13 #include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h"
14 #include "mlir/Dialect/MemRef/IR/MemRef.h"
15 #include "mlir/Dialect/SCF/SCF.h"
16 #include "mlir/Dialect/Tensor/IR/Tensor.h"
17 #include "mlir/IR/Dialect.h"
18 #include "mlir/IR/Operation.h"
19 #include "mlir/IR/PatternMatch.h"
20 
21 using namespace mlir;
22 using namespace mlir::bufferization;
23 using namespace mlir::scf;
24 
25 namespace mlir {
26 namespace scf {
27 namespace {
28 
29 // bufferization.to_memref is not allowed to change the rank.
30 static void ensureToMemrefOpIsValid(Value tensor, Type memrefType) {
31 #ifndef NDEBUG
32   auto rankedTensorType = tensor.getType().dyn_cast<RankedTensorType>();
33   assert((!rankedTensorType || (memrefType.cast<MemRefType>().getRank() ==
34                                 rankedTensorType.getRank())) &&
35          "to_memref would be invalid: mismatching ranks");
36 #endif
37 }
38 
39 /// Bufferization of scf.execute_region. Can be analyzed, but bufferization not
40 /// fully implemented at the moment.
41 struct ExecuteRegionOpInterface
42     : public BufferizableOpInterface::ExternalModel<ExecuteRegionOpInterface,
43                                                     scf::ExecuteRegionOp> {
44   SmallVector<OpOperand *>
45   getAliasingOpOperand(Operation *op, OpResult opResult,
46                        const AnalysisState &state) const {
47     // ExecuteRegionOps do not have tensor OpOperands. The yielded value can be
48     // any SSA value that is in scope. To allow for use-def chain traversal
49     // through ExecuteRegionOps in the analysis, the corresponding yield value
50     // is considered to be aliasing with the result.
51     auto executeRegionOp = cast<scf::ExecuteRegionOp>(op);
52     size_t resultNum = std::distance(op->getOpResults().begin(),
53                                      llvm::find(op->getOpResults(), opResult));
54     // TODO: Support multiple blocks.
55     assert(executeRegionOp.getRegion().getBlocks().size() == 1 &&
56            "expected exactly 1 block");
57     auto yieldOp = dyn_cast<scf::YieldOp>(
58         executeRegionOp.getRegion().front().getTerminator());
59     assert(yieldOp && "expected scf.yield terminator in scf.execute_region");
60     return {&yieldOp->getOpOperand(resultNum)};
61   }
62 
63   // TODO: For better bufferization results, this could return `true` only if
64   // there is a memory write in the region.
65   bool isMemoryWrite(Operation *op, OpResult opResult,
66                      const AnalysisState &state) const {
67     // Similar to scf.if, results of this op are always considered memory writes
68     // in the analysis. This is a useful pattern for all ops that have tensor
69     // OpResults but no tensor OpOperands. By default, `isMemoryWrite` is
70     // implemented in terms of `bufferizesToMemoryWrite`, which does not work on
71     // ops without OpOperands.
72     return true;
73   }
74 
75   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
76                           BufferizationState &state) const {
77     auto executeRegionOp = cast<scf::ExecuteRegionOp>(op);
78 
79     // Compute new result types.
80     SmallVector<Type> newResultTypes;
81     for (Type type : executeRegionOp->getResultTypes()) {
82       if (auto tensorType = type.dyn_cast<TensorType>()) {
83         // TODO: Infer the result type instead of computing it.
84         newResultTypes.push_back(getMemRefType(tensorType, state.getOptions()));
85       } else {
86         newResultTypes.push_back(type);
87       }
88     }
89 
90     // Create new op and move over region.
91     auto newOp =
92         rewriter.create<scf::ExecuteRegionOp>(op->getLoc(), newResultTypes);
93     newOp.getRegion().takeBody(executeRegionOp.getRegion());
94 
95     // Update terminator.
96     assert(newOp.getRegion().getBlocks().size() == 1 &&
97            "only 1 block supported");
98     Block *newBlock = &newOp.getRegion().front();
99     auto yieldOp = cast<scf::YieldOp>(newBlock->getTerminator());
100     rewriter.setInsertionPoint(yieldOp);
101     SmallVector<Value> newYieldValues;
102     for (const auto &it : llvm::enumerate(yieldOp.getResults())) {
103       Value val = it.value();
104       if (val.getType().isa<TensorType>()) {
105         newYieldValues.push_back(rewriter.create<bufferization::ToMemrefOp>(
106             yieldOp.getLoc(), newResultTypes[it.index()], val));
107       } else {
108         newYieldValues.push_back(val);
109       }
110     }
111     rewriter.replaceOpWithNewOp<scf::YieldOp>(yieldOp, newYieldValues);
112 
113     // Update all uses of the old op.
114     rewriter.setInsertionPointAfter(newOp);
115     SmallVector<Value> newResults;
116     for (const auto &it : llvm::enumerate(executeRegionOp->getResultTypes())) {
117       if (it.value().isa<TensorType>()) {
118         newResults.push_back(rewriter.create<bufferization::ToTensorOp>(
119             executeRegionOp.getLoc(), newOp->getResult(it.index())));
120       } else {
121         newResults.push_back(newOp->getResult(it.index()));
122       }
123     }
124 
125     // Replace old op.
126     rewriter.replaceOp(executeRegionOp, newResults);
127 
128     return success();
129   }
130 
131   BufferRelation bufferRelation(Operation *op, OpResult opResult,
132                                 const AnalysisState &state) const {
133     return BufferRelation::Equivalent;
134   }
135 };
136 
137 /// Bufferization of scf.if. Replace with a new scf.if that yields memrefs.
138 struct IfOpInterface
139     : public BufferizableOpInterface::ExternalModel<IfOpInterface, scf::IfOp> {
140   SmallVector<OpOperand *>
141   getAliasingOpOperand(Operation *op, OpResult opResult,
142                        const AnalysisState &state) const {
143     // IfOps do not have tensor OpOperands. The yielded value can be any SSA
144     // value that is in scope. To allow for use-def chain traversal through
145     // IfOps in the analysis, both corresponding yield values from the then/else
146     // branches are considered to be aliasing with the result.
147     auto ifOp = cast<scf::IfOp>(op);
148     size_t resultNum = std::distance(op->getOpResults().begin(),
149                                      llvm::find(op->getOpResults(), opResult));
150     return {&ifOp.thenYield()->getOpOperand(resultNum),
151             &ifOp.elseYield()->getOpOperand(resultNum)};
152   }
153 
154   // TODO: For better bufferization results, this could return `true` only if
155   // there is a memory write in one (or both) of the branches. Since this is not
156   // allowed at the moment, we should never encounter scf.ifs that yield
157   // unmodified tensors. Such scf.yield ops could just fold away.
158   bool isMemoryWrite(Operation *op, OpResult opResult,
159                      const AnalysisState &state) const {
160     // IfOp results are always considered memory writes in the analysis. This
161     // design decision simplifies the analysis considerably. E.g., consider the
162     // following test case:
163     //
164     // %0 = "some_writing_op" : tensor<?xf32>
165     // %r = scf.if %c -> (tensor<?xf32>) {
166     //   scf.yield %0
167     // } else {
168     //   %1 = "another_writing_op"(%0) : tensor<?xf32>
169     // }
170     // "some_reading_op"(%r)
171     //
172     // "another_writing_op" in the above example should be able to bufferize
173     // inplace in the absence of another read of %0. However, if the scf.if op
174     // would not be considered a "write", the analysis would detect the
175     // following conflict:
176     //
177     // * read = some_reading_op
178     // * lastWrite = %0  (Note: The last write of %r would be a set: {%0, %1}.)
179     // * conflictingWrite = %1
180     //
181     // For more details, check the "scf.IfOp" section of the design document.
182     return true;
183   }
184 
185   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
186                           BufferizationState &state) const {
187     auto ifOp = cast<scf::IfOp>(op);
188 
189     // Compute new types of the bufferized scf.if op.
190     SmallVector<Type> newTypes;
191     for (Type returnType : ifOp->getResultTypes()) {
192       if (auto tensorType = returnType.dyn_cast<TensorType>()) {
193         // TODO: Infer the result type instead of computing it.
194         newTypes.push_back(getMemRefType(tensorType, state.getOptions()));
195       } else {
196         newTypes.push_back(returnType);
197       }
198     }
199 
200     // Create new op.
201     auto newIfOp =
202         rewriter.create<scf::IfOp>(ifOp.getLoc(), newTypes, ifOp.getCondition(),
203                                    /*withElseRegion=*/true);
204 
205     // Remove terminators.
206     if (!newIfOp.thenBlock()->empty()) {
207       rewriter.eraseOp(newIfOp.thenBlock()->getTerminator());
208       rewriter.eraseOp(newIfOp.elseBlock()->getTerminator());
209     }
210 
211     // Move over then/else blocks.
212     rewriter.mergeBlocks(ifOp.thenBlock(), newIfOp.thenBlock());
213     rewriter.mergeBlocks(ifOp.elseBlock(), newIfOp.elseBlock());
214 
215     // Update scf.yield of new then-block.
216     auto thenYieldOp = cast<scf::YieldOp>(newIfOp.thenBlock()->getTerminator());
217     rewriter.setInsertionPoint(thenYieldOp);
218     SmallVector<Value> thenYieldValues;
219     for (OpOperand &operand : thenYieldOp->getOpOperands()) {
220       if (operand.get().getType().isa<TensorType>()) {
221         ensureToMemrefOpIsValid(operand.get(),
222                                 newTypes[operand.getOperandNumber()]);
223         Value toMemrefOp = rewriter.create<bufferization::ToMemrefOp>(
224             operand.get().getLoc(), newTypes[operand.getOperandNumber()],
225             operand.get());
226         operand.set(toMemrefOp);
227       }
228     }
229 
230     // Update scf.yield of new else-block.
231     auto elseYieldOp = cast<scf::YieldOp>(newIfOp.elseBlock()->getTerminator());
232     rewriter.setInsertionPoint(elseYieldOp);
233     SmallVector<Value> elseYieldValues;
234     for (OpOperand &operand : elseYieldOp->getOpOperands()) {
235       if (operand.get().getType().isa<TensorType>()) {
236         ensureToMemrefOpIsValid(operand.get(),
237                                 newTypes[operand.getOperandNumber()]);
238         Value toMemrefOp = rewriter.create<bufferization::ToMemrefOp>(
239             operand.get().getLoc(), newTypes[operand.getOperandNumber()],
240             operand.get());
241         operand.set(toMemrefOp);
242       }
243     }
244 
245     // Replace op results.
246     replaceOpWithBufferizedValues(rewriter, op, newIfOp->getResults());
247 
248     return success();
249   }
250 
251   BufferRelation bufferRelation(Operation *op, OpResult opResult,
252                                 const AnalysisState &state) const {
253     // IfOp results are equivalent to their corresponding yield values if both
254     // yield values are equivalent to each other.
255     auto bufferizableOp = cast<BufferizableOpInterface>(op);
256     SmallVector<OpOperand *> yieldValues =
257         bufferizableOp.getAliasingOpOperand(opResult, state);
258     assert(yieldValues.size() == 2 && "expected 2 yield values");
259     bool equivalentYields = state.areEquivalentBufferizedValues(
260         yieldValues[0]->get(), yieldValues[1]->get());
261     return equivalentYields ? BufferRelation::Equivalent : BufferRelation::None;
262   }
263 };
264 
265 /// Helper function for loop bufferization. Return the indices of all values
266 /// that have a tensor type.
267 static DenseSet<int64_t> getTensorIndices(ValueRange values) {
268   DenseSet<int64_t> result;
269   for (const auto &it : llvm::enumerate(values))
270     if (it.value().getType().isa<TensorType>())
271       result.insert(it.index());
272   return result;
273 }
274 
275 /// Helper function for loop bufferization. Return the indices of all
276 /// bbArg/yielded value pairs who's buffer relation is "Equivalent".
277 DenseSet<int64_t> getEquivalentBuffers(Block::BlockArgListType bbArgs,
278                                        ValueRange yieldedValues,
279                                        const AnalysisState &state) {
280   unsigned int minSize = std::min(bbArgs.size(), yieldedValues.size());
281   DenseSet<int64_t> result;
282   for (unsigned int i = 0; i < minSize; ++i) {
283     if (!bbArgs[i].getType().isa<TensorType>() ||
284         !yieldedValues[i].getType().isa<TensorType>())
285       continue;
286     if (state.areEquivalentBufferizedValues(bbArgs[i], yieldedValues[i]))
287       result.insert(i);
288   }
289   return result;
290 }
291 
292 /// Helper function for loop bufferization. Cast the given buffer to the given
293 /// memref type.
294 static Value castBuffer(OpBuilder &b, Value buffer, Type type) {
295   assert(type.isa<BaseMemRefType>() && "expected BaseMemRefType");
296   assert(buffer.getType().isa<BaseMemRefType>() && "expected BaseMemRefType");
297   // If the buffer already has the correct type, no cast is needed.
298   if (buffer.getType() == type)
299     return buffer;
300   // TODO: In case `type` has a layout map that is not the fully dynamic
301   // one, we may not be able to cast the buffer. In that case, the loop
302   // iter_arg's layout map must be changed (see uses of `castBuffer`).
303   assert(memref::CastOp::areCastCompatible(buffer.getType(), type) &&
304          "scf.while op bufferization: cast incompatible");
305   return b.create<memref::CastOp>(buffer.getLoc(), type, buffer).getResult();
306 }
307 
308 /// Helper function for loop bufferization. Return the bufferized values of the
309 /// given OpOperands. If an operand is not a tensor, return the original value.
310 static SmallVector<Value> getBuffers(RewriterBase &rewriter,
311                                      MutableArrayRef<OpOperand> operands,
312                                      BufferizationState &state) {
313   SmallVector<Value> result;
314   for (OpOperand &opOperand : operands) {
315     if (opOperand.get().getType().isa<TensorType>()) {
316       Value resultBuffer = state.getBuffer(rewriter, opOperand.get());
317       result.push_back(resultBuffer);
318     } else {
319       result.push_back(opOperand.get());
320     }
321   }
322   return result;
323 }
324 
325 /// Helper function for loop bufferization. Compute the buffer that should be
326 /// yielded from a loop block (loop body or loop condition).
327 static Value getYieldedBuffer(RewriterBase &rewriter, Value tensor,
328                               BaseMemRefType type, BufferizationState &state) {
329   assert(tensor.getType().isa<TensorType>() && "expected tensor");
330   ensureToMemrefOpIsValid(tensor, type);
331   Value yieldedVal = state.getBuffer(rewriter, tensor);
332   return castBuffer(rewriter, yieldedVal, type);
333 }
334 
335 /// Helper function for loop bufferization. Given a range of values, apply
336 /// `func` to those marked in `tensorIndices`. Otherwise, store the unmodified
337 /// value in the result vector.
338 static SmallVector<Value>
339 convertTensorValues(ValueRange values, const DenseSet<int64_t> &tensorIndices,
340                     llvm::function_ref<Value(Value, int64_t)> func) {
341   SmallVector<Value> result;
342   for (const auto &it : llvm::enumerate(values)) {
343     size_t idx = it.index();
344     Value val = it.value();
345     result.push_back(tensorIndices.contains(idx) ? func(val, idx) : val);
346   }
347   return result;
348 }
349 
350 /// Helper function for loop bufferization. Given a list of pre-bufferization
351 /// yielded values, compute the list of bufferized yielded values.
352 SmallVector<Value> getYieldedValues(RewriterBase &rewriter, ValueRange values,
353                                     TypeRange bufferizedTypes,
354                                     const DenseSet<int64_t> &tensorIndices,
355                                     BufferizationState &state) {
356   return convertTensorValues(
357       values, tensorIndices, [&](Value val, int64_t index) {
358         return getYieldedBuffer(rewriter, val,
359                                 bufferizedTypes[index].cast<BaseMemRefType>(),
360                                 state);
361       });
362 }
363 
364 /// Helper function for loop bufferization. Given a list of bbArgs of the new
365 /// (bufferized) loop op, wrap the bufferized tensor args (now memrefs) into
366 /// ToTensorOps, so that the block body can be moved over to the new op.
367 SmallVector<Value>
368 getBbArgReplacements(RewriterBase &rewriter, Block::BlockArgListType bbArgs,
369                      const DenseSet<int64_t> &tensorIndices) {
370   return convertTensorValues(
371       bbArgs, tensorIndices, [&](Value val, int64_t index) {
372         return rewriter.create<bufferization::ToTensorOp>(val.getLoc(), val);
373       });
374 }
375 
376 /// Bufferization of scf.for. Replace with a new scf.for that operates on
377 /// memrefs.
378 struct ForOpInterface
379     : public BufferizableOpInterface::ExternalModel<ForOpInterface,
380                                                     scf::ForOp> {
381   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
382                               const AnalysisState &state) const {
383     // scf::ForOp alone doesn't bufferize to a memory read, one of the uses of
384     // its matching bbArg may.
385     auto forOp = cast<scf::ForOp>(op);
386     return state.isValueRead(forOp.getRegionIterArgForOpOperand(opOperand));
387   }
388 
389   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
390                                const AnalysisState &state) const {
391     // Tensor iter_args of scf::ForOps are always considered as a write.
392     return true;
393   }
394 
395   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
396                                             const AnalysisState &state) const {
397     auto forOp = cast<scf::ForOp>(op);
398     return {forOp.getResultForOpOperand(opOperand)};
399   }
400 
401   BufferRelation bufferRelation(Operation *op, OpResult opResult,
402                                 const AnalysisState &state) const {
403     // ForOp results are equivalent to their corresponding init_args if the
404     // corresponding iter_args and yield values are equivalent.
405     auto forOp = cast<scf::ForOp>(op);
406     OpOperand &forOperand = forOp.getOpOperandForResult(opResult);
407     auto bbArg = forOp.getRegionIterArgForOpOperand(forOperand);
408     auto yieldOp =
409         cast<scf::YieldOp>(forOp.getLoopBody().front().getTerminator());
410     bool equivalentYield = state.areEquivalentBufferizedValues(
411         bbArg, yieldOp->getOperand(opResult.getResultNumber()));
412     return equivalentYield ? BufferRelation::Equivalent : BufferRelation::None;
413   }
414 
415   bool isWritable(Operation *op, Value value,
416                   const AnalysisState &state) const {
417     // Interestingly, scf::ForOp's bbArg can **always** be viewed
418     // inplace from the perspective of ops nested under:
419     //   1. Either the matching iter operand is not bufferized inplace and an
420     //      alloc + optional copy makes the bbArg itself inplaceable.
421     //   2. Or the matching iter operand is bufferized inplace and bbArg just
422     //      bufferizes to that too.
423     return true;
424   }
425 
426   LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter,
427                                  const AnalysisState &state) const {
428     auto bufferizableOp = cast<BufferizableOpInterface>(op);
429     if (failed(bufferizableOp.resolveTensorOpOperandConflicts(rewriter, state)))
430       return failure();
431 
432     if (!state.getOptions().enforceAliasingInvariants)
433       return success();
434 
435     // According to the `getAliasing...` implementations, a bufferized OpResult
436     // may alias only with the corresponding bufferized init_arg and with no
437     // other buffers. I.e., the i-th OpResult may alias with the i-th init_arg;
438     // but not with any other OpOperand. If a corresponding OpResult/init_arg
439     // pair bufferizes to equivalent buffers, this aliasing requirement is
440     // satisfied. Otherwise, we cannot be sure and must yield a new buffer copy.
441     // (New buffer copies do not alias with any buffer.)
442     auto forOp = cast<scf::ForOp>(op);
443     auto yieldOp =
444         cast<scf::YieldOp>(forOp.getLoopBody().front().getTerminator());
445     OpBuilder::InsertionGuard g(rewriter);
446     rewriter.setInsertionPoint(yieldOp);
447 
448     // Indices of all iter_args that have tensor type. These are the ones that
449     // are bufferized.
450     DenseSet<int64_t> indices = getTensorIndices(forOp.getInitArgs());
451     // For every yielded value, is the value equivalent to its corresponding
452     // bbArg?
453     DenseSet<int64_t> equivalentYields = getEquivalentBuffers(
454         forOp.getRegionIterArgs(), yieldOp.getResults(), state);
455     SmallVector<Value> yieldValues;
456     for (int64_t idx = 0;
457          idx < static_cast<int64_t>(yieldOp.getResults().size()); ++idx) {
458       Value value = yieldOp.getResults()[idx];
459       if (!indices.contains(idx) || equivalentYields.contains(idx)) {
460         yieldValues.push_back(value);
461         continue;
462       }
463       Value alloc = rewriter.create<bufferization::AllocTensorOp>(
464           yieldOp.getLoc(), value.getType().cast<RankedTensorType>(),
465           /*dynamicSizes=*/ValueRange(), value, /*escape=*/true);
466       yieldValues.push_back(alloc);
467     }
468 
469     rewriter.updateRootInPlace(
470         yieldOp, [&]() { yieldOp.getResultsMutable().assign(yieldValues); });
471     return success();
472   }
473 
474   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
475                           BufferizationState &state) const {
476     auto forOp = cast<scf::ForOp>(op);
477     Block *oldLoopBody = &forOp.getLoopBody().front();
478 
479     // Indices of all iter_args that have tensor type. These are the ones that
480     // are bufferized.
481     DenseSet<int64_t> indices = getTensorIndices(forOp.getInitArgs());
482 
483     // The new memref init_args of the loop.
484     SmallVector<Value> initArgs =
485         getBuffers(rewriter, forOp.getIterOpOperands(), state);
486 
487     // Construct a new scf.for op with memref instead of tensor values.
488     auto newForOp = rewriter.create<scf::ForOp>(
489         forOp.getLoc(), forOp.getLowerBound(), forOp.getUpperBound(),
490         forOp.getStep(), initArgs);
491     newForOp->setAttrs(forOp->getAttrs());
492     ValueRange initArgsRange(initArgs);
493     TypeRange initArgsTypes(initArgsRange);
494     Block *loopBody = &newForOp.getLoopBody().front();
495 
496     // Set up new iter_args. The loop body uses tensors, so wrap the (memref)
497     // iter_args of the new loop in ToTensorOps.
498     rewriter.setInsertionPointToStart(loopBody);
499     SmallVector<Value> iterArgs =
500         getBbArgReplacements(rewriter, newForOp.getRegionIterArgs(), indices);
501     iterArgs.insert(iterArgs.begin(), newForOp.getInductionVar());
502 
503     // Erase terminator if present.
504     if (iterArgs.size() == 1)
505       rewriter.eraseOp(loopBody->getTerminator());
506 
507     // Move loop body to new loop.
508     rewriter.mergeBlocks(oldLoopBody, loopBody, iterArgs);
509 
510     // Update scf.yield of new loop.
511     auto yieldOp = cast<scf::YieldOp>(loopBody->getTerminator());
512     rewriter.setInsertionPoint(yieldOp);
513     SmallVector<Value> yieldValues = getYieldedValues(
514         rewriter, yieldOp.getResults(), initArgsTypes, indices, state);
515     yieldOp.getResultsMutable().assign(yieldValues);
516 
517     // Replace loop results.
518     replaceOpWithBufferizedValues(rewriter, op, newForOp->getResults());
519 
520     return success();
521   }
522 
523   /// Assert that yielded values of an scf.for op are equivalent to their
524   /// corresponding bbArgs. In that case, the buffer relations of the
525   /// corresponding OpResults are "Equivalent".
526   ///
527   /// If this is not the case, an allocs+copies are inserted and yielded from
528   /// the loop. This could be a performance problem, so it must be explicitly
529   /// activated with `alloc-return-allocs`.
530   LogicalResult verifyAnalysis(Operation *op,
531                                const AnalysisState &state) const {
532     const auto &options =
533         static_cast<const OneShotBufferizationOptions &>(state.getOptions());
534     if (options.allowReturnAllocs)
535       return success();
536 
537     auto forOp = cast<scf::ForOp>(op);
538     auto yieldOp =
539         cast<scf::YieldOp>(forOp.getLoopBody().front().getTerminator());
540     for (OpResult opResult : op->getOpResults()) {
541       if (!opResult.getType().isa<TensorType>())
542         continue;
543 
544       // Note: This is overly strict. We should check for aliasing bufferized
545       // values. But we don't have a "must-alias" analysis yet.
546       if (bufferRelation(op, opResult, state) != BufferRelation::Equivalent)
547         return yieldOp->emitError()
548                << "Yield operand #" << opResult.getResultNumber()
549                << " is not equivalent to the corresponding iter bbArg";
550     }
551 
552     return success();
553   }
554 };
555 
556 /// Bufferization of scf.while. Replace with a new scf.while that operates on
557 /// memrefs.
558 struct WhileOpInterface
559     : public BufferizableOpInterface::ExternalModel<WhileOpInterface,
560                                                     scf::WhileOp> {
561   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
562                               const AnalysisState &state) const {
563     // Tensor iter_args of scf::WhileOps are always considered as a read.
564     return true;
565   }
566 
567   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
568                                const AnalysisState &state) const {
569     // Tensor iter_args of scf::WhileOps are always considered as a write.
570     return true;
571   }
572 
573   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
574                                             const AnalysisState &state) const {
575     auto whileOp = cast<scf::WhileOp>(op);
576     unsigned int idx = opOperand.getOperandNumber();
577 
578     // The OpResults and OpOperands may not match. They may not even have the
579     // same type. The number of OpResults and OpOperands can also differ.
580     if (idx >= op->getNumResults() ||
581         opOperand.get().getType() != op->getResult(idx).getType())
582       return {};
583 
584     // The only aliasing OpResult may be the one at the same index.
585     return {whileOp->getResult(idx)};
586   }
587 
588   BufferRelation bufferRelation(Operation *op, OpResult opResult,
589                                 const AnalysisState &state) const {
590     // WhileOp results are equivalent to their corresponding init_args if the
591     // corresponding iter_args and yield values are equivalent (for both the
592     // "before" and the "after" block).
593     unsigned int resultNumber = opResult.getResultNumber();
594     auto whileOp = cast<scf::WhileOp>(op);
595 
596     // The "before" region bbArgs and the OpResults may not match.
597     if (resultNumber >= whileOp.getBeforeArguments().size())
598       return BufferRelation::None;
599     if (opResult.getType() !=
600         whileOp.getBeforeArguments()[resultNumber].getType())
601       return BufferRelation::None;
602 
603     auto conditionOp = whileOp.getConditionOp();
604     BlockArgument conditionBbArg = whileOp.getBeforeArguments()[resultNumber];
605     Value conditionOperand = conditionOp.getArgs()[resultNumber];
606     bool equivCondition =
607         state.areEquivalentBufferizedValues(conditionBbArg, conditionOperand);
608 
609     auto yieldOp = whileOp.getYieldOp();
610     BlockArgument bodyBbArg = whileOp.getAfterArguments()[resultNumber];
611     Value yieldOperand = yieldOp.getOperand(resultNumber);
612     bool equivYield =
613         state.areEquivalentBufferizedValues(bodyBbArg, yieldOperand);
614 
615     return equivCondition && equivYield ? BufferRelation::Equivalent
616                                         : BufferRelation::None;
617   }
618 
619   bool isWritable(Operation *op, Value value,
620                   const AnalysisState &state) const {
621     // Interestingly, scf::WhileOp's bbArg can **always** be viewed
622     // inplace from the perspective of ops nested under:
623     //   1. Either the matching iter operand is not bufferized inplace and an
624     //      alloc + optional copy makes the bbArg itself inplaceable.
625     //   2. Or the matching iter operand is bufferized inplace and bbArg just
626     //      bufferizes to that too.
627     return true;
628   }
629 
630   LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter,
631                                  const AnalysisState &state) const {
632     auto bufferizableOp = cast<BufferizableOpInterface>(op);
633     if (failed(bufferizableOp.resolveTensorOpOperandConflicts(rewriter, state)))
634       return failure();
635 
636     if (!state.getOptions().enforceAliasingInvariants)
637       return success();
638 
639     // According to the `getAliasing...` implementations, a bufferized OpResult
640     // may alias only with the corresponding bufferized init_arg and with no
641     // other buffers. I.e., the i-th OpResult may alias with the i-th init_arg;
642     // but not with any other OpOperand. If a corresponding OpResult/init_arg
643     // pair bufferizes to equivalent buffers, this aliasing requirement is
644     // satisfied. Otherwise, we cannot be sure and must yield a new buffer copy.
645     // (New buffer copies do not alias with any buffer.)
646     OpBuilder::InsertionGuard g(rewriter);
647     auto whileOp = cast<scf::WhileOp>(op);
648     auto conditionOp = whileOp.getConditionOp();
649     auto yieldOp = whileOp.getYieldOp();
650 
651     // Indices of all bbArgs that have tensor type. These are the ones that
652     // are bufferized. The "before" and "after" regions may have different args.
653     DenseSet<int64_t> indicesBefore = getTensorIndices(whileOp.getInits());
654     DenseSet<int64_t> indicesAfter =
655         getTensorIndices(whileOp.getAfterArguments());
656 
657     // For every yielded value, is the value equivalent to its corresponding
658     // bbArg?
659     DenseSet<int64_t> equivalentYieldsBefore = getEquivalentBuffers(
660         whileOp.getBeforeArguments(), conditionOp.getArgs(), state);
661     DenseSet<int64_t> equivalentYieldsAfter = getEquivalentBuffers(
662         whileOp.getAfterArguments(), whileOp.getYieldOp().getResults(), state);
663 
664     // Update "before" region.
665     rewriter.setInsertionPoint(conditionOp);
666     SmallVector<Value> beforeYieldValues;
667     for (int64_t idx = 0;
668          idx < static_cast<int64_t>(conditionOp.getArgs().size()); ++idx) {
669       Value value = conditionOp.getArgs()[idx];
670       if (!indicesBefore.contains(idx) ||
671           equivalentYieldsBefore.contains(idx)) {
672         beforeYieldValues.push_back(value);
673         continue;
674       }
675       Value alloc = rewriter.create<bufferization::AllocTensorOp>(
676           conditionOp.getLoc(), value.getType().cast<RankedTensorType>(),
677           /*dynamicSizes=*/ValueRange(), value, /*escape=*/true);
678       beforeYieldValues.push_back(alloc);
679     }
680     rewriter.updateRootInPlace(conditionOp, [&]() {
681       conditionOp.getArgsMutable().assign(beforeYieldValues);
682     });
683 
684     // Update "after" region.
685     rewriter.setInsertionPoint(yieldOp);
686     SmallVector<Value> afterYieldValues;
687     for (int64_t idx = 0;
688          idx < static_cast<int64_t>(yieldOp.getResults().size()); ++idx) {
689       Value value = yieldOp.getResults()[idx];
690       if (!indicesAfter.contains(idx) || equivalentYieldsAfter.contains(idx)) {
691         afterYieldValues.push_back(value);
692         continue;
693       }
694       Value alloc = rewriter.create<bufferization::AllocTensorOp>(
695           yieldOp.getLoc(), value.getType().cast<RankedTensorType>(),
696           /*dynamicSizes=*/ValueRange(), value, /*escape=*/true);
697       afterYieldValues.push_back(alloc);
698     }
699     rewriter.updateRootInPlace(yieldOp, [&]() {
700       yieldOp.getResultsMutable().assign(afterYieldValues);
701     });
702 
703     return success();
704   }
705 
706   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
707                           BufferizationState &state) const {
708     auto whileOp = cast<scf::WhileOp>(op);
709 
710     assert(whileOp.getBefore().getBlocks().size() == 1 &&
711            "regions with multiple blocks not supported");
712     Block *beforeBody = &whileOp.getBefore().front();
713     assert(whileOp.getAfter().getBlocks().size() == 1 &&
714            "regions with multiple blocks not supported");
715     Block *afterBody = &whileOp.getAfter().front();
716 
717     // Indices of all bbArgs that have tensor type. These are the ones that
718     // are bufferized. The "before" and "after" regions may have different args.
719     DenseSet<int64_t> indicesBefore = getTensorIndices(whileOp.getInits());
720     DenseSet<int64_t> indicesAfter =
721         getTensorIndices(whileOp.getAfterArguments());
722 
723     // The new memref init_args of the loop.
724     SmallVector<Value> initArgs =
725         getBuffers(rewriter, whileOp->getOpOperands(), state);
726 
727     // The result types of a WhileOp are the same as the "after" bbArg types.
728     SmallVector<Type> argsTypesAfter = llvm::to_vector(
729         llvm::map_range(whileOp.getAfterArguments(), [&](BlockArgument bbArg) {
730           return state.getBufferType(bbArg).cast<Type>();
731         }));
732 
733     // Construct a new scf.while op with memref instead of tensor values.
734     ValueRange argsRangeBefore(initArgs);
735     TypeRange argsTypesBefore(argsRangeBefore);
736     auto newWhileOp = rewriter.create<scf::WhileOp>(whileOp.getLoc(),
737                                                     argsTypesAfter, initArgs);
738 
739     // Add before/after regions to the new op.
740     SmallVector<Location> bbArgLocsBefore(initArgs.size(), whileOp.getLoc());
741     SmallVector<Location> bbArgLocsAfter(argsTypesAfter.size(),
742                                          whileOp.getLoc());
743     Block *newBeforeBody = &newWhileOp.getBefore().emplaceBlock();
744     newWhileOp.getBefore().addArguments(argsTypesBefore, bbArgLocsBefore);
745     Block *newAfterBody = &newWhileOp.getAfter().emplaceBlock();
746     newWhileOp.getAfter().addArguments(argsTypesAfter, bbArgLocsAfter);
747 
748     // Set up new iter_args and move the loop condition block to the new op.
749     // The old block uses tensors, so wrap the (memref) bbArgs of the new block
750     // in ToTensorOps.
751     rewriter.setInsertionPointToStart(newBeforeBody);
752     SmallVector<Value> newBeforeArgs = getBbArgReplacements(
753         rewriter, newWhileOp.getBeforeArguments(), indicesBefore);
754     rewriter.mergeBlocks(beforeBody, newBeforeBody, newBeforeArgs);
755 
756     // Update scf.condition of new loop.
757     auto newConditionOp = newWhileOp.getConditionOp();
758     rewriter.setInsertionPoint(newConditionOp);
759     // Only equivalent buffers or new buffer allocations may be yielded to the
760     // "after" region.
761     // TODO: This could be relaxed for better bufferization results.
762     SmallVector<Value> newConditionArgs =
763         getYieldedValues(rewriter, newConditionOp.getArgs(), argsTypesAfter,
764                          indicesAfter, state);
765     newConditionOp.getArgsMutable().assign(newConditionArgs);
766 
767     // Set up new iter_args and move the loop body block to the new op.
768     // The old block uses tensors, so wrap the (memref) bbArgs of the new block
769     // in ToTensorOps.
770     rewriter.setInsertionPointToStart(newAfterBody);
771     SmallVector<Value> newAfterArgs = getBbArgReplacements(
772         rewriter, newWhileOp.getAfterArguments(), indicesAfter);
773     rewriter.mergeBlocks(afterBody, newAfterBody, newAfterArgs);
774 
775     // Update scf.yield of the new loop.
776     auto newYieldOp = newWhileOp.getYieldOp();
777     rewriter.setInsertionPoint(newYieldOp);
778     // Only equivalent buffers or new buffer allocations may be yielded to the
779     // "before" region.
780     // TODO: This could be relaxed for better bufferization results.
781     SmallVector<Value> newYieldValues =
782         getYieldedValues(rewriter, newYieldOp.getResults(), argsTypesBefore,
783                          indicesBefore, state);
784     newYieldOp.getResultsMutable().assign(newYieldValues);
785 
786     // Replace loop results.
787     replaceOpWithBufferizedValues(rewriter, op, newWhileOp->getResults());
788 
789     return success();
790   }
791 
792   /// Assert that yielded values of an scf.while op are equivalent to their
793   /// corresponding bbArgs. In that case, the buffer relations of the
794   /// corresponding OpResults are "Equivalent".
795   ///
796   /// If this is not the case, allocs+copies are inserted and yielded from
797   /// the loop. This could be a performance problem, so it must be explicitly
798   /// activated with `alloc-return-allocs`.
799   ///
800   /// Not: In contrast to scf::ForOp, scf::WhileOp has two regions and the
801   /// equivalence condition must be checked for both.
802   LogicalResult verifyAnalysis(Operation *op,
803                                const AnalysisState &state) const {
804     auto whileOp = cast<scf::WhileOp>(op);
805     const auto &options =
806         static_cast<const OneShotBufferizationOptions &>(state.getOptions());
807     if (options.allowReturnAllocs)
808       return success();
809 
810     auto conditionOp = whileOp.getConditionOp();
811     for (const auto &it : llvm::enumerate(conditionOp.getArgs())) {
812       if (!it.value().getType().isa<TensorType>())
813         continue;
814       if (!state.areEquivalentBufferizedValues(
815               it.value(), conditionOp->getBlock()->getArgument(it.index())))
816         return conditionOp->emitError()
817                << "Condition arg #" << it.index()
818                << " is not equivalent to the corresponding iter bbArg";
819     }
820 
821     auto yieldOp = whileOp.getYieldOp();
822     for (const auto &it : llvm::enumerate(yieldOp.getResults())) {
823       if (!it.value().getType().isa<TensorType>())
824         continue;
825       if (!state.areEquivalentBufferizedValues(
826               it.value(), yieldOp->getBlock()->getArgument(it.index())))
827         return yieldOp->emitError()
828                << "Yield operand #" << it.index()
829                << " is not equivalent to the corresponding iter bbArg";
830     }
831 
832     return success();
833   }
834 };
835 
836 /// Bufferization of scf.yield. Bufferized as part of their enclosing ops, so
837 /// this is for analysis only.
838 struct YieldOpInterface
839     : public BufferizableOpInterface::ExternalModel<YieldOpInterface,
840                                                     scf::YieldOp> {
841   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
842                               const AnalysisState &state) const {
843     return true;
844   }
845 
846   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
847                                const AnalysisState &state) const {
848     return false;
849   }
850 
851   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
852                                             const AnalysisState &state) const {
853     if (isa<scf::IfOp>(op->getParentOp()))
854       return {op->getParentOp()->getResult(opOperand.getOperandNumber())};
855     if (isa<scf::ExecuteRegionOp>(op->getParentOp()))
856       return {op->getParentOp()->getResult(opOperand.getOperandNumber())};
857     return {};
858   }
859 
860   bool mustBufferizeInPlace(Operation *op, OpOperand &opOperand,
861                             const AnalysisState &state) const {
862     // Yield operands always bufferize inplace. Otherwise, an alloc + copy
863     // may be generated inside the block. We should not return/yield allocations
864     // when possible.
865     return true;
866   }
867 
868   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
869                           BufferizationState &state) const {
870     auto yieldOp = cast<scf::YieldOp>(op);
871     if (!isa<scf::ExecuteRegionOp, scf::IfOp, scf::ForOp, scf::WhileOp>(
872             yieldOp->getParentOp()))
873       return yieldOp->emitError("unsupported scf::YieldOp parent");
874     return success();
875   }
876 };
877 
878 using tensor::ExtractSliceOp;
879 
880 /// Return the destinations that an ForeachThreadOp is inserting into. One per
881 /// ParallelInsertSliceOp.
882 static SmallVector<OpOperand *>
883 getInsertionDest(ForeachThreadOp foreachThreadOp) {
884   PerformConcurrentlyOp terminator = foreachThreadOp.getTerminator();
885   SmallVector<OpOperand *> result;
886   terminator.walk([&](ParallelInsertSliceOp insertOp) {
887     result.push_back(&insertOp->getOpOperand(1) /*dest*/);
888   });
889   return result;
890 }
891 
892 /// Bufferization of ForeachThreadOp. This also bufferizes the terminator of the
893 /// region. There are op interfaces for the terminators (PerformConcurrentlyOp
894 /// and ParallelInsertSliceOp), but these are only used during analysis. Not
895 /// for bufferization.
896 struct ForeachThreadOpInterface
897     : public BufferizableOpInterface::ExternalModel<ForeachThreadOpInterface,
898                                                     ForeachThreadOp> {
899   SmallVector<OpOperand *>
900   getAliasingOpOperand(Operation *op, OpResult opResult,
901                        const AnalysisState &state) const {
902     // Get OpOperand (dest) from corresponding ParallelInsertSliceOp.
903     auto foreachThreadOp = cast<ForeachThreadOp>(op);
904     return {getInsertionDest(foreachThreadOp)[opResult.getResultNumber()]};
905   }
906 
907   bool isMemoryWrite(Operation *op, OpResult opResult,
908                      const AnalysisState &state) const {
909     // This op is a memory write. Stop lookup here to avoid finding false
910     // conflicts involving this op and one of the ops in the region. This is
911     // similar to how scf.if ops are analyzed.
912     return true;
913   }
914 
915   BufferRelation bufferRelation(Operation *op, OpResult opResult,
916                                 const AnalysisState &state) const {
917     return BufferRelation::Equivalent;
918   }
919 
920   LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter,
921                                  const AnalysisState &state) const {
922     auto bufferizableOp = cast<BufferizableOpInterface>(op);
923     if (failed(bufferizableOp.resolveTensorOpOperandConflicts(rewriter, state)))
924       return failure();
925 
926     OpBuilder::InsertionGuard g(rewriter);
927     auto foreachThreadOp = cast<ForeachThreadOp>(op);
928     for (OpResult opResult : foreachThreadOp->getOpResults()) {
929       SmallVector<OpOperand *> destOperands =
930           state.getAliasingOpOperand(opResult);
931       assert(destOperands.size() == 1 &&
932              "expected exactly one aliasing OpOperand");
933       assert(isa<ParallelInsertSliceOp>(destOperands.front()->getOwner()) &&
934              "expected ParallelInsertSliceOp");
935 
936       // Nothing to do if there is no conflict.
937       if (state.isInPlace(*destOperands.front()))
938         continue;
939 
940       // Create AllocTensorOp.
941       bool isYielded = state.isTensorYielded(opResult);
942       auto resultType = opResult.getType().cast<RankedTensorType>();
943       Value alloc = rewriter.create<bufferization::AllocTensorOp>(
944           op->getLoc(), resultType, /*dynamicDims=*/ValueRange(),
945           /*copy=*/destOperands.front()->get(),
946           /*escape=*/isYielded);
947 
948       // Update terminator operand.
949       rewriter.updateRootInPlace(destOperands.front()->getOwner(),
950                                  [&]() { destOperands.front()->set(alloc); });
951     }
952 
953     return success();
954   }
955 
956   LogicalResult bufferize(Operation *op, RewriterBase &b,
957                           BufferizationState &state) const {
958     OpBuilder::InsertionGuard g(b);
959     auto foreachThreadOp = cast<ForeachThreadOp>(op);
960 
961     // Gather new results of the ForeachThreadOp.
962     SmallVector<Value> newResults;
963     for (OpResult opResult : foreachThreadOp->getOpResults()) {
964       OpOperand *insertDest =
965           getInsertionDest(foreachThreadOp)[opResult.getResultNumber()];
966       // Insert copies right before the PerformConcurrentlyOp terminator. They
967       // should not be inside terminator (which would be the default insertion
968       // point).
969       Value buffer = state.getBuffer(b, insertDest->get());
970       newResults.push_back(buffer);
971     }
972 
973     // Create new ForeachThreadOp without any results and drop the automatically
974     // introduced terminator.
975     TypeRange newResultTypes;
976     auto newForeachThreadOp =
977         b.create<ForeachThreadOp>(foreachThreadOp.getLoc(), newResultTypes,
978                                   foreachThreadOp.getNumThreads());
979     newForeachThreadOp.getBody()->getTerminator()->erase();
980 
981     // Move over block contents of the old op.
982     b.mergeBlocks(foreachThreadOp.getBody(), newForeachThreadOp.getBody(),
983                   {newForeachThreadOp.getBody()->getArguments()});
984 
985     // Bufferize terminator.
986     auto performConcurrentlyOp = cast<PerformConcurrentlyOp>(
987         newForeachThreadOp.getBody()->getTerminator());
988     b.setInsertionPoint(performConcurrentlyOp);
989     unsigned resultCounter = 0;
990     WalkResult walkResult =
991         performConcurrentlyOp.walk([&](ParallelInsertSliceOp insertOp) {
992           Location loc = insertOp.getLoc();
993           Type srcType = getMemRefType(
994               insertOp.getSource().getType().cast<RankedTensorType>(),
995               state.getOptions());
996           // ParallelInsertSliceOp bufferizes to a copy.
997           auto srcMemref = b.create<bufferization::ToMemrefOp>(
998               loc, srcType, insertOp.getSource());
999           Value destMemref = newResults[resultCounter++];
1000           Value subview = b.create<memref::SubViewOp>(
1001               loc, destMemref, insertOp.getMixedOffsets(),
1002               insertOp.getMixedSizes(), insertOp.getMixedStrides());
1003           // This memcpy will fold away if everything bufferizes in-place.
1004           if (failed(state.getOptions().createMemCpy(b, insertOp.getLoc(),
1005                                                      srcMemref, subview)))
1006             return WalkResult::interrupt();
1007           b.eraseOp(insertOp);
1008           return WalkResult::advance();
1009         });
1010     if (walkResult.wasInterrupted())
1011       return failure();
1012 
1013     // Replace the op.
1014     replaceOpWithBufferizedValues(b, op, newResults);
1015 
1016     return success();
1017   }
1018 };
1019 
1020 /// Nothing to do for PerformConcurrentlyOp.
1021 struct PerformConcurrentlyOpInterface
1022     : public BufferizableOpInterface::ExternalModel<
1023           PerformConcurrentlyOpInterface, PerformConcurrentlyOp> {
1024   LogicalResult bufferize(Operation *op, RewriterBase &b,
1025                           BufferizationState &state) const {
1026     llvm_unreachable("op does not have any tensor OpOperands / OpResults");
1027     return failure();
1028   }
1029 };
1030 
1031 /// Return true if the (ExtractSliceOp, ParallelInsertSliceOp) pair match (i.e.
1032 /// equivalent operand / result and same offset/sizes/strides specification).
1033 static bool areEquivalentExtractSliceOps(const AnalysisState &state,
1034                                          ExtractSliceOp st,
1035                                          ParallelInsertSliceOp sti) {
1036   if (!st || !sti)
1037     return false;
1038   if (st != sti &&
1039       !state.areEquivalentBufferizedValues(st.source(), sti.getDest()))
1040     return false;
1041   if (!sameOffsetsSizesAndStrides(st, sti, isEqualConstantIntOrValue))
1042     return false;
1043   return true;
1044 }
1045 
1046 /// Return true if `value` is originating from an ExtractSliceOp that matches
1047 /// the given InsertSliceOp.
1048 static bool hasMatchingExtractSliceOp(const AnalysisState &state, Value value,
1049                                       ParallelInsertSliceOp insertOp) {
1050   auto condition = [&](Value val) {
1051     if (auto extractOp = val.getDefiningOp<ExtractSliceOp>())
1052       if (areEquivalentExtractSliceOps(state, extractOp, insertOp))
1053         return true;
1054     return false;
1055   };
1056 
1057   return llvm::all_of(state.findValueInReverseUseDefChain(value, condition),
1058                       condition);
1059 }
1060 
1061 /// Analysis of ParallelInsertSliceOp.
1062 struct ParallelInsertSliceOpInterface
1063     : public BufferizableOpInterface::ExternalModel<
1064           ParallelInsertSliceOpInterface, ParallelInsertSliceOp> {
1065   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
1066                                             const AnalysisState &state) const {
1067     if (&opOperand != &op->getOpOperand(1) /*dest*/)
1068       return {};
1069 
1070     // ParallelInsertSliceOp itself has no results. Tensors are returned via
1071     // the parent op.
1072     auto foreachThreadOp = op->getParentOfType<ForeachThreadOp>();
1073     assert(foreachThreadOp &&
1074            "could not find valid owner of parallel_insert_slice");
1075 
1076     // The i-th ParallelInsertSliceOp result is returned via the i-th OpResult
1077     // of the parent ForeachThreadOp.
1078     Block *block = op->getBlock();
1079     unsigned int opIdx = 0;
1080     for (ParallelInsertSliceOp insertOp :
1081          block->getOps<ParallelInsertSliceOp>()) {
1082       if (insertOp.getOperation() == op)
1083         break;
1084       ++opIdx;
1085     }
1086     assert(opIdx < foreachThreadOp->getNumResults() &&
1087            "could not find op inside terminator op");
1088 
1089     return {foreachThreadOp->getResult(opIdx)};
1090   }
1091 
1092   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
1093                               const AnalysisState &state) const {
1094     return true;
1095   }
1096 
1097   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
1098                                const AnalysisState &state) const {
1099     return &opOperand == &op->getOpOperand(1) /*dest*/;
1100   }
1101 
1102   BufferRelation bufferRelation(Operation *op, OpResult opResult,
1103                                 const AnalysisState &state) const {
1104     return BufferRelation::Equivalent;
1105   }
1106 
1107   LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter,
1108                                  const AnalysisState &state) const {
1109     return success();
1110   }
1111 
1112   LogicalResult bufferize(Operation *op, RewriterBase &b,
1113                           BufferizationState &state) const {
1114     // Will be bufferized as part of ForeachThreadOp.
1115     return failure();
1116   }
1117 
1118   // TODO: This is copied from TensorInterfaceImpl.cpp. Find a way to share
1119   // the code.
1120   bool isNotConflicting(Operation *op, OpOperand *uRead,
1121                         OpOperand *uConflictingWrite,
1122                         const AnalysisState &state) const {
1123     Operation *readingOp = uRead->getOwner();
1124     Operation *conflictingWritingOp = uConflictingWrite->getOwner();
1125 
1126     // Special rules for matching ExtractSliceOp/InsertSliceOp pairs. If
1127     // uRead is an InsertSliceOp...
1128     if (auto insertSliceOp = dyn_cast<ParallelInsertSliceOp>(readingOp)) {
1129       // As an example, consider the following IR.
1130       //
1131       // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
1132       // %1 = linalg.fill %cst, %0 {inplace= [true] }
1133       // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
1134       //     {inplace= [true] }
1135 
1136       // TODO: Use insertSliceOp.getDestOpOperand etc. when available.
1137       if (uRead == &insertSliceOp->getOpOperand(1) /*dest*/ &&
1138           hasMatchingExtractSliceOp(state, uConflictingWrite->get(),
1139                                     insertSliceOp))
1140         // Case 1: The main insight is that InsertSliceOp reads only part of
1141         // the destination tensor. The overwritten area is not read. If
1142         // uConflictingWrite writes into exactly the memory location that is
1143         // being read by uRead, this is not a conflict.
1144         //
1145         // In the above example:
1146         // uRead             = OpOperand 1 (%t) of tensor.insert_slice
1147         // uConflictingWrite = OpOperand 1 (%0) of linalg.fill
1148         //
1149         // The read of %t does not conflict with the write of the FillOp
1150         // (same aliases!) because the area that the FillOp operates on is
1151         // exactly the one that is *not* read via %t.
1152         return true;
1153 
1154       if (uRead == &insertSliceOp->getOpOperand(0) /*source*/ &&
1155           uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ &&
1156           hasMatchingExtractSliceOp(state, uRead->get(), insertSliceOp))
1157         // Case 2: The read of the source tensor and the write to the dest
1158         // tensor via an InsertSliceOp is not a conflict if the read is
1159         // reading exactly that part of an equivalent tensor that the
1160         // InsertSliceOp is writing.
1161         //
1162         // In the above example:
1163         // uRead             = OpOperand 0 (%1) of tensor.insert_slice
1164         // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
1165         return true;
1166     }
1167 
1168     // If uConflictingWrite is an InsertSliceOp...
1169     if (auto insertSliceOp =
1170             dyn_cast<ParallelInsertSliceOp>(conflictingWritingOp))
1171       // As an example, consider the following IR.
1172       //
1173       // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
1174       // %1 = linalg.fill %cst, %0 {inplace= [true] }
1175       // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
1176       //     {inplace= [true] }
1177       // %3 = vector.transfer_read %1, %cst
1178       //
1179       // In the above example:
1180       // uRead             = OpOperand 0 (%1) of vector.transfer_read
1181       // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
1182       // lastWrite         = %1
1183       //
1184       // This is not a conflict because the InsertSliceOp overwrites the
1185       // memory segment of %1 with the exact same data. (Effectively, there
1186       // is no memory write here.)
1187       if (uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ &&
1188           state.areEquivalentBufferizedValues(uRead->get(),
1189                                               insertSliceOp.getSource()) &&
1190           hasMatchingExtractSliceOp(state, insertSliceOp.getSource(),
1191                                     insertSliceOp))
1192         return true;
1193 
1194     return false;
1195   }
1196 };
1197 
1198 } // namespace
1199 } // namespace scf
1200 } // namespace mlir
1201 
1202 void mlir::scf::registerBufferizableOpInterfaceExternalModels(
1203     DialectRegistry &registry) {
1204   registry.addExtension(+[](MLIRContext *ctx, scf::SCFDialect *dialect) {
1205     ExecuteRegionOp::attachInterface<ExecuteRegionOpInterface>(*ctx);
1206     ForOp::attachInterface<ForOpInterface>(*ctx);
1207     IfOp::attachInterface<IfOpInterface>(*ctx);
1208     ForeachThreadOp::attachInterface<ForeachThreadOpInterface>(*ctx);
1209     ParallelInsertSliceOp::attachInterface<ParallelInsertSliceOpInterface>(
1210         *ctx);
1211     PerformConcurrentlyOp::attachInterface<PerformConcurrentlyOpInterface>(
1212         *ctx);
1213     WhileOp::attachInterface<WhileOpInterface>(*ctx);
1214     YieldOp::attachInterface<YieldOpInterface>(*ctx);
1215   });
1216 }
1217