1 //===- OneShotAnalysis.cpp - One-Shot (Single Pass) Analysis --------------===//
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 // One-Shot Analysis analyzes function bodies. Function boundaries (FuncOp
10 // bbArgs, CallOps, ReturnOps) are treated as "unknown" ops.
11 // ModuleBufferization.cpp is an extension of One-Shot Analysis for simple
12 // call graphs.
13 //
14 // One-Shot Bufferize consists of two phases.
15 //
16 // 1. Analyze ops to decide which OpResults can bufferize inplace, i.e., without
17 //    inserting buffer copies. The analysis queries op bufferization semantics
18 //    via `BufferizableOpInterface`.
19 // 2. Bufferize ops by calling `BufferizableOpInterface::bufferize`. This
20 //    function does not generate buffer copies for OpResults that were decided
21 //    to bufferize inplace during the analysis phase.
22 //
23 // This file contains only the analysis. The actual bufferization is implemented
24 // via `bufferizeOp` (Bufferize.h). For convenience, this file also contains a
25 // helper function `runOneShotBufferize` that analyzes an op (and its nested
26 // ops) and then bufferizes it.
27 //
28 // Inplace bufferization decisions are passed from the analysis to the
29 // bufferization phase via `BufferizationState` and `BufferizationAliasInfo`.
30 // They can be printed for debugging purposes with `testAnalysisOnly`.
31 //
32 // Ops that do not implement `BufferizableOpInterface` can be analyzed but are
33 // treated conservatively. E.g., the analysis has to assume that their tensor
34 // OpOperands bufferize to memory writes. While such ops can be analyzed, they
35 // are not bufferized and remain in the IR. to_tensor and to_memref ops are
36 // inserted at the bufferization boundary.
37 //
38 // This analysis caters to high-performance codegen where buffer reuse is deemed
39 // critical: the analysis should fail if the bufferized form of the function
40 // needs to return a buffer, unless `allowReturnMemref` is enabled.
41 
42 #include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h"
43 
44 #include <random>
45 
46 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
47 #include "mlir/Dialect/Bufferization/IR/Bufferization.h"
48 #include "mlir/Dialect/Bufferization/Transforms/Bufferize.h"
49 #include "mlir/Dialect/MemRef/IR/MemRef.h"
50 #include "mlir/IR/AsmState.h"
51 #include "mlir/IR/Dominance.h"
52 #include "mlir/IR/Operation.h"
53 #include "mlir/IR/TypeUtilities.h"
54 #include "mlir/Interfaces/ControlFlowInterfaces.h"
55 #include "llvm/ADT/DenseSet.h"
56 #include "llvm/ADT/SetVector.h"
57 
58 using namespace mlir;
59 using namespace mlir::bufferization;
60 
61 static bool isaTensor(Type t) { return t.isa<TensorType>(); }
62 
63 //===----------------------------------------------------------------------===//
64 // Bufferization-specific attribute manipulation.
65 // These are for testing and debugging only. Bufferization information is
66 // stored in BufferizationAliasInfo. When run with `testAnalysisOnly`, the IR
67 // is annotated with the results of the analysis (copied from
68 // BufferizationAliasInfo), so that they can be checked in tests.
69 //===----------------------------------------------------------------------===//
70 
71 /// Attribute marker to specify op results that can be bufferized inPlace.
72 constexpr StringLiteral kInPlaceResultsAttrName = "__inplace_operands_attr__";
73 
74 /// Mark whether OpOperand will be bufferized inplace.
75 static void setInPlaceOpOperand(OpOperand &opOperand, bool inPlace) {
76   Operation *op = opOperand.getOwner();
77   auto attr =
78       op->getAttr(kInPlaceResultsAttrName).dyn_cast_or_null<ArrayAttr>();
79   SmallVector<StringRef> inPlaceVector;
80   if (attr) {
81     inPlaceVector = SmallVector<StringRef>(
82         llvm::to_vector<4>(attr.getAsValueRange<StringAttr>()));
83   } else {
84     inPlaceVector = SmallVector<StringRef>(op->getNumOperands(), "none");
85     for (OpOperand &opOperand : op->getOpOperands())
86       if (opOperand.get().getType().isa<TensorType>())
87         inPlaceVector[opOperand.getOperandNumber()] = "false";
88   }
89 
90   inPlaceVector[opOperand.getOperandNumber()] = inPlace ? "true" : "false";
91   op->setAttr(kInPlaceResultsAttrName,
92               OpBuilder(op).getStrArrayAttr(inPlaceVector));
93 }
94 
95 //===----------------------------------------------------------------------===//
96 // BufferizationAliasInfo
97 //===----------------------------------------------------------------------===//
98 
99 BufferizationAliasInfo::BufferizationAliasInfo(Operation *rootOp) {
100   rootOp->walk([&](Operation *op) {
101     for (Value v : op->getResults())
102       if (v.getType().isa<TensorType>())
103         createAliasInfoEntry(v);
104     for (Region &r : op->getRegions())
105       for (Block &b : r.getBlocks())
106         for (auto bbArg : b.getArguments())
107           if (bbArg.getType().isa<TensorType>())
108             createAliasInfoEntry(bbArg);
109   });
110 }
111 
112 /// Add a new entry for `v` in the `aliasInfo` and `equivalentInfo`. In the
113 /// beginning the alias and equivalence sets only contain `v` itself.
114 void BufferizationAliasInfo::createAliasInfoEntry(Value v) {
115   aliasInfo.insert(v);
116   equivalentInfo.insert(v);
117 }
118 
119 /// Insert an info entry for `newValue` and merge its alias set with that of
120 /// `alias`.
121 void BufferizationAliasInfo::insertNewBufferAlias(Value newValue, Value alias) {
122   createAliasInfoEntry(newValue);
123   aliasInfo.unionSets(newValue, alias);
124 }
125 
126 /// Insert an info entry for `newValue` and merge its alias set with that of
127 /// `alias`. Additionally, merge their equivalence classes.
128 void BufferizationAliasInfo::insertNewBufferEquivalence(Value newValue,
129                                                         Value alias) {
130   insertNewBufferAlias(newValue, alias);
131   equivalentInfo.unionSets(newValue, alias);
132 }
133 
134 /// Return `true` if a value was marked as in-place bufferized.
135 bool BufferizationAliasInfo::isInPlace(OpOperand &operand) const {
136   return inplaceBufferized.contains(&operand);
137 }
138 
139 /// Set the inPlace bufferization spec to true.
140 void BufferizationAliasInfo::bufferizeInPlace(OpOperand &operand,
141                                               BufferizationState &state) {
142   markInPlace(operand);
143   for (OpResult result : state.getAliasingOpResult(operand))
144     aliasInfo.unionSets(result, operand.get());
145 }
146 
147 /// Set the inPlace bufferization spec to false.
148 void BufferizationAliasInfo::bufferizeOutOfPlace(OpOperand &operand) {
149   assert(!inplaceBufferized.contains(&operand) &&
150          "OpOperand was already decided to bufferize inplace");
151 }
152 
153 /// Apply `fun` to all the members of the equivalence class of `v`.
154 void BufferizationAliasInfo::applyOnEquivalenceClass(
155     Value v, function_ref<void(Value)> fun) const {
156   auto leaderIt = equivalentInfo.findLeader(v);
157   for (auto mit = leaderIt, meit = equivalentInfo.member_end(); mit != meit;
158        ++mit) {
159     fun(*mit);
160   }
161 }
162 
163 /// Apply `fun` to all aliases of `v`.
164 void BufferizationAliasInfo::applyOnAliases(
165     Value v, function_ref<void(Value)> fun) const {
166   auto leaderIt = aliasInfo.findLeader(v);
167   for (auto mit = leaderIt, meit = aliasInfo.member_end(); mit != meit; ++mit) {
168     fun(*mit);
169   }
170 }
171 
172 BufferizationAliasInfo::EquivalenceClassRangeType
173 BufferizationAliasInfo::getAliases(Value v) const {
174   DenseSet<Value> res;
175   auto it = aliasInfo.findValue(aliasInfo.getLeaderValue(v));
176   for (auto mit = aliasInfo.member_begin(it), meit = aliasInfo.member_end();
177        mit != meit; ++mit) {
178     res.insert(static_cast<Value>(*mit));
179   }
180   return BufferizationAliasInfo::EquivalenceClassRangeType(
181       aliasInfo.member_begin(it), aliasInfo.member_end());
182 }
183 
184 //===----------------------------------------------------------------------===//
185 // AnalysisBufferizationState
186 //===----------------------------------------------------------------------===//
187 
188 AnalysisBufferizationState::AnalysisBufferizationState(
189     Operation *op, const AnalysisBufferizationOptions &options)
190     : BufferizationState(options), aliasInfo(op) {
191   // Set up alias sets for OpResults that must bufferize in-place. This should
192   // be done before making any other bufferization decisions.
193   op->walk([&](BufferizableOpInterface bufferizableOp) {
194     if (!options.isOpAllowed(bufferizableOp))
195       return WalkResult::skip();
196     for (OpOperand &opOperand : bufferizableOp->getOpOperands()) {
197       if (opOperand.get().getType().isa<TensorType>())
198         if (bufferizableOp.mustBufferizeInPlace(opOperand, *this)) {
199           for (OpResult opResult :
200                bufferizableOp.getAliasingOpResult(opOperand, *this))
201             aliasInfo.unionAliasSets(opOperand.get(), opResult);
202           aliasInfo.markInPlace(opOperand);
203         }
204     }
205     return WalkResult::advance();
206   });
207 }
208 
209 bool AnalysisBufferizationState::isInPlace(OpOperand &opOperand) const {
210   return aliasInfo.isInPlace(opOperand);
211 }
212 
213 bool AnalysisBufferizationState::areEquivalentBufferizedValues(Value v1,
214                                                                Value v2) const {
215   return aliasInfo.areEquivalentBufferizedValues(v1, v2);
216 }
217 
218 //===----------------------------------------------------------------------===//
219 // Bufferization-specific alias analysis.
220 //===----------------------------------------------------------------------===//
221 
222 /// Return true if opOperand has been decided to bufferize in-place.
223 static bool isInplaceMemoryWrite(OpOperand &opOperand,
224                                  const BufferizationAliasInfo &aliasInfo,
225                                  BufferizationState &state) {
226   // OpOperands that do not bufferize to a memory write do not write in-place.
227   if (!state.bufferizesToMemoryWrite(opOperand))
228     return false;
229   // Check current bufferization decisions.
230   return aliasInfo.isInPlace(opOperand);
231 }
232 
233 /// Return true if, under current bufferization decisions, the buffer of `value`
234 /// is not writable.
235 static bool aliasesNonWritableBuffer(Value value,
236                                      const BufferizationAliasInfo &aliasInfo,
237                                      BufferizationState &state) {
238   bool foundNonWritableBuffer = false;
239   aliasInfo.applyOnAliases(value, [&](Value v) {
240     // Query BufferizableOpInterface to see if the value is writable.
241     // TODO: Out-of-place bufferized value could be considered writable.
242     if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(v))
243       if (bufferizableOp && bufferizableOp.isWritable(v, state))
244         return;
245 
246     // Query BufferizableOpInterface to see if the BlockArgument is writable.
247     if (auto bbArg = v.dyn_cast<BlockArgument>())
248       if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(
249               bbArg.getOwner()->getParentOp()))
250         if (bufferizableOp.isWritable(bbArg, state))
251           return;
252 
253     foundNonWritableBuffer = true;
254   });
255 
256   return foundNonWritableBuffer;
257 }
258 
259 /// Return true if the buffer to which `operand` would bufferize is equivalent
260 /// to some buffer write.
261 static bool aliasesInPlaceWrite(Value value,
262                                 const BufferizationAliasInfo &aliasInfo,
263                                 BufferizationState &state) {
264   bool foundInplaceWrite = false;
265   aliasInfo.applyOnAliases(value, [&](Value v) {
266     for (auto &use : v.getUses()) {
267       if (isInplaceMemoryWrite(use, aliasInfo, state)) {
268         foundInplaceWrite = true;
269         return;
270       }
271     }
272   });
273   return foundInplaceWrite;
274 }
275 
276 /// Return true if `a` happens before `b`, i.e., `a` or one of its ancestors
277 /// properly dominates `b` and `b` is not inside `a`.
278 static bool happensBefore(Operation *a, Operation *b,
279                           const DominanceInfo &domInfo) {
280   do {
281     // TODO: Instead of isProperAncestor + properlyDominates, we should use
282     // properlyDominatesImpl(a, b, /*enclosingOpOk=*/false)
283     if (a->isProperAncestor(b))
284       return false;
285     if (domInfo.properlyDominates(a, b))
286       return true;
287   } while ((a = a->getParentOp()));
288   return false;
289 }
290 
291 /// Annotate IR with details about the detected RaW conflict.
292 static void annotateConflict(OpOperand *uRead, OpOperand *uConflictingWrite,
293                              Value lastWrite) {
294   static uint64_t counter = 0;
295   Operation *readingOp = uRead->getOwner();
296   Operation *conflictingWritingOp = uConflictingWrite->getOwner();
297 
298   OpBuilder b(conflictingWritingOp->getContext());
299   std::string id = "C_" + std::to_string(counter++);
300 
301   std::string conflictingWriteAttr =
302       id +
303       "[CONFL-WRITE: " + std::to_string(uConflictingWrite->getOperandNumber()) +
304       "]";
305   conflictingWritingOp->setAttr(conflictingWriteAttr, b.getUnitAttr());
306 
307   std::string readAttr =
308       id + "[READ: " + std::to_string(uRead->getOperandNumber()) + "]";
309   readingOp->setAttr(readAttr, b.getUnitAttr());
310 
311   if (auto opResult = lastWrite.dyn_cast<OpResult>()) {
312     std::string lastWriteAttr = id + "[LAST-WRITE: result " +
313                                 std::to_string(opResult.getResultNumber()) +
314                                 "]";
315     opResult.getDefiningOp()->setAttr(lastWriteAttr, b.getUnitAttr());
316   } else {
317     auto bbArg = lastWrite.cast<BlockArgument>();
318     std::string lastWriteAttr =
319         id + "[LAST-WRITE: bbArg " + std::to_string(bbArg.getArgNumber()) + "]";
320     bbArg.getOwner()->getParentOp()->setAttr(lastWriteAttr, b.getUnitAttr());
321   }
322 }
323 
324 /// Given sets of uses and writes, return true if there is a RaW conflict under
325 /// the assumption that all given reads/writes alias the same buffer and that
326 /// all given writes bufferize inplace.
327 ///
328 /// A conflict is: According to SSA use-def chains, a read R is supposed to read
329 /// the result of a write W1. But because of bufferization decisions, R actually
330 /// reads another write W2.
331 static bool hasReadAfterWriteInterference(
332     const DenseSet<OpOperand *> &usesRead,
333     const DenseSet<OpOperand *> &usesWrite, const DominanceInfo &domInfo,
334     BufferizationState &state, const BufferizationAliasInfo &aliasInfo) {
335   const BufferizationOptions &options = state.getOptions();
336 
337   for (OpOperand *uRead : usesRead) {
338     Operation *readingOp = uRead->getOwner();
339 
340     // Find most recent writes of uRead by following the SSA use-def chain.
341     // E.g.:
342     //
343     // %0 = "writing_op"(%t) : tensor<?x32> -> tensor<?xf32>
344     // %1 = "aliasing_op"(%0) : tensor<?x32> -> tensor<?xf32>
345     // %2 = "reading_op"(%1) : : tensor<?x32> -> not_a_tensor_type
346     //
347     // In the above example, if uRead is the OpOperand of reading_op, lastWrite
348     // is %0. Note that operations that create an alias but do not write (such
349     // as ExtractSliceOp) are skipped.
350     SetVector<Value> lastWrites = state.findLastPrecedingWrite(uRead->get());
351 
352     // Look for conflicting memory writes. Potential conflicts are writes to an
353     // alias that have been decided to bufferize inplace.
354     for (OpOperand *uConflictingWrite : usesWrite) {
355       // Throughout this loop, check for multiple requirements that have to be
356       // met for uConflictingWrite to be an actual conflict.
357       Operation *conflictingWritingOp = uConflictingWrite->getOwner();
358 
359       // No conflict if the readingOp dominates conflictingWritingOp, i.e., the
360       // write is not visible when reading.
361       if (happensBefore(readingOp, conflictingWritingOp, domInfo))
362         continue;
363 
364       // No conflict if the reading use equals the use of the conflicting write.
365       // A use cannot conflict with itself. Note: Just being the same op is not
366       // enough. It has to be the same use.
367       if (uConflictingWrite == uRead)
368         continue;
369 
370       // No conflict if the op interface says so.
371       if (auto bufferizableOp = options.dynCastBufferizableOp(readingOp))
372         if (bufferizableOp.isNotConflicting(uRead, uConflictingWrite, state))
373           continue;
374 
375       if (conflictingWritingOp != readingOp)
376         if (auto bufferizableOp =
377                 options.dynCastBufferizableOp(conflictingWritingOp))
378           if (bufferizableOp.isNotConflicting(uRead, uConflictingWrite, state))
379             continue;
380 
381       // Ops are not conflicting if they are in mutually exclusive regions.
382       if (insideMutuallyExclusiveRegions(readingOp, conflictingWritingOp))
383         continue;
384 
385       // Check all possible last writes.
386       for (Value lastWrite : lastWrites) {
387         // No conflict if the conflicting write happens before the last
388         // write.
389         if (Operation *writingOp = lastWrite.getDefiningOp()) {
390           if (happensBefore(conflictingWritingOp, writingOp, domInfo))
391             // conflictingWritingOp happens before writingOp. No conflict.
392             continue;
393           // No conflict if conflictingWritingOp is contained in writingOp.
394           if (writingOp->isProperAncestor(conflictingWritingOp))
395             continue;
396         } else {
397           auto bbArg = lastWrite.cast<BlockArgument>();
398           Block *block = bbArg.getOwner();
399           if (!block->findAncestorOpInBlock(*conflictingWritingOp))
400             // conflictingWritingOp happens outside of the block. No
401             // conflict.
402             continue;
403         }
404 
405         // No conflict if the conflicting write and the last write are the same
406         // use.
407         SmallVector<OpResult> aliasingOpResult =
408             state.getAliasingOpResult(*uConflictingWrite);
409         if (aliasingOpResult.size() == 1 && aliasingOpResult[0] == lastWrite)
410           continue;
411 
412         // All requirements are met. Conflict found!
413 
414         if (options.printConflicts)
415           annotateConflict(uRead, uConflictingWrite, lastWrite);
416 
417         return true;
418       }
419     }
420   }
421 
422   return false;
423 }
424 
425 /// Return true if bufferizing `operand` inplace would create a conflict. A read
426 /// R and a write W of the same alias set is a conflict if inplace bufferization
427 /// of W changes the value read by R to a value different from the one that
428 /// would be expected by tracing back R's origin through SSA use-def chains.
429 /// A conflict can only be introduced by a new alias and/or an inplace
430 /// bufferization decision.
431 ///
432 /// Example:
433 /// %0 = tensor.extract_slice %t[...][...][1, 1] {inplace?}
434 /// %1 = vector.transfer_write %v1, %t {inplace} : vector<5xf32>, tensor<?xf32>
435 /// %e = tensor.extract_slice %1
436 /// %2 = vector.transfer_write %v2, %0 {inplace} : vector<6xf32>, tensor<?xf32>
437 /// %3 = vector.transfer_read %e, %cst : tensor<?xf32>, vector<7xf32>
438 ///
439 /// In the above example, the two TransferWriteOps have already been decided to
440 /// bufferize inplace. Bufferizing the ExtractSliceOp inplace would create a
441 /// conflict because:
442 /// * According to SSA use-def chains, we expect to read the result of %1.
443 /// * However, adding an alias {%0, %t} would mean that the second
444 ///   TransferWriteOp overwrites the first one. Therefore, the TransferReadOp
445 ///   would no longer be reading the result of %1.
446 ///
447 /// If `checkConsistencyOnly` is true, this function checks if there is a
448 /// read-after-write conflict without bufferizing `operand` inplace. This would
449 /// indicate a problem with the current inplace bufferization decisions.
450 ///
451 /// Note: If `checkConsistencyOnly`, this function may be called with a null
452 /// OpResult. In that case, only the consistency of bufferization decisions
453 /// involving aliases of the given OpOperand are checked.
454 static bool wouldCreateReadAfterWriteInterference(
455     OpOperand &operand, const DominanceInfo &domInfo, BufferizationState &state,
456     const BufferizationAliasInfo &aliasInfo,
457     bool checkConsistencyOnly = false) {
458   // Helper function to iterate on aliases of `root` and capture the reads.
459   auto getAliasingReads = [&](DenseSet<OpOperand *> &res, Value root) {
460     aliasInfo.applyOnAliases(root, [&](Value alias) {
461       for (auto &use : alias.getUses())
462         // Read to a value that aliases root.
463         if (state.bufferizesToMemoryRead(use))
464           res.insert(&use);
465     });
466   };
467 
468   // Helper function to iterate on aliases of `root` and capture the writes.
469   auto getAliasingInplaceWrites = [&](DenseSet<OpOperand *> &res, Value root) {
470     aliasInfo.applyOnAliases(root, [&](Value alias) {
471       for (auto &use : alias.getUses())
472         // Inplace write to a value that aliases root.
473         if (isInplaceMemoryWrite(use, aliasInfo, state))
474           res.insert(&use);
475     });
476   };
477 
478   // Collect reads and writes of all aliases of OpOperand and OpResult.
479   DenseSet<OpOperand *> usesRead, usesWrite;
480   getAliasingReads(usesRead, operand.get());
481   getAliasingInplaceWrites(usesWrite, operand.get());
482   for (OpResult result : state.getAliasingOpResult(operand)) {
483     getAliasingReads(usesRead, result);
484     getAliasingInplaceWrites(usesWrite, result);
485   }
486   if (!checkConsistencyOnly && state.bufferizesToMemoryWrite(operand))
487     usesWrite.insert(&operand);
488 
489   return hasReadAfterWriteInterference(usesRead, usesWrite, domInfo, state,
490                                        aliasInfo);
491 }
492 
493 /// Return true if bufferizing `opOperand` inplace would create a write to a
494 /// non-writable buffer.
495 static bool
496 wouldCreateWriteToNonWritableBuffer(OpOperand &opOperand,
497                                     const BufferizationAliasInfo &aliasInfo,
498                                     BufferizationState &state) {
499   // Certain buffers are not writeable:
500   //   1. A function bbArg that is not inplaceable or
501   //   2. A constant op.
502   bool nonWritable =
503       aliasesNonWritableBuffer(opOperand.get(), aliasInfo, state);
504   if (!nonWritable)
505     return false;
506 
507   // This is a problem only if the buffer is written to via some alias.
508   bool hasWrite = aliasesInPlaceWrite(opOperand.get(), aliasInfo, state) ||
509                   state.bufferizesToMemoryWrite(opOperand);
510 
511   for (OpResult opResult : state.getAliasingOpResult(opOperand))
512     hasWrite |= aliasesInPlaceWrite(opResult, aliasInfo, state);
513 
514   return hasWrite;
515 }
516 
517 //===----------------------------------------------------------------------===//
518 // Bufferization analyses.
519 //===----------------------------------------------------------------------===//
520 
521 /// Determine if `operand` can be bufferized in-place.
522 static LogicalResult bufferizableInPlaceAnalysisImpl(
523     OpOperand &operand, BufferizationAliasInfo &aliasInfo,
524     BufferizationState &state, const DominanceInfo &domInfo) {
525   bool foundInterference =
526       wouldCreateWriteToNonWritableBuffer(operand, aliasInfo, state) ||
527       wouldCreateReadAfterWriteInterference(operand, domInfo, state, aliasInfo);
528 
529   if (foundInterference)
530     aliasInfo.bufferizeOutOfPlace(operand);
531   else
532     aliasInfo.bufferizeInPlace(operand, state);
533 
534   return success();
535 }
536 
537 /// Analyze the `ops` to determine which OpOperands are inplaceable. Walk ops in
538 /// reverse and bufferize ops greedily. This is a good starter heuristic.
539 ///
540 /// Even if an op does not read or write, it may still create an alias when
541 /// bufferized in-place. An example of such ops is tensor.extract_slice.
542 ///
543 /// Rationale for bufferizing `%1 = tensor.extract_slice %0[...]` inplace:
544 ///
545 /// When bufferized out of place, an ExtractSliceOp lowers to alloc + copy. This
546 /// cannot change the flow of information for either the source or the
547 /// result buffers.
548 ///
549 /// When bufferized inplace, an ExtractSliceOp does not by itself create any
550 /// read or write from memory. Instead, it has the effect of merging the alias
551 /// sets of the source and the result buffers.
552 ///
553 /// An analysis is required to ensure inplace bufferization would not result in
554 /// RaW dependence violations.
555 static LogicalResult inPlaceAnalysis(SmallVector<Operation *> &ops,
556                                      BufferizationAliasInfo &aliasInfo,
557                                      BufferizationState &state,
558                                      const DominanceInfo &domInfo,
559                                      unsigned analysisFuzzerSeed = 0) {
560   if (analysisFuzzerSeed) {
561     // This is a fuzzer. For testing purposes only. Randomize the order in which
562     // operations are analyzed. The bufferization quality is likely worse, but
563     // we want to make sure that no assertions are triggered anywhere.
564     std::mt19937 g(analysisFuzzerSeed);
565     llvm::shuffle(ops.begin(), ops.end(), g);
566   }
567 
568   // Walk ops in reverse for better interference analysis.
569   for (Operation *op : reverse(ops))
570     for (OpOperand &opOperand : op->getOpOperands())
571       if (opOperand.get().getType().isa<TensorType>())
572         if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op))
573           if (failed(bufferizableInPlaceAnalysisImpl(opOperand, aliasInfo,
574                                                      state, domInfo)))
575             return failure();
576 
577   return success();
578 }
579 
580 /// Return true if the given op has a tensor result or a tensor operand.
581 static bool hasTensorSemantics(Operation *op) {
582   bool hasTensorResult = any_of(op->getResultTypes(), isaTensor);
583   bool hasTensorOperand = any_of(op->getOperandTypes(), isaTensor);
584   return hasTensorResult || hasTensorOperand;
585 }
586 
587 /// Analyze all ops that are contained in `op`.
588 static LogicalResult inPlaceAnalysis(Operation *op,
589                                      BufferizationAliasInfo &aliasInfo,
590                                      BufferizationState &state,
591                                      const DominanceInfo &domInfo,
592                                      unsigned analysisFuzzerSeed = 0) {
593   // Collect ops so we can build our own reverse traversal.
594   SmallVector<Operation *> ops;
595   op->walk([&](Operation *op) {
596     // No tensors => no buffers.
597     if (!hasTensorSemantics(op))
598       return;
599     ops.push_back(op);
600   });
601 
602   return inPlaceAnalysis(ops, aliasInfo, state, domInfo, analysisFuzzerSeed);
603 }
604 
605 /// Analyze equivalence of tied OpResult/OpOperand pairs of the given ops.
606 static void equivalenceAnalysis(SmallVector<Operation *> &ops,
607                                 BufferizationAliasInfo &aliasInfo,
608                                 BufferizationState &state) {
609   for (Operation *op : ops)
610     if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op))
611       for (OpResult opResult : op->getOpResults())
612         if (opResult.getType().isa<TensorType>())
613           for (OpOperand *opOperand :
614                bufferizableOp.getAliasingOpOperand(opResult, state))
615             if (state.isInPlace(*opOperand))
616               if (bufferizableOp.bufferRelation(opResult, state) ==
617                   BufferRelation::Equivalent)
618                 aliasInfo.unionEquivalenceClasses(opResult, opOperand->get());
619 }
620 
621 /// Analyze equivalence of tied OpResult/OpOperand pairs of all ops contained
622 /// in `op`.
623 static void equivalenceAnalysis(Operation *op,
624                                 BufferizationAliasInfo &aliasInfo,
625                                 BufferizationState &state) {
626   // Traverse ops in PostOrder: Nested ops first, then enclosing ops.
627   SmallVector<Operation *> ops;
628   op->walk<WalkOrder::PostOrder>([&](Operation *op) {
629     // No tensors => no buffers.
630     if (none_of(op->getResultTypes(), isaTensor))
631       return;
632     ops.push_back(op);
633   });
634 
635   equivalenceAnalysis(ops, aliasInfo, state);
636 }
637 
638 /// Assert that the current bufferization decisions are consistent.
639 static LogicalResult
640 checkAliasInfoConsistency(Operation *op, const DominanceInfo &domInfo,
641                           BufferizationState &state,
642                           const BufferizationAliasInfo &aliasInfo) {
643   const BufferizationOptions &options = state.getOptions();
644   Operation *inconsistentOp = nullptr;
645   WalkResult walkResult = op->walk([&](Operation *op) {
646     if (auto bufferizableOp = options.dynCastBufferizableOp(op))
647       for (OpOperand &opOperand : op->getOpOperands())
648         if (opOperand.get().getType().isa<TensorType>()) {
649           if (wouldCreateReadAfterWriteInterference(
650                   opOperand, domInfo, state, aliasInfo,
651                   /*checkConsistencyOnly=*/true)) {
652             // This error can happen if certain "mustBufferizeInPlace" interface
653             // methods are implemented incorrectly, such that the IR already has
654             // a RaW conflict before making any bufferization decisions.
655             inconsistentOp = op;
656             return WalkResult::interrupt();
657           }
658         }
659     return WalkResult::advance();
660   });
661 
662   if (walkResult.wasInterrupted())
663     return inconsistentOp->emitError("input IR has RaW conflict");
664   return success();
665 }
666 
667 /// Annotate the IR with the result of the analysis. For testing/debugging only.
668 static void
669 annotateOpsWithBufferizationMarkers(Operation *op,
670                                     const BufferizationAliasInfo &aliasInfo,
671                                     BufferizationState &state) {
672   op->walk([&](Operation *op) {
673     if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op))
674       for (OpOperand &opOperand : op->getOpOperands())
675         if (opOperand.get().getType().isa<TensorType>())
676           setInPlaceOpOperand(opOperand, aliasInfo.isInPlace(opOperand));
677   });
678 }
679 
680 /// Assert that IR is in destination-passing style. I.e., every value that is
681 /// returned or yielded from a block is:
682 /// * aliasing a bbArg of that block or a parent block, or
683 /// * aliasing an OpResult of a op in a parent block.
684 ///
685 /// Example:
686 /// ```
687 /// %0 = "some_op" : tensor<?xf32>
688 /// %1 = scf.if %c -> (tensor<?xf32>) {
689 ///   scf.yield %0 : tensor<?xf32>
690 /// } else {
691 ///   %t = linalg.init_tensor : tensor<?xf32>
692 ///   scf.yield %t : tensor<?xf32>
693 /// }
694 /// ```
695 /// In the above example, the first scf.yield op satifies destination-passing
696 /// style because the yielded value %0 is defined in the parent block. The
697 /// second scf.yield op does not satisfy destination-passing style because the
698 /// yielded value %t is defined in the same block as the scf.yield op.
699 // TODO: The current implementation checks for equivalent values instead of
700 // aliasing values, which is stricter than needed. We can currently not check
701 // for aliasing values because the analysis is a maybe-alias analysis and we
702 // need a must-alias analysis here.
703 static LogicalResult
704 assertDestinationPassingStyle(Operation *op, BufferizationState &state,
705                               BufferizationAliasInfo &aliasInfo,
706                               SmallVector<Operation *> &newOps) {
707   LogicalResult status = success();
708   DominanceInfo domInfo(op);
709   op->walk([&](Operation *returnOp) {
710     if (!isRegionReturnLike(returnOp))
711       return WalkResult::advance();
712 
713     for (OpOperand &returnValOperand : returnOp->getOpOperands()) {
714       Value returnVal = returnValOperand.get();
715       // Skip non-tensor values.
716       if (!returnVal.getType().isa<TensorType>())
717         continue;
718 
719       bool foundEquivValue = false;
720       aliasInfo.applyOnEquivalenceClass(returnVal, [&](Value equivVal) {
721         if (auto bbArg = equivVal.dyn_cast<BlockArgument>()) {
722           Operation *definingOp = bbArg.getOwner()->getParentOp();
723           if (definingOp->isProperAncestor(returnOp))
724             foundEquivValue = true;
725           return;
726         }
727 
728         Operation *definingOp = equivVal.getDefiningOp();
729         if (definingOp->getBlock()->findAncestorOpInBlock(
730                 *returnOp->getParentOp()))
731           // Skip ops that happen after `returnOp` and parent ops.
732           if (happensBefore(definingOp, returnOp, domInfo))
733             foundEquivValue = true;
734       });
735 
736       if (!foundEquivValue)
737         status =
738             returnOp->emitError()
739             << "operand #" << returnValOperand.getOperandNumber()
740             << " of ReturnLike op does not satisfy destination passing style";
741     }
742 
743     return WalkResult::advance();
744   });
745 
746   return status;
747 }
748 
749 LogicalResult bufferization::analyzeOp(Operation *op,
750                                        AnalysisBufferizationState &state) {
751   DominanceInfo domInfo(op);
752   BufferizationAliasInfo &aliasInfo = state.getAliasInfo();
753   const auto &options =
754       static_cast<const AnalysisBufferizationOptions &>(state.getOptions());
755 
756   if (failed(checkAliasInfoConsistency(op, domInfo, state, aliasInfo)))
757     return failure();
758 
759   // If the analysis fails, just return.
760   if (failed(inPlaceAnalysis(op, aliasInfo, state, domInfo,
761                              options.analysisFuzzerSeed)))
762     return failure();
763   equivalenceAnalysis(op, aliasInfo, state);
764 
765   for (const PostAnalysisStepFn &fn : options.postAnalysisSteps) {
766     SmallVector<Operation *> newOps;
767     if (failed(fn(op, state, aliasInfo, newOps)))
768       return failure();
769     // Analyze ops that were created by the PostAnalysisStepFn.
770     if (failed(inPlaceAnalysis(newOps, aliasInfo, state, domInfo)))
771       return failure();
772     equivalenceAnalysis(newOps, aliasInfo, state);
773   }
774 
775   if (!options.allowReturnMemref) {
776     SmallVector<Operation *> newOps;
777     if (failed(assertDestinationPassingStyle(op, state, aliasInfo, newOps)))
778       return failure();
779   }
780 
781   // Annotate operations if we only want to report the analysis.
782   if (options.testAnalysisOnly)
783     annotateOpsWithBufferizationMarkers(op, aliasInfo, state);
784 
785   return success();
786 }
787 
788 LogicalResult bufferization::runOneShotBufferize(
789     Operation *op, std::unique_ptr<AnalysisBufferizationOptions> options) {
790   AnalysisBufferizationState state(op, *options);
791   if (failed(analyzeOp(op, state)))
792     return failure();
793   if (options->testAnalysisOnly)
794     return success();
795   return bufferizeOp(op, state);
796 }
797