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 `AnalysisState` 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 `allowReturnAllocs` 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/Func/IR/FuncOps.h"
50 #include "mlir/Dialect/MemRef/IR/MemRef.h"
51 #include "mlir/IR/AsmState.h"
52 #include "mlir/IR/Dominance.h"
53 #include "mlir/IR/Operation.h"
54 #include "mlir/IR/TypeUtilities.h"
55 #include "mlir/Interfaces/ControlFlowInterfaces.h"
56 #include "llvm/ADT/DenseSet.h"
57 #include "llvm/ADT/SetVector.h"
58 
59 using namespace mlir;
60 using namespace mlir::bufferization;
61 
62 static bool isaTensor(Type t) { return t.isa<TensorType>(); }
63 
64 //===----------------------------------------------------------------------===//
65 // Bufferization-specific attribute manipulation.
66 // These are for testing and debugging only. Bufferization information is
67 // stored in BufferizationAliasInfo. When run with `testAnalysisOnly`, the IR
68 // is annotated with the results of the analysis (copied from
69 // BufferizationAliasInfo), so that they can be checked in tests.
70 //===----------------------------------------------------------------------===//
71 
72 /// Attribute marker to specify op results that can be bufferized inPlace.
73 constexpr StringLiteral kInPlaceResultsAttrName = "__inplace_operands_attr__";
74 
75 /// Mark whether OpOperand will be bufferized inplace.
76 static void setInPlaceOpOperand(OpOperand &opOperand, bool inPlace) {
77   Operation *op = opOperand.getOwner();
78   auto attr =
79       op->getAttr(kInPlaceResultsAttrName).dyn_cast_or_null<ArrayAttr>();
80   SmallVector<StringRef> inPlaceVector;
81   if (attr) {
82     inPlaceVector = SmallVector<StringRef>(
83         llvm::to_vector<4>(attr.getAsValueRange<StringAttr>()));
84   } else {
85     inPlaceVector = SmallVector<StringRef>(op->getNumOperands(), "none");
86     for (OpOperand &opOperand : op->getOpOperands())
87       if (opOperand.get().getType().isa<TensorType>())
88         inPlaceVector[opOperand.getOperandNumber()] = "false";
89   }
90 
91   inPlaceVector[opOperand.getOperandNumber()] = inPlace ? "true" : "false";
92   op->setAttr(kInPlaceResultsAttrName,
93               OpBuilder(op).getStrArrayAttr(inPlaceVector));
94 }
95 
96 //===----------------------------------------------------------------------===//
97 // BufferizationAliasInfo
98 //===----------------------------------------------------------------------===//
99 
100 BufferizationAliasInfo::BufferizationAliasInfo(Operation *rootOp) {
101   rootOp->walk([&](Operation *op) {
102     for (Value v : op->getResults())
103       if (v.getType().isa<TensorType>())
104         createAliasInfoEntry(v);
105     for (Region &r : op->getRegions())
106       for (Block &b : r.getBlocks())
107         for (auto bbArg : b.getArguments())
108           if (bbArg.getType().isa<TensorType>())
109             createAliasInfoEntry(bbArg);
110   });
111 }
112 
113 /// Add a new entry for `v` in the `aliasInfo` and `equivalentInfo`. In the
114 /// beginning the alias and equivalence sets only contain `v` itself.
115 void BufferizationAliasInfo::createAliasInfoEntry(Value v) {
116   aliasInfo.insert(v);
117   equivalentInfo.insert(v);
118 }
119 
120 /// Insert an info entry for `newValue` and merge its alias set with that of
121 /// `alias`.
122 void BufferizationAliasInfo::insertNewBufferAlias(Value newValue, Value alias) {
123   createAliasInfoEntry(newValue);
124   aliasInfo.unionSets(newValue, alias);
125 }
126 
127 /// Insert an info entry for `newValue` and merge its alias set with that of
128 /// `alias`. Additionally, merge their equivalence classes.
129 void BufferizationAliasInfo::insertNewBufferEquivalence(Value newValue,
130                                                         Value alias) {
131   insertNewBufferAlias(newValue, alias);
132   equivalentInfo.unionSets(newValue, alias);
133 }
134 
135 /// Return `true` if a value was marked as in-place bufferized.
136 bool BufferizationAliasInfo::isInPlace(OpOperand &operand) const {
137   return inplaceBufferized.contains(&operand);
138 }
139 
140 /// Set the inPlace bufferization spec to true.
141 void BufferizationAliasInfo::bufferizeInPlace(OpOperand &operand,
142                                               AnalysisState &state) {
143   markInPlace(operand);
144   for (OpResult result : state.getAliasingOpResult(operand))
145     aliasInfo.unionSets(result, operand.get());
146 }
147 
148 /// Set the inPlace bufferization spec to false.
149 void BufferizationAliasInfo::bufferizeOutOfPlace(OpOperand &operand) {
150   assert(!inplaceBufferized.contains(&operand) &&
151          "OpOperand was already decided to bufferize inplace");
152 }
153 
154 /// Apply `fun` to all the members of the equivalence class of `v`.
155 void BufferizationAliasInfo::applyOnEquivalenceClass(
156     Value v, function_ref<void(Value)> fun) const {
157   auto leaderIt = equivalentInfo.findLeader(v);
158   for (auto mit = leaderIt, meit = equivalentInfo.member_end(); mit != meit;
159        ++mit) {
160     fun(*mit);
161   }
162 }
163 
164 /// Apply `fun` to all aliases of `v`.
165 void BufferizationAliasInfo::applyOnAliases(
166     Value v, function_ref<void(Value)> fun) const {
167   auto leaderIt = aliasInfo.findLeader(v);
168   for (auto mit = leaderIt, meit = aliasInfo.member_end(); mit != meit; ++mit) {
169     fun(*mit);
170   }
171 }
172 
173 BufferizationAliasInfo::EquivalenceClassRangeType
174 BufferizationAliasInfo::getAliases(Value v) const {
175   DenseSet<Value> res;
176   auto it = aliasInfo.findValue(aliasInfo.getLeaderValue(v));
177   for (auto mit = aliasInfo.member_begin(it), meit = aliasInfo.member_end();
178        mit != meit; ++mit) {
179     res.insert(static_cast<Value>(*mit));
180   }
181   return BufferizationAliasInfo::EquivalenceClassRangeType(
182       aliasInfo.member_begin(it), aliasInfo.member_end());
183 }
184 
185 //===----------------------------------------------------------------------===//
186 // OneShotAnalysisState
187 //===----------------------------------------------------------------------===//
188 
189 OneShotAnalysisState::OneShotAnalysisState(
190     Operation *op, const OneShotBufferizationOptions &options)
191     : AnalysisState(options), aliasInfo(op) {
192   // Set up alias sets for OpResults that must bufferize in-place. This should
193   // be done before making any other bufferization decisions.
194   op->walk([&](BufferizableOpInterface bufferizableOp) {
195     if (!options.isOpAllowed(bufferizableOp))
196       return WalkResult::skip();
197     for (OpOperand &opOperand : bufferizableOp->getOpOperands()) {
198       if (opOperand.get().getType().isa<TensorType>())
199         if (bufferizableOp.mustBufferizeInPlace(opOperand, *this)) {
200           for (OpResult opResult :
201                bufferizableOp.getAliasingOpResult(opOperand, *this))
202             aliasInfo.unionAliasSets(opOperand.get(), opResult);
203           aliasInfo.markInPlace(opOperand);
204         }
205     }
206     return WalkResult::advance();
207   });
208 }
209 
210 bool OneShotAnalysisState::isInPlace(OpOperand &opOperand) const {
211   return aliasInfo.isInPlace(opOperand);
212 }
213 
214 bool OneShotAnalysisState::areEquivalentBufferizedValues(Value v1,
215                                                          Value v2) const {
216   return aliasInfo.areEquivalentBufferizedValues(v1, v2);
217 }
218 
219 bool OneShotAnalysisState::areAliasingBufferizedValues(Value v1,
220                                                        Value v2) const {
221   return aliasInfo.areAliasingBufferizedValues(v1, v2);
222 }
223 
224 // Gather yielded tensors in `yieldedTensors` by querying all aliases. This is
225 // to ensure that such information is available during bufferization time.
226 // Alias information can no longer be queried through BufferizationAliasInfo
227 // once we have started modifying the IR.
228 void OneShotAnalysisState::gatherYieldedTensors(Operation *op) {
229   op->walk([&](Operation *returnOp) {
230     if (!isRegionReturnLike(returnOp) || !getOptions().isOpAllowed(returnOp))
231       return WalkResult::advance();
232 
233     for (OpOperand &returnValOperand : returnOp->getOpOperands()) {
234       Value returnVal = returnValOperand.get();
235       // Skip non-tensor values.
236       if (!returnVal.getType().isa<TensorType>())
237         continue;
238 
239       // Add all aliases of the returned value. But only the ones that are in
240       // the same block.
241       aliasInfo.applyOnAliases(returnVal, [&](Value v) {
242         if (auto bbArg = v.dyn_cast<BlockArgument>()) {
243           if (bbArg.getOwner()->getParentOp() == returnOp->getParentOp())
244             yieldedTensors.insert(bbArg);
245           return;
246         }
247         Operation *definingOp = v.getDefiningOp();
248         if (definingOp->getParentOp() == returnOp->getParentOp())
249           yieldedTensors.insert(v);
250       });
251     }
252 
253     return WalkResult::advance();
254   });
255 }
256 
257 void OneShotAnalysisState::gatherUndefinedTensorUses(Operation *op) {
258   op->walk([&](Operation *op) {
259     // Skip unknown ops.
260     auto bufferizableOp = getOptions().dynCastBufferizableOp(op);
261     if (!bufferizableOp)
262       return WalkResult::skip();
263 
264     // Check all tensor OpResults.
265     for (OpResult opResult : op->getOpResults()) {
266       if (!opResult.getType().isa<TensorType>())
267         continue;
268 
269       // If there is no preceding memory write, the tensor contents are
270       // undefined.
271       // Note: If `findLastPrecedingWrite` reaches the end of the reverse SSA
272       // use-def chain, it returns that value, regardless of whether it is a
273       // memory write or not.
274       SetVector<Value> lastWrites = findLastPrecedingWrite(opResult);
275       bool isUndefined = llvm::none_of(lastWrites, [&](Value lastWrite) {
276         if (auto bufferizableOp = getOptions().dynCastBufferizableOp(lastWrite))
277           return bufferizableOp.isMemoryWrite(lastWrite.cast<OpResult>(),
278                                               *this);
279         return true;
280       });
281       if (isUndefined)
282         for (OpOperand &use : opResult.getUses())
283           undefinedTensorUses.insert(&use);
284     }
285 
286     return WalkResult::advance();
287   });
288 }
289 
290 bool OneShotAnalysisState::hasUndefinedContents(OpOperand *opOperand) const {
291   return undefinedTensorUses.contains(opOperand);
292 }
293 
294 bool OneShotAnalysisState::isTensorYielded(Value tensor) const {
295   return yieldedTensors.contains(tensor);
296 }
297 
298 bool OneShotAnalysisState::isValueWritten(Value value) const {
299   bool isWritten = false;
300   aliasInfo.applyOnAliases(value, [&](Value val) {
301     for (OpOperand &use : val.getUses())
302       if (isInPlace(use) && bufferizesToMemoryWrite(use))
303         isWritten = true;
304   });
305   return isWritten;
306 }
307 
308 //===----------------------------------------------------------------------===//
309 // Bufferization-specific alias analysis.
310 //===----------------------------------------------------------------------===//
311 
312 /// Return true if opOperand has been decided to bufferize in-place.
313 static bool isInplaceMemoryWrite(OpOperand &opOperand,
314                                  const BufferizationAliasInfo &aliasInfo,
315                                  AnalysisState &state) {
316   // OpOperands that do not bufferize to a memory write do not write in-place.
317   if (!state.bufferizesToMemoryWrite(opOperand))
318     return false;
319   // Check current bufferization decisions.
320   return aliasInfo.isInPlace(opOperand);
321 }
322 
323 /// Return true if, under current bufferization decisions, the buffer of `value`
324 /// is not writable.
325 static bool aliasesNonWritableBuffer(Value value,
326                                      const BufferizationAliasInfo &aliasInfo,
327                                      AnalysisState &state) {
328   bool foundNonWritableBuffer = false;
329   aliasInfo.applyOnAliases(value, [&](Value v) {
330     // Query BufferizableOpInterface to see if the value is writable.
331     // TODO: Out-of-place bufferized value could be considered writable.
332     if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(v))
333       if (bufferizableOp && bufferizableOp.isWritable(v, state))
334         return;
335 
336     // Query BufferizableOpInterface to see if the BlockArgument is writable.
337     if (auto bbArg = v.dyn_cast<BlockArgument>())
338       if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(
339               bbArg.getOwner()->getParentOp()))
340         if (bufferizableOp.isWritable(bbArg, state))
341           return;
342 
343     foundNonWritableBuffer = true;
344   });
345 
346   return foundNonWritableBuffer;
347 }
348 
349 /// Return true if the buffer to which `operand` would bufferize is equivalent
350 /// to some buffer write.
351 static bool aliasesInPlaceWrite(Value value,
352                                 const BufferizationAliasInfo &aliasInfo,
353                                 AnalysisState &state) {
354   bool foundInplaceWrite = false;
355   aliasInfo.applyOnAliases(value, [&](Value v) {
356     for (auto &use : v.getUses()) {
357       if (isInplaceMemoryWrite(use, aliasInfo, state)) {
358         foundInplaceWrite = true;
359         return;
360       }
361     }
362   });
363   return foundInplaceWrite;
364 }
365 
366 /// Return true if `a` happens before `b`, i.e., `a` or one of its ancestors
367 /// properly dominates `b` and `b` is not inside `a`.
368 static bool happensBefore(Operation *a, Operation *b,
369                           const DominanceInfo &domInfo) {
370   do {
371     // TODO: Instead of isProperAncestor + properlyDominates, we should use
372     // properlyDominatesImpl(a, b, /*enclosingOpOk=*/false)
373     if (a->isProperAncestor(b))
374       return false;
375     if (domInfo.properlyDominates(a, b))
376       return true;
377   } while ((a = a->getParentOp()));
378   return false;
379 }
380 
381 /// For each given value, find the closest enclosing repetitive region. If this
382 /// is the same region for each value, return it. Otherwise return None.
383 /// Note: If there is no enclosing repetitive region, return nullptr.
384 static Optional<Region *>
385 getCommonEnclosingRepetitiveRegion(ArrayRef<Value> values) {
386   if (values.empty())
387     return None;
388   Region *r = getEnclosingRepetitiveRegion(values.front());
389   for (Value value : values.drop_front())
390     if (getEnclosingRepetitiveRegion(value) != r)
391       return None;
392   return r;
393 }
394 
395 /// Return `true` if the given tensor value is a memory write. Most values are
396 /// tensor writes, but ops that define a tensor SSA value without specifying its
397 /// contents (e.g., alloc_tensor) are not.
398 static bool isMemoryWrite(Value value, const AnalysisState &state) {
399   auto opResult = value.dyn_cast<OpResult>();
400   if (!opResult)
401     return true;
402   auto bufferizableOp = state.getOptions().dynCastBufferizableOp(value);
403   if (!bufferizableOp)
404     return true;
405   return bufferizableOp.isMemoryWrite(opResult, state);
406 }
407 
408 /// Annotate IR with details about the detected RaW conflict.
409 static void annotateConflict(OpOperand *uRead, OpOperand *uConflictingWrite,
410                              Value lastWrite) {
411   static uint64_t counter = 0;
412   Operation *readingOp = uRead->getOwner();
413   Operation *conflictingWritingOp = uConflictingWrite->getOwner();
414 
415   OpBuilder b(conflictingWritingOp->getContext());
416   std::string id = "C_" + std::to_string(counter++);
417 
418   std::string conflictingWriteAttr =
419       id +
420       "[CONFL-WRITE: " + std::to_string(uConflictingWrite->getOperandNumber()) +
421       "]";
422   conflictingWritingOp->setAttr(conflictingWriteAttr, b.getUnitAttr());
423 
424   std::string readAttr =
425       id + "[READ: " + std::to_string(uRead->getOperandNumber()) + "]";
426   readingOp->setAttr(readAttr, b.getUnitAttr());
427 
428   if (auto opResult = lastWrite.dyn_cast<OpResult>()) {
429     std::string lastWriteAttr = id + "[LAST-WRITE: result " +
430                                 std::to_string(opResult.getResultNumber()) +
431                                 "]";
432     opResult.getDefiningOp()->setAttr(lastWriteAttr, b.getUnitAttr());
433   } else {
434     auto bbArg = lastWrite.cast<BlockArgument>();
435     std::string lastWriteAttr =
436         id + "[LAST-WRITE: bbArg " + std::to_string(bbArg.getArgNumber()) + "]";
437     bbArg.getOwner()->getParentOp()->setAttr(lastWriteAttr, b.getUnitAttr());
438   }
439 }
440 
441 /// Given sets of uses and writes, return true if there is a RaW conflict under
442 /// the assumption that all given reads/writes alias the same buffer and that
443 /// all given writes bufferize inplace.
444 ///
445 /// A conflict is: According to SSA use-def chains, a read R is supposed to read
446 /// the result of a write W1. But because of bufferization decisions, R actually
447 /// reads another write W2.
448 static bool hasReadAfterWriteInterference(
449     const DenseSet<OpOperand *> &usesRead,
450     const DenseSet<OpOperand *> &usesWrite, const DominanceInfo &domInfo,
451     AnalysisState &state, const BufferizationAliasInfo &aliasInfo) {
452   const BufferizationOptions &options = state.getOptions();
453 
454   // Gather all written aliases. Skip over aliases that are not actual writes.
455   SmallVector<Value> writtenAliases;
456   for (OpOperand *uWrite : usesWrite)
457     if (isMemoryWrite(uWrite->get(), state))
458       writtenAliases.push_back(uWrite->get());
459   // Find the inner-most enclosing repetitive region of each alias. If this is
460   // the same region for every alias, save it in `repetitiveRegionOfWrites`.
461   Optional<Region *> repetitiveRegionOfWrites =
462       getCommonEnclosingRepetitiveRegion(writtenAliases);
463 
464   for (OpOperand *uRead : usesRead) {
465     Operation *readingOp = uRead->getOwner();
466 
467     // Find most recent writes of uRead by following the SSA use-def chain.
468     // E.g.:
469     //
470     // %0 = "writing_op"(%t) : tensor<?x32> -> tensor<?xf32>
471     // %1 = "aliasing_op"(%0) : tensor<?x32> -> tensor<?xf32>
472     // %2 = "reading_op"(%1) : : tensor<?x32> -> not_a_tensor_type
473     //
474     // In the above example, if uRead is the OpOperand of reading_op, lastWrite
475     // is %0. Note that operations that create an alias but do not write (such
476     // as ExtractSliceOp) are skipped.
477     SetVector<Value> lastWrites = state.findLastPrecedingWrite(uRead->get());
478 
479     // Look for conflicting memory writes. Potential conflicts are writes to an
480     // alias that have been decided to bufferize inplace.
481     for (OpOperand *uConflictingWrite : usesWrite) {
482       // Throughout this loop, check for multiple requirements that have to be
483       // met for uConflictingWrite to be an actual conflict.
484       Operation *conflictingWritingOp = uConflictingWrite->getOwner();
485 
486       // Check if conflictingWritingOp is in the same repetitive region as all
487       // written aliases. If this is not the case, there is no meaningful
488       // `happensBefore` relationship because conflictingWritingOp may be
489       // executed multiple times. E.g.:
490       //
491       // %0 = ... : tensor<?xf32>
492       // scf.for ... {
493       //   "reading_op"(%0) : tensor<?xf32>
494       //   %1 = "writing_op"(%0) : tensor<?xf32> -> tensor<?xf32>
495       //   ...
496       // }
497       //
498       // In the above example, reading_op happens before writing_op according to
499       // op dominance. However, both ops may happen multiple times; in
500       // particular, the second execution of reading_op happens after the first
501       // execution of writing_op. This is problematic if the tensor they operate
502       // on (%0) is defined outside of the loop.
503       //
504       // Counter example:
505       //
506       // scf.for ... {
507       //   %0 = ... : tensor<?xf32>
508       //   "reading_op"(%0) : tensor<?xf32>
509       //   %1 = "writing_op"(%0) : tensor<?xf32> -> tensor<?xf32>
510       //   ...
511       // }
512       //
513       // In this example, %0 is in the same repetitive region as
514       // conflictingWritingOp, so op dominance can be used to compute the
515       // `happensBefore` relationship.
516       //
517       // Note: iter_args of loops are not aliases of their respective block
518       // arguments, so op domanice can be used when analyzing ops that operate
519       // on them.
520       //
521       // Note: If `writtenAliases` is empty, there are no memory writes outside
522       // of the repetitive region of conflictingWritingOp, which means that all
523       // relevant aliases are inside the same repetitive region.
524       bool canUseOpDominance =
525           writtenAliases.empty() ||
526           repetitiveRegionOfWrites ==
527               getEnclosingRepetitiveRegion(conflictingWritingOp);
528 
529       // No conflict if the readingOp dominates conflictingWritingOp, i.e., the
530       // write is not visible when reading.
531       //
532       // Note: If ops are executed multiple times (e.g., because they are inside
533       //       a loop), there may be no meaningful `happensBefore` relationship.
534       if (canUseOpDominance &&
535           happensBefore(readingOp, conflictingWritingOp, domInfo))
536         continue;
537 
538       // No conflict if the reading use equals the use of the conflicting write.
539       // A use cannot conflict with itself.
540       //
541       // Note: Just being the same op is not enough. It has to be the same use.
542       // Note: If the op is executed multiple times (e.g., because it is inside
543       //       a loop), it may be conflicting with itself.
544       if (canUseOpDominance && uConflictingWrite == uRead)
545         continue;
546 
547       // No conflict if the op interface says so.
548       if (auto bufferizableOp = options.dynCastBufferizableOp(readingOp))
549         if (bufferizableOp.isNotConflicting(uRead, uConflictingWrite, state))
550           continue;
551 
552       if (conflictingWritingOp != readingOp)
553         if (auto bufferizableOp =
554                 options.dynCastBufferizableOp(conflictingWritingOp))
555           if (bufferizableOp.isNotConflicting(uRead, uConflictingWrite, state))
556             continue;
557 
558       // Ops are not conflicting if they are in mutually exclusive regions.
559       //
560       // Note: If ops are executed multiple times (e.g., because they are inside
561       //       a loop), mutually exclusive regions may be executed multiple
562       //       times.
563       if (canUseOpDominance &&
564           insideMutuallyExclusiveRegions(readingOp, conflictingWritingOp))
565         continue;
566 
567       // Check all possible last writes.
568       for (Value lastWrite : lastWrites) {
569         // No conflict if the conflicting write happens before the last
570         // write.
571         if (Operation *writingOp = lastWrite.getDefiningOp()) {
572           if (happensBefore(conflictingWritingOp, writingOp, domInfo))
573             // conflictingWritingOp happens before writingOp. No conflict.
574             continue;
575           // No conflict if conflictingWritingOp is contained in writingOp.
576           if (writingOp->isProperAncestor(conflictingWritingOp))
577             continue;
578         } else {
579           auto bbArg = lastWrite.cast<BlockArgument>();
580           Block *block = bbArg.getOwner();
581           if (!block->findAncestorOpInBlock(*conflictingWritingOp))
582             // conflictingWritingOp happens outside of the block. No
583             // conflict.
584             continue;
585         }
586 
587         // No conflict if the conflicting write and the last write are the same
588         // use.
589         SmallVector<OpResult> aliasingOpResult =
590             state.getAliasingOpResult(*uConflictingWrite);
591         if (aliasingOpResult.size() == 1 && aliasingOpResult[0] == lastWrite)
592           continue;
593 
594         // All requirements are met. Conflict found!
595 
596         if (options.printConflicts)
597           annotateConflict(uRead, uConflictingWrite, lastWrite);
598 
599         return true;
600       }
601     }
602   }
603 
604   return false;
605 }
606 
607 /// Return true if bufferizing `operand` inplace would create a conflict. A read
608 /// R and a write W of the same alias set is a conflict if inplace bufferization
609 /// of W changes the value read by R to a value different from the one that
610 /// would be expected by tracing back R's origin through SSA use-def chains.
611 /// A conflict can only be introduced by a new alias and/or an inplace
612 /// bufferization decision.
613 ///
614 /// Example:
615 /// %0 = tensor.extract_slice %t[...][...][1, 1] {inplace?}
616 /// %1 = vector.transfer_write %v1, %t {inplace} : vector<5xf32>, tensor<?xf32>
617 /// %e = tensor.extract_slice %1
618 /// %2 = vector.transfer_write %v2, %0 {inplace} : vector<6xf32>, tensor<?xf32>
619 /// %3 = vector.transfer_read %e, %cst : tensor<?xf32>, vector<7xf32>
620 ///
621 /// In the above example, the two TransferWriteOps have already been decided to
622 /// bufferize inplace. Bufferizing the ExtractSliceOp inplace would create a
623 /// conflict because:
624 /// * According to SSA use-def chains, we expect to read the result of %1.
625 /// * However, adding an alias {%0, %t} would mean that the second
626 ///   TransferWriteOp overwrites the first one. Therefore, the TransferReadOp
627 ///   would no longer be reading the result of %1.
628 ///
629 /// If `checkConsistencyOnly` is true, this function checks if there is a
630 /// read-after-write conflict without bufferizing `operand` inplace. This would
631 /// indicate a problem with the current inplace bufferization decisions.
632 ///
633 /// Note: If `checkConsistencyOnly`, this function may be called with a null
634 /// OpResult. In that case, only the consistency of bufferization decisions
635 /// involving aliases of the given OpOperand are checked.
636 static bool wouldCreateReadAfterWriteInterference(
637     OpOperand &operand, const DominanceInfo &domInfo, AnalysisState &state,
638     const BufferizationAliasInfo &aliasInfo,
639     bool checkConsistencyOnly = false) {
640   // Helper function to iterate on aliases of `root` and capture the reads.
641   auto getAliasingReads = [&](DenseSet<OpOperand *> &res, Value root) {
642     aliasInfo.applyOnAliases(root, [&](Value alias) {
643       for (auto &use : alias.getUses())
644         // Read to a value that aliases root.
645         if (state.bufferizesToMemoryRead(use))
646           res.insert(&use);
647     });
648   };
649 
650   // Helper function to iterate on aliases of `root` and capture the writes.
651   auto getAliasingInplaceWrites = [&](DenseSet<OpOperand *> &res, Value root) {
652     aliasInfo.applyOnAliases(root, [&](Value alias) {
653       for (auto &use : alias.getUses())
654         // Inplace write to a value that aliases root.
655         if (isInplaceMemoryWrite(use, aliasInfo, state))
656           res.insert(&use);
657     });
658   };
659 
660   // Collect reads and writes of all aliases of OpOperand and OpResult.
661   DenseSet<OpOperand *> usesRead, usesWrite;
662   getAliasingReads(usesRead, operand.get());
663   getAliasingInplaceWrites(usesWrite, operand.get());
664   for (OpResult result : state.getAliasingOpResult(operand)) {
665     getAliasingReads(usesRead, result);
666     getAliasingInplaceWrites(usesWrite, result);
667   }
668   if (!checkConsistencyOnly && state.bufferizesToMemoryWrite(operand))
669     usesWrite.insert(&operand);
670 
671   return hasReadAfterWriteInterference(usesRead, usesWrite, domInfo, state,
672                                        aliasInfo);
673 }
674 
675 /// Return true if bufferizing `opOperand` inplace would create a write to a
676 /// non-writable buffer.
677 static bool
678 wouldCreateWriteToNonWritableBuffer(OpOperand &opOperand,
679                                     const BufferizationAliasInfo &aliasInfo,
680                                     AnalysisState &state) {
681   // Certain buffers are not writeable:
682   //   1. A function bbArg that is not inplaceable or
683   //   2. A constant op.
684   bool nonWritable =
685       aliasesNonWritableBuffer(opOperand.get(), aliasInfo, state);
686   if (!nonWritable)
687     return false;
688 
689   // This is a problem only if the buffer is written to via some alias.
690   bool hasWrite = aliasesInPlaceWrite(opOperand.get(), aliasInfo, state) ||
691                   state.bufferizesToMemoryWrite(opOperand);
692 
693   for (OpResult opResult : state.getAliasingOpResult(opOperand))
694     hasWrite |= aliasesInPlaceWrite(opResult, aliasInfo, state);
695 
696   return hasWrite;
697 }
698 
699 //===----------------------------------------------------------------------===//
700 // Bufferization analyses.
701 //===----------------------------------------------------------------------===//
702 
703 /// Determine if `operand` can be bufferized in-place.
704 static LogicalResult bufferizableInPlaceAnalysisImpl(
705     OpOperand &operand, BufferizationAliasInfo &aliasInfo, AnalysisState &state,
706     const DominanceInfo &domInfo) {
707   bool foundInterference =
708       wouldCreateWriteToNonWritableBuffer(operand, aliasInfo, state) ||
709       wouldCreateReadAfterWriteInterference(operand, domInfo, state, aliasInfo);
710 
711   if (foundInterference)
712     aliasInfo.bufferizeOutOfPlace(operand);
713   else
714     aliasInfo.bufferizeInPlace(operand, state);
715 
716   return success();
717 }
718 
719 /// Analyze the `ops` to determine which OpOperands are inplaceable. Walk ops in
720 /// reverse and bufferize ops greedily. This is a good starter heuristic.
721 ///
722 /// Even if an op does not read or write, it may still create an alias when
723 /// bufferized in-place. An example of such ops is tensor.extract_slice.
724 ///
725 /// Rationale for bufferizing `%1 = tensor.extract_slice %0[...]` inplace:
726 ///
727 /// When bufferized out of place, an ExtractSliceOp lowers to alloc + copy. This
728 /// cannot change the flow of information for either the source or the
729 /// result buffers.
730 ///
731 /// When bufferized inplace, an ExtractSliceOp does not by itself create any
732 /// read or write from memory. Instead, it has the effect of merging the alias
733 /// sets of the source and the result buffers.
734 ///
735 /// An analysis is required to ensure inplace bufferization would not result in
736 /// RaW dependence violations.
737 static LogicalResult inPlaceAnalysis(SmallVector<Operation *> &ops,
738                                      BufferizationAliasInfo &aliasInfo,
739                                      AnalysisState &state,
740                                      const DominanceInfo &domInfo,
741                                      unsigned analysisFuzzerSeed = 0) {
742   if (analysisFuzzerSeed) {
743     // This is a fuzzer. For testing purposes only. Randomize the order in which
744     // operations are analyzed. The bufferization quality is likely worse, but
745     // we want to make sure that no assertions are triggered anywhere.
746     std::mt19937 g(analysisFuzzerSeed);
747     llvm::shuffle(ops.begin(), ops.end(), g);
748   }
749 
750   // Walk ops in reverse for better interference analysis.
751   for (Operation *op : reverse(ops))
752     for (OpOperand &opOperand : op->getOpOperands())
753       if (opOperand.get().getType().isa<TensorType>())
754         if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op))
755           if (failed(bufferizableInPlaceAnalysisImpl(opOperand, aliasInfo,
756                                                      state, domInfo)))
757             return failure();
758 
759   return success();
760 }
761 
762 /// Return true if the given op has a tensor result or a tensor operand.
763 static bool hasTensorSemantics(Operation *op) {
764   bool hasTensorResult = any_of(op->getResultTypes(), isaTensor);
765   bool hasTensorOperand = any_of(op->getOperandTypes(), isaTensor);
766   return hasTensorResult || hasTensorOperand;
767 }
768 
769 /// Analyze all ops that are contained in `op`.
770 static LogicalResult inPlaceAnalysis(Operation *op,
771                                      BufferizationAliasInfo &aliasInfo,
772                                      AnalysisState &state,
773                                      const DominanceInfo &domInfo,
774                                      unsigned analysisFuzzerSeed = 0) {
775   // Collect ops so we can build our own reverse traversal.
776   SmallVector<Operation *> ops;
777   op->walk([&](Operation *op) {
778     // No tensors => no buffers.
779     if (!hasTensorSemantics(op))
780       return;
781     ops.push_back(op);
782   });
783 
784   return inPlaceAnalysis(ops, aliasInfo, state, domInfo, analysisFuzzerSeed);
785 }
786 
787 /// Analyze equivalence of tied OpResult/OpOperand pairs of the given ops.
788 static void equivalenceAnalysis(SmallVector<Operation *> &ops,
789                                 BufferizationAliasInfo &aliasInfo,
790                                 AnalysisState &state) {
791   for (Operation *op : ops)
792     if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op))
793       for (OpResult opResult : op->getOpResults())
794         if (opResult.getType().isa<TensorType>())
795           for (OpOperand *opOperand :
796                bufferizableOp.getAliasingOpOperand(opResult, state))
797             if (state.isInPlace(*opOperand))
798               if (bufferizableOp.bufferRelation(opResult, state) ==
799                   BufferRelation::Equivalent)
800                 aliasInfo.unionEquivalenceClasses(opResult, opOperand->get());
801 }
802 
803 /// Analyze equivalence of tied OpResult/OpOperand pairs of all ops contained
804 /// in `op`.
805 static void equivalenceAnalysis(Operation *op,
806                                 BufferizationAliasInfo &aliasInfo,
807                                 AnalysisState &state) {
808   // Traverse ops in PostOrder: Nested ops first, then enclosing ops.
809   SmallVector<Operation *> ops;
810   op->walk<WalkOrder::PostOrder>([&](Operation *op) {
811     // No tensors => no buffers.
812     if (none_of(op->getResultTypes(), isaTensor))
813       return;
814     ops.push_back(op);
815   });
816 
817   equivalenceAnalysis(ops, aliasInfo, state);
818 }
819 
820 /// Assert that the current bufferization decisions are consistent.
821 static LogicalResult
822 checkAliasInfoConsistency(Operation *op, const DominanceInfo &domInfo,
823                           AnalysisState &state,
824                           const BufferizationAliasInfo &aliasInfo) {
825   const BufferizationOptions &options = state.getOptions();
826   Operation *inconsistentOp = nullptr;
827   WalkResult walkResult = op->walk([&](Operation *op) {
828     if (auto bufferizableOp = options.dynCastBufferizableOp(op))
829       for (OpOperand &opOperand : op->getOpOperands())
830         if (opOperand.get().getType().isa<TensorType>()) {
831           if (wouldCreateReadAfterWriteInterference(
832                   opOperand, domInfo, state, aliasInfo,
833                   /*checkConsistencyOnly=*/true)) {
834             // This error can happen if certain "mustBufferizeInPlace" interface
835             // methods are implemented incorrectly, such that the IR already has
836             // a RaW conflict before making any bufferization decisions.
837             inconsistentOp = op;
838             return WalkResult::interrupt();
839           }
840         }
841     return WalkResult::advance();
842   });
843 
844   if (walkResult.wasInterrupted())
845     return inconsistentOp->emitError("input IR has RaW conflict");
846   return success();
847 }
848 
849 /// Annotate the IR with the result of the analysis. For testing/debugging only.
850 static void
851 annotateOpsWithBufferizationMarkers(Operation *op,
852                                     const BufferizationAliasInfo &aliasInfo,
853                                     AnalysisState &state) {
854   op->walk([&](Operation *op) {
855     if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op))
856       for (OpOperand &opOperand : op->getOpOperands())
857         if (opOperand.get().getType().isa<TensorType>())
858           setInPlaceOpOperand(opOperand, aliasInfo.isInPlace(opOperand));
859   });
860 }
861 
862 /// Assert that IR is in destination-passing style. I.e., every value that is
863 /// returned or yielded from a block is:
864 /// * aliasing a bbArg of that block or a parent block, or
865 /// * aliasing an OpResult of a op in a parent block.
866 ///
867 /// Example:
868 /// ```
869 /// %0 = "some_op" : tensor<?xf32>
870 /// %1 = scf.if %c -> (tensor<?xf32>) {
871 ///   scf.yield %0 : tensor<?xf32>
872 /// } else {
873 ///   %t = linalg.alloc_tensor : tensor<?xf32>
874 ///   scf.yield %t : tensor<?xf32>
875 /// }
876 /// ```
877 /// In the above example, the first scf.yield op satifies destination-passing
878 /// style because the yielded value %0 is defined in the parent block. The
879 /// second scf.yield op does not satisfy destination-passing style because the
880 /// yielded value %t is defined in the same block as the scf.yield op.
881 // TODO: The current implementation checks for equivalent values instead of
882 // aliasing values, which is stricter than needed. We can currently not check
883 // for aliasing values because the analysis is a maybe-alias analysis and we
884 // need a must-alias analysis here.
885 static LogicalResult
886 assertDestinationPassingStyle(Operation *op, AnalysisState &state,
887                               BufferizationAliasInfo &aliasInfo,
888                               SmallVector<Operation *> &newOps) {
889   LogicalResult status = success();
890   DominanceInfo domInfo(op);
891   op->walk([&](Operation *returnOp) {
892     if (!isRegionReturnLike(returnOp) ||
893         !state.getOptions().isOpAllowed(returnOp))
894       return WalkResult::advance();
895 
896     for (OpOperand &returnValOperand : returnOp->getOpOperands()) {
897       Value returnVal = returnValOperand.get();
898       // Skip non-tensor values.
899       if (!returnVal.getType().isa<TensorType>())
900         continue;
901 
902       bool foundEquivValue = false;
903       aliasInfo.applyOnEquivalenceClass(returnVal, [&](Value equivVal) {
904         if (auto bbArg = equivVal.dyn_cast<BlockArgument>()) {
905           Operation *definingOp = bbArg.getOwner()->getParentOp();
906           if (definingOp->isProperAncestor(returnOp))
907             foundEquivValue = true;
908           return;
909         }
910 
911         Operation *definingOp = equivVal.getDefiningOp();
912         if (definingOp->getBlock()->findAncestorOpInBlock(
913                 *returnOp->getParentOp()))
914           // Skip ops that happen after `returnOp` and parent ops.
915           if (happensBefore(definingOp, returnOp, domInfo))
916             foundEquivValue = true;
917       });
918 
919       if (!foundEquivValue)
920         status =
921             returnOp->emitError()
922             << "operand #" << returnValOperand.getOperandNumber()
923             << " of ReturnLike op does not satisfy destination passing style";
924     }
925 
926     return WalkResult::advance();
927   });
928 
929   return status;
930 }
931 
932 LogicalResult bufferization::analyzeOp(Operation *op,
933                                        OneShotAnalysisState &state) {
934   DominanceInfo domInfo(op);
935   BufferizationAliasInfo &aliasInfo = state.getAliasInfo();
936   const auto &options =
937       static_cast<const OneShotBufferizationOptions &>(state.getOptions());
938 
939   // Catch incorrect API usage.
940   assert((state.hasDialectState(func::FuncDialect::getDialectNamespace()) ||
941           !options.bufferizeFunctionBoundaries) &&
942          "must use ModuleBufferize to bufferize function boundaries");
943 
944   if (failed(checkAliasInfoConsistency(op, domInfo, state, aliasInfo)))
945     return failure();
946 
947   // If the analysis fails, just return.
948   if (failed(inPlaceAnalysis(op, aliasInfo, state, domInfo,
949                              options.analysisFuzzerSeed)))
950     return failure();
951   equivalenceAnalysis(op, aliasInfo, state);
952 
953   bool failedAnalysis = false;
954   if (!options.allowReturnAllocs) {
955     SmallVector<Operation *> newOps;
956     failedAnalysis |=
957         failed(assertDestinationPassingStyle(op, state, aliasInfo, newOps));
958   }
959 
960   // Gather some extra analysis data.
961   state.gatherYieldedTensors(op);
962   state.gatherUndefinedTensorUses(op);
963 
964   // Analysis verification: After setting up alias/equivalence sets, each op
965   // can check for expected invariants/limitations and fail the analysis if
966   // necessary.
967   op->walk([&](Operation *op) {
968     if (BufferizableOpInterface bufferizableOp =
969             options.dynCastBufferizableOp(op))
970       failedAnalysis |= failed(bufferizableOp.verifyAnalysis(state));
971   });
972 
973   // Annotate operations if we only want to report the analysis.
974   if (options.testAnalysisOnly)
975     annotateOpsWithBufferizationMarkers(op, aliasInfo, state);
976 
977   return success(!failedAnalysis);
978 }
979 
980 LogicalResult
981 bufferization::runOneShotBufferize(Operation *op,
982                                    const OneShotBufferizationOptions &options) {
983   OneShotAnalysisState state(op, options);
984   if (failed(analyzeOp(op, state)))
985     return failure();
986   if (options.testAnalysisOnly)
987     return success();
988   return bufferizeOp(op, state);
989 }
990