MLIR 23.0.0git
OneShotAnalysis.cpp
Go to the documentation of this file.
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. By default, function boundaries
10// (FuncOp bbArgs, CallOps, ReturnOps) are treated as "unknown" ops.
11// OneShotModuleBufferization.cpp is an extension of One-Shot Analysis for
12// simple call graphs without loops.
13//
14// One-Shot Bufferize consists of three phases.
15//
16// 1. Analyze ops to decide which OpOperands can bufferize inplace, i.e.,
17// without inserting buffer copies. The analysis queries op bufferization
18// semantics via `BufferizableOpInterface`.
19// 2. Insert copies for OpOperands that were decided to bufferize out-of-place
20// in tensor land during `TensorCopyInsertion`.
21// 3. Bufferize ops by calling `BufferizableOpInterface::bufferize`.
22//
23// This file contains only the analysis. For convenience, this file also
24// contains a helper function `runOneShotBufferize` that analyzes an op (and its
25// nested ops) and then bufferizes it.
26//
27// Inplace bufferization decisions are passed from the analysis to the
28// `TensorCopyInsertion` phase via `AnalysisState`. They can be printed for
29// debugging purposes with `testAnalysisOnly`.
30//
31// Ops that do not implement `BufferizableOpInterface` can be analyzed but are
32// treated conservatively. E.g., the analysis has to assume that their tensor
33// OpOperands bufferize to memory writes. While such ops can be analyzed, they
34// are not bufferized and remain in the IR. to_tensor and to_buffer ops are
35// inserted at the bufferization boundary.
36//
37// This analysis caters to high-performance codegen where buffer reuse is deemed
38// critical: the analysis should fail if the bufferized form of the function
39// needs to return a buffer, unless `allowReturnAllocs` is enabled.
40
42
43#include <random>
44
50#include "mlir/IR/AsmState.h"
51#include "mlir/IR/Dominance.h"
52#include "mlir/IR/Iterators.h"
53#include "mlir/IR/Operation.h"
57#include "llvm/ADT/DenseSet.h"
58#include "llvm/ADT/SetVector.h"
59#include "llvm/Support/DebugLog.h"
60
62
63// Run mlir-opt with `-debug-only="one-shot-analysis"` for detailed debug
64// output.
65#define DEBUG_TYPE "one-shot-analysis"
66
67using namespace mlir;
68using namespace mlir::bufferization;
69
70static bool isaTensor(Type t) { return isa<TensorType>(t); }
71
72//===----------------------------------------------------------------------===//
73// Bufferization-specific attribute manipulation.
74// These are for testing and debugging only. Bufferization information is stored
75// in OneShotBufferizationState. When run with `testAnalysisOnly`, the IR is
76// annotated with the results of the analysis, so that they can be checked in
77// tests.
78//===----------------------------------------------------------------------===//
79
80/// Attribute marker to specify op operands that bufferize in-place.
81constexpr StringLiteral kInPlaceOperandsAttrName = "__inplace_operands_attr__";
82
83constexpr StringLiteral kOpResultAliasSetAttrName =
84 "__opresult_alias_set_attr__";
85
86constexpr StringLiteral kBbArgAliasSetAttrName = "__bbarg_alias_set_attr__";
87
88/// Mark whether OpOperand will be bufferized inplace.
89static void setInPlaceOpOperand(OpOperand &opOperand, bool inPlace) {
90 Operation *op = opOperand.getOwner();
91 SmallVector<StringRef> inPlaceVector;
92 if (auto attr = op->getAttr(kInPlaceOperandsAttrName)) {
93 inPlaceVector = SmallVector<StringRef>(llvm::to_vector<4>(
94 cast<ArrayAttr>(attr).getAsValueRange<StringAttr>()));
95 // The existing attribute may have fewer entries than the current operand
96 // count (e.g., when user-provided annotations are inconsistent with the
97 // op's actual operand count). Resize to avoid an out-of-bounds access.
98 if (inPlaceVector.size() < op->getNumOperands())
99 inPlaceVector.resize(op->getNumOperands(), "none");
100 } else {
101 inPlaceVector = SmallVector<StringRef>(op->getNumOperands(), "none");
102 for (OpOperand &opOperand : op->getOpOperands())
103 if (isa<TensorType>(opOperand.get().getType()))
104 inPlaceVector[opOperand.getOperandNumber()] = "false";
105 }
106 inPlaceVector[opOperand.getOperandNumber()] = inPlace ? "true" : "false";
108 OpBuilder(op).getStrArrayAttr(inPlaceVector));
109}
110
111//===----------------------------------------------------------------------===//
112// OneShotAnalysisState
113//===----------------------------------------------------------------------===//
114
118 // Set up alias sets.
119 op->walk([&](Operation *op) {
120 for (Value v : op->getResults())
121 if (isa<TensorType>(v.getType()))
123 for (Region &r : op->getRegions())
124 for (Block &b : r.getBlocks())
125 for (auto bbArg : b.getArguments())
126 if (isa<TensorType>(bbArg.getType()))
128 });
129
130 // Mark OpOperands in-place that must bufferize in-place.
131 op->walk([&](BufferizableOpInterface bufferizableOp) {
132 if (!options.isOpAllowed(bufferizableOp))
133 return WalkResult::skip();
134 for (OpOperand &opOperand : bufferizableOp->getOpOperands())
135 if (isa<TensorType>(opOperand.get().getType()))
136 if (bufferizableOp.mustBufferizeInPlace(opOperand, *this))
137 bufferizeInPlace(opOperand);
138 return WalkResult::advance();
139 });
140}
141
143 Value v, function_ref<void(Value)> fun) const {
144 auto leaderIt = equivalentInfo.findLeader(v);
145 for (auto mit = leaderIt, meit = equivalentInfo.member_end(); mit != meit;
146 ++mit) {
147 fun(*mit);
148 }
149}
150
152 function_ref<void(Value)> fun) const {
153 auto leaderIt = aliasInfo.findLeader(v);
154 for (auto mit = leaderIt, meit = aliasInfo.member_end(); mit != meit; ++mit) {
155 fun(*mit);
156 }
157}
158
160 Value v2) const {
161 return equivalentInfo.isEquivalent(v1, v2);
162}
163
165 Value v2) const {
166 return aliasInfo.isEquivalent(v1, v2);
167}
168
170 if (inplaceBufferized.contains(&operand))
171 return;
172 inplaceBufferized.insert(&operand);
173 for (AliasingValue alias : getAliasingValues(operand))
174 aliasInfo.unionSets(alias.value, operand.get());
175 ++statNumTensorInPlace;
176}
177
179 assert(!inplaceBufferized.contains(&operand) &&
180 "OpOperand was already decided to bufferize inplace");
181 ++statNumTensorOutOfPlace;
182}
183
185 aliasInfo.insert(v);
186 equivalentInfo.insert(v);
187}
188
190 op->walk([&](Operation *op) {
191 // Skip unknown ops.
192 auto bufferizableOp = getOptions().dynCastBufferizableOp(op);
193 if (!bufferizableOp)
194 return WalkResult::skip();
195
196 // Check all tensor OpResults.
197 for (OpResult opResult : op->getOpResults()) {
198 if (!isa<TensorType>(opResult.getType()))
199 continue;
200
201 // If there is no preceding definition, the tensor contents are
202 // undefined.
203 if (opResult.getUses().empty())
204 continue;
205 // It does not really matter which use to take to search about
206 // the value's definitions.
207 OpOperand *opOperand = &(*opResult.getUses().begin());
208 if (findDefinitionsCached(opOperand).empty())
209 for (OpOperand &use : opResult.getUses())
210 undefinedTensorUses.insert(&use);
211 }
212
213 return WalkResult::advance();
214 });
215}
216
218 return undefinedTensorUses.contains(opOperand);
219}
220
222 return inplaceBufferized.contains(&opOperand);
223}
224
226 bool isWritten = false;
227 applyOnAliases(value, [&](Value val) {
228 for (OpOperand &use : val.getUses())
229 if (isInPlace(use) && bufferizesToMemoryWrite(use))
230 isWritten = true;
231 });
232 return isWritten;
233}
234
236 // TODO: Out-of-place bufferized value could be considered writable.
237 // Query BufferizableOpInterface to see if the BlockArgument is writable.
238 if (auto bufferizableOp =
239 getOptions().dynCastBufferizableOp(getOwnerOfValue(value)))
240 return bufferizableOp.isWritable(value, *this);
241
242 // Not a bufferizable op: The conservative answer is "not writable".
243 return false;
244}
245
247 aliasInfo.unionSets(v1, v2);
248}
249
251 equivalentInfo.unionSets(v1, v2);
252}
253
255
256//===----------------------------------------------------------------------===//
257// Bufferization-specific alias analysis.
258//===----------------------------------------------------------------------===//
259
260/// Return true if opOperand has been decided to bufferize in-place.
261static bool isInplaceMemoryWrite(OpOperand &opOperand,
262 const OneShotAnalysisState &state) {
263 // OpOperands that do not bufferize to a memory write do not write in-place.
264 if (!state.bufferizesToMemoryWrite(opOperand))
265 return false;
266 // Check current bufferization decisions.
267 return state.isInPlace(opOperand);
268}
269
270/// Return true if `a` happens before `b`, i.e., `a` or one of its ancestors
271/// properly dominates `b` and `b` is not inside `a`.
273 const DominanceInfo &domInfo) {
274 do {
275 // TODO: Instead of isProperAncestor + properlyDominates, we should use
276 // properlyDominatesImpl(a, b, /*enclosingOpOk=*/false)
277 if (a->isProperAncestor(b))
278 return false;
279 if (domInfo.properlyDominates(a, b))
280 return true;
281 } while ((a = a->getParentOp()));
282 return false;
283}
284
285/// Return `true` if op dominance can be used to rule out a read-after-write
286/// conflicts based on the ordering of ops. Returns `false` if op dominance
287/// cannot be used to due region-based loops.
288///
289/// Generalized op dominance can often be used to rule out potential conflicts
290/// due to "read happens before write". E.g., the following IR is not a RaW
291/// conflict because the read happens *before* the write.
292///
293/// Example 1:
294/// %0 = ... : tensor<?xf32> // DEF
295/// "reading_op"(%0) : tensor<?xf32> // READ
296/// %1 = "writing_op"(%0) : tensor<?xf32> -> tensor<?xf32> // WRITE
297///
298/// This is no longer true inside loops (or repetitive regions). In such cases,
299/// there may not be a meaningful `happensBefore` relationship because ops
300/// could be executed multiple times. E.g.:
301///
302/// Example 2:
303/// %0 = ... : tensor<?xf32> // DEF
304/// scf.for ... {
305/// "reading_op"(%0) : tensor<?xf32> // READ
306/// %1 = "writing_op"(%0) : tensor<?xf32> -> tensor<?xf32> // WRITE
307/// ...
308/// }
309///
310/// In the above example, reading_op happens before writing_op according to
311/// op dominance. However, both ops may happen multiple times; in
312/// particular, the second execution of reading_op happens after the first
313/// execution of writing_op. This is problematic because the tensor %0 they
314/// operate on (i.e., the "definition") is defined outside of the loop.
315///
316/// On a high-level, there is a potential RaW in a program if there exists a
317/// possible program execution such that there is a sequence of DEF, followed
318/// by WRITE, followed by READ. Each additional DEF resets the sequence.
319///
320/// E.g.:
321/// No conflict: DEF, WRITE, DEF, READ
322/// Potential conflict: DEF, READ, WRITE, READ, WRITE
323///
324/// Example 1 has no conflict: DEF, READ, WRITE
325/// Example 2 has a potential conflict: DEF, (READ, WRITE)*
326//
327/// Example 3:
328/// scf.for ... {
329/// %0 = ... : tensor<?xf32>
330/// "reading_op"(%0) : tensor<?xf32>
331/// %1 = "writing_op"(%0) : tensor<?xf32> -> tensor<?xf32>
332/// ...
333/// }
334/// This has no conflict: (DEF, READ, WRITE)*
335///
336/// Example 4:
337/// %0 = ... : tensor<?xf32>
338/// scf.for ... {
339/// scf.for ... { "reading_op"(%0) }
340/// %1 = "writing_op"(%0)
341/// }
342/// This has a potential conflict: DEF, ((READ)*, WRITE)*
343///
344/// Example 5:
345/// %0 = ... : tensor<?xf32>
346/// scf.for ... { %1 = "writing_op"(%0) }
347/// scf.for ... { "reading_op"(%0) }
348/// This has a potential conflict: DEF, WRITE*, READ*
349///
350/// The following rules are used to rule out RaW conflicts via ordering of ops:
351///
352/// 1. If the closest enclosing repetitive region of DEF is a proper ancestor of
353/// a repetitive region that enclosing both READ and WRITE, we cannot rule
354/// out RaW conflict due to the ordering of ops.
355/// 2. Otherwise: There are no loops that interfere with our analysis; for
356/// analysis purposes, we can assume that there are no loops/repetitive
357/// regions. I.e., we can rule out a RaW conflict if READ happensBefore WRITE
358/// or WRITE happensBefore DEF. (Checked in `hasReadAfterWriteInterference`.)
359///
361 const SetVector<Value> &definitions,
362 AnalysisState &state) {
363 const BufferizationOptions &options = state.getOptions();
364 for (Value def : definitions) {
365 Region *rRead =
366 state.getEnclosingRepetitiveRegion(uRead->getOwner(), options);
367 Region *rDef = state.getEnclosingRepetitiveRegion(def, options);
368
369 // READ and DEF are in the same repetitive region. `happensBefore` can be
370 // used to rule out RaW conflicts due to op ordering.
371 if (rRead == rDef)
372 continue;
373
374 // Find the enclosing repetitive region of READ that is closest to DEF but
375 // not the repetitive region of DEF itself.
376 while (true) {
377 Region *nextRegion = getNextEnclosingRepetitiveRegion(rRead, options);
378 if (nextRegion == rDef)
379 break;
380 assert(nextRegion && "expected to find another repetitive region");
381 rRead = nextRegion;
382 }
383
384 // We cannot use op dominance if WRITE is inside the same repetitive region.
385 if (rRead->getParentOp()->isAncestor(uWrite->getOwner()))
386 return false;
387 }
388
389 return true;
390}
391
392/// Return `true` if op dominance can be used to rule out a read-after-write
393/// conflicts based on the ordering of ops. Returns `false` if op dominance
394/// cannot be used to due block-based loops within a region.
395///
396/// Refer to the `canUseOpDominanceDueToRegions` documentation for details on
397/// how op domiance is used during RaW conflict detection.
398///
399/// On a high-level, there is a potential RaW in a program if there exists a
400/// possible program execution such that there is a sequence of DEF, followed
401/// by WRITE, followed by READ. Each additional DEF resets the sequence.
402///
403/// Op dominance cannot be used if there is a path from block(READ) to
404/// block(WRITE) and a path from block(WRITE) to block(READ). block(DEF) should
405/// not appear on that path.
407 const SetVector<Value> &definitions,
408 AnalysisState &state) {
409 // Fast path: If READ and WRITE are in different regions, their block cannot
410 // be reachable just via unstructured control flow. (Loops due to regions are
411 // covered by `canUseOpDominanceDueToRegions`.)
412 if (uRead->getOwner()->getParentRegion() !=
413 uWrite->getOwner()->getParentRegion())
414 return true;
415
416 Block *readBlock = uRead->getOwner()->getBlock();
417 Block *writeBlock = uWrite->getOwner()->getBlock();
418 for (Value def : definitions) {
419 Block *defBlock = def.getParentBlock();
420 if (readBlock->isReachable(writeBlock, {defBlock}) &&
421 writeBlock->isReachable(readBlock, {defBlock}))
422 return false;
423 }
424
425 return true;
426}
427
428static bool canUseOpDominance(OpOperand *uRead, OpOperand *uWrite,
429 const SetVector<Value> &definitions,
430 AnalysisState &state) {
431 return canUseOpDominanceDueToRegions(uRead, uWrite, definitions, state) &&
432 canUseOpDominanceDueToBlocks(uRead, uWrite, definitions, state);
433}
434
435/// Annotate IR with details about the detected RaW conflict.
436static void annotateConflict(OpOperand *uRead, OpOperand *uConflictingWrite,
437 Value definition) {
438 static uint64_t counter = 0;
439 Operation *readingOp = uRead->getOwner();
440 Operation *conflictingWritingOp = uConflictingWrite->getOwner();
441
442 OpBuilder b(conflictingWritingOp->getContext());
443 std::string id = "C_" + std::to_string(counter++);
444
445 std::string conflictingWriteAttr =
446 id +
447 "[CONFL-WRITE: " + std::to_string(uConflictingWrite->getOperandNumber()) +
448 "]";
449 conflictingWritingOp->setAttr(conflictingWriteAttr, b.getUnitAttr());
450
451 std::string readAttr =
452 id + "[READ: " + std::to_string(uRead->getOperandNumber()) + "]";
453 readingOp->setAttr(readAttr, b.getUnitAttr());
454
455 if (auto opResult = dyn_cast<OpResult>(definition)) {
456 std::string defAttr =
457 id + "[DEF: result " + std::to_string(opResult.getResultNumber()) + "]";
458 opResult.getDefiningOp()->setAttr(defAttr, b.getUnitAttr());
459 } else {
460 auto bbArg = cast<BlockArgument>(definition);
461 std::string defAttr =
462 id + "[DEF: bbArg " + std::to_string(bbArg.getArgNumber()) + "]";
463 bbArg.getOwner()->getParentOp()->setAttr(defAttr, b.getUnitAttr());
464 }
465}
466
467/// Return 'true' if a tensor that is equivalent to `other` can be found in the
468/// reverse use-def chain of `start`. Note: If an OpOperand bufferizes out of
469/// place along that use-def chain, the two tensors may not materialize as
470/// equivalent buffers (but separate allocations).
471///
472/// Note: This function also requires that the two tensors have equivalent
473/// indexing. I.e., the tensor types do not change along the use-def chain,
474/// apart from static <-> dynamic dim casts.
476 OpOperand *start,
477 Value other) {
478 TraversalConfig config;
479 config.followEquivalentOnly = true;
480 config.alwaysIncludeLeaves = false;
481 config.followSameTypeOrCastsOnly = true;
482 return !state
483 .findValueInReverseUseDefChain(
484 start, [&](Value v) { return v == other; }, config)
485 .empty();
486}
487
488/// Return "true" if the given operand's value is originating from a subset
489/// that is equivalent to the subset that `subsetOp` inserts into.
491 OpOperand *opOperand,
492 SubsetInsertionOpInterface subsetOp) {
493 auto matchingSubset = [&](Value val) {
494 if (auto opResult = dyn_cast<OpResult>(val))
495 if (subsetOp.isEquivalentSubset(opResult, [&](Value v1, Value v2) {
496 return state.areEquivalentBufferizedValues(v1, v2);
497 }))
498 return true;
499 return false;
500 };
501 // There may be multiple leaves at which the reverse SSA use-def chain lookup
502 // terminates. All of them must be equivalent subsets.
503 SetVector<Value> backwardSlice =
504 state.findValueInReverseUseDefChain(opOperand, matchingSubset);
505 return llvm::all_of(backwardSlice, matchingSubset);
506}
507
508/// Return "true" if the given "read" and potentially conflicting "write" are
509/// not conflicting due to their subset relationship. The comments in this
510/// function are expressed in terms of tensor.extract_slice/tensor.insert_slice
511/// pairs, but apply to any subset ops that implement the
512/// `SubsetInsertionOpInterface`.
514 OpOperand *uConflictingWrite,
515 const AnalysisState &state) {
516 Operation *readingOp = uRead->getOwner();
517 Operation *conflictingWritingOp = uConflictingWrite->getOwner();
518
519 // Special rules for matching ExtractSliceOp/InsertSliceOp pairs. If
520 // uRead is an InsertSliceOp...
521 if (auto subsetOp = dyn_cast<SubsetInsertionOpInterface>(readingOp)) {
522 // As an example, consider the following IR.
523 //
524 // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
525 // %1 = linalg.fill %cst, %0 {inplace= [true] }
526 // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
527 // {inplace= [true] }
528
529 if (uRead == &subsetOp.getDestinationOperand() &&
530 matchesInsertDestination(state, uConflictingWrite, subsetOp))
531 // Case 1: The main insight is that InsertSliceOp reads only part of
532 // the destination tensor. The overwritten area is not read. If
533 // uConflictingWrite writes into exactly the memory location that is
534 // being read by uRead, this is not a conflict.
535 //
536 // In the above example:
537 // uRead = OpOperand 1 (%t) of tensor.insert_slice
538 // uConflictingWrite = OpOperand 1 (%0) of linalg.fill
539 //
540 // The read of %t does not conflict with the write of the FillOp
541 // (same aliases!) because the area that the FillOp operates on is
542 // exactly the one that is *not* read via %t.
543 return true;
544
545 if (uRead == &subsetOp.getSourceOperand() &&
546 uConflictingWrite == &subsetOp.getDestinationOperand() &&
547 matchesInsertDestination(state, uRead, subsetOp))
548 // Case 2: The read of the source tensor and the write to the dest
549 // tensor via an InsertSliceOp is not a conflict if the read is
550 // reading exactly that part of an equivalent tensor that the
551 // InsertSliceOp is writing.
552 //
553 // In the above example:
554 // uRead = OpOperand 0 (%1) of tensor.insert_slice
555 // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
556 return true;
557 }
558
559 // If uConflictingWrite is an InsertSliceOp...
560 if (auto subsetOp =
561 dyn_cast<SubsetInsertionOpInterface>(conflictingWritingOp))
562 // As an example, consider the following IR.
563 //
564 // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
565 // %1 = linalg.fill %cst, %0 {inplace= [true] }
566 // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
567 // {inplace= [true] }
568 // %3 = vector.transfer_read %1, %cst
569 //
570 // In the above example:
571 // uRead = OpOperand 0 (%1) of vector.transfer_read
572 // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
573 // definition = %1
574 //
575 // This is not a conflict because the InsertSliceOp overwrites the
576 // memory segment of %1 with the exact same data. (Effectively, there
577 // is no memory write here.)
578 if (uConflictingWrite == &subsetOp.getDestinationOperand() &&
579 state.areEquivalentBufferizedValues(
580 uRead->get(), subsetOp.getSourceOperand().get()) &&
581 matchesInsertDestination(state, &subsetOp.getSourceOperand(), subsetOp))
582 return true;
583
584 return false;
585}
586
587/// Given sets of uses and writes, return true if there is a RaW conflict under
588/// the assumption that all given reads/writes alias the same buffer and that
589/// all given writes bufferize inplace.
590///
591/// A conflict is: According to SSA use-def chains, a read R is supposed to read
592/// the result of a definition W1. But because of bufferization decisions, R
593/// actually reads another definition W2.
594static bool
596 const DenseSet<OpOperand *> &usesWrite,
597 const DominanceInfo &domInfo,
598 OneShotAnalysisState &state) {
599 const BufferizationOptions &options = state.getOptions();
600
601 // Before going through the main RaW analysis, find cases where a buffer must
602 // be privatized due to parallelism. If the result of a write is never read,
603 // privatization is not necessary (and large parts of the IR are likely dead).
604 if (options.checkParallelRegions && !usesRead.empty()) {
605 for (OpOperand *uConflictingWrite : usesWrite) {
606 // Find the allocation point or last write (definition) of the buffer.
607 // Note: In contrast to `findDefinitions`, this also returns results of
608 // ops that do not bufferize to memory write when no other definition
609 // could be found. E.g., "bufferization.alloc_tensor" would be included,
610 // even though that op just bufferizes to an allocation but does define
611 // the contents of the buffer.
612 SetVector<Value> definitionsOrLeaves =
613 state.findValueInReverseUseDefChain(uConflictingWrite, [&](Value v) {
614 return state.bufferizesToMemoryWrite(v);
615 });
616 assert(!definitionsOrLeaves.empty() &&
617 "expected at least one definition or leaf");
618
619 // The writing op must bufferize out-of-place if the definition is in a
620 // different parallel region than this write.
621 for (Value def : definitionsOrLeaves) {
622 if (getParallelRegion(def.getParentRegion(), options) !=
623 getParallelRegion(uConflictingWrite->getOwner()->getParentRegion(),
624 options)) {
625 LDBG() << "\n- bufferizes out-of-place due to parallel region:\n"
626 << " unConflictingWrite = operand "
627 << uConflictingWrite->getOperandNumber() << " of "
628 << OpWithFlags(uConflictingWrite->getOwner(),
629 OpPrintingFlags().skipRegions());
630 return true;
631 }
632 }
633 }
634 }
635
636 for (OpOperand *uRead : usesRead) {
637 Operation *readingOp = uRead->getOwner();
638 LDBG() << "\n- check conflict:\n"
639 << " uRead = operand " << uRead->getOperandNumber() << " of "
640 << OpWithFlags(readingOp, OpPrintingFlags().skipRegions());
641
642 // Find the definition of uRead by following the SSA use-def chain.
643 // E.g.:
644 //
645 // %0 = "writing_op"(%t) : tensor<?x32> -> tensor<?xf32>
646 // %1 = "aliasing_op"(%0) : tensor<?x32> -> tensor<?xf32>
647 // %2 = "reading_op"(%1) : : tensor<?x32> -> not_a_tensor_type
648 //
649 // In the above example, if uRead is the OpOperand of reading_op, the
650 // definition is %0. Note that operations that create an alias but do not
651 // bufferize to a memory write (such as ExtractSliceOp) are skipped.
652 const SetVector<Value> &definitions = state.findDefinitionsCached(uRead);
653 if (definitions.empty()) {
654 // Fast path: No conflict if there are no definitions.
655 LDBG() << " no conflict: read value has no definitions";
656 continue;
657 }
658
659 // Look for conflicting memory writes. Potential conflicts are writes to an
660 // alias that have been decided to bufferize inplace.
661 for (OpOperand *uConflictingWrite : usesWrite) {
662 LDBG() << " unConflictingWrite = operand "
663 << uConflictingWrite->getOperandNumber() << " of "
664 << OpWithFlags(uConflictingWrite->getOwner(),
665 OpPrintingFlags().skipRegions());
666
667 // Check if op dominance can be used to rule out read-after-write
668 // conflicts.
669 bool useDominance =
670 canUseOpDominance(uRead, uConflictingWrite, definitions, state);
671 LDBG() << "\n- useDominance = " << useDominance;
672
673 // Throughout this loop, check for multiple requirements that have to be
674 // met for uConflictingWrite to be an actual conflict.
675 Operation *conflictingWritingOp = uConflictingWrite->getOwner();
676
677 // Inside of repetitive regions, ops may be executed multiple times and op
678 // dominance cannot be used to rule out conflicts.
679 if (useDominance) {
680 // No conflict if the readingOp dominates conflictingWritingOp, i.e.,
681 // the write is not visible when reading.
682 //
683 // Note: If ops are executed multiple times (e.g., because they are
684 // inside a loop), there may be no meaningful `happensBefore`
685 // relationship.
686 if (happensBefore(readingOp, conflictingWritingOp, domInfo)) {
687 LDBG() << " no conflict: read happens before write";
688 continue;
689 }
690
691 // No conflict if the reading use equals the use of the conflicting
692 // write. A use cannot conflict with itself.
693 //
694 // Note: Just being the same op is not enough. It has to be the same
695 // use.
696 // Note: If the op is executed multiple times (e.g., because it is
697 // inside a loop), it may be conflicting with itself.
698 if (uConflictingWrite == uRead) {
699 LDBG() << " no conflict: read and write are same use";
700 continue;
701 }
702
703 // Ops are not conflicting if they are in mutually exclusive regions.
704 //
705 // Note: If ops are executed multiple times (e.g., because they are
706 // inside a loop), mutually exclusive regions may be executed
707 // multiple times.
708 if (state.insideMutuallyExclusiveRegions(readingOp,
709 conflictingWritingOp)) {
710 LDBG() << " no conflict: read and write are in "
711 "mutually exclusive regions";
712 continue;
713 }
714
715 // Two equivalent operands of the same op are not conflicting if the op
716 // bufferizes to element-wise access. I.e., all loads at a position
717 // happen before all stores to the same position.
718 if (conflictingWritingOp == readingOp) {
719 if (auto bufferizableOp = options.dynCastBufferizableOp(readingOp)) {
720 if (bufferizableOp.bufferizesToElementwiseAccess(
721 state, {uRead, uConflictingWrite})) {
723 state, uRead, uConflictingWrite->get()) ||
725 state, uConflictingWrite, uRead->get())) {
726 LDBG() << " no conflict: op bufferizes to element-wise access";
727 continue;
728 }
729 }
730 }
731 }
732 }
733
734 // No conflict if the operands are non-conflicting subsets.
735 if (areNonConflictingSubsets(uRead, uConflictingWrite, state)) {
736 LDBG() << " no conflict: non-conflicting subsets";
737 continue;
738 }
739
740 // No conflict if the op interface says so.
741 if (auto bufferizableOp = options.dynCastBufferizableOp(readingOp)) {
742 if (bufferizableOp.isNotConflicting(uRead, uConflictingWrite, state)) {
743 LDBG() << " no conflict: op interace of reading op says 'no'";
744 continue;
745 }
746 }
747
748 if (conflictingWritingOp != readingOp) {
749 if (auto bufferizableOp =
750 options.dynCastBufferizableOp(conflictingWritingOp)) {
751 if (bufferizableOp.isNotConflicting(uRead, uConflictingWrite,
752 state)) {
753 LDBG() << " no conflict: op interace of writing op says 'no'";
754 continue;
755 }
756 }
757 }
758
759 // Check all possible definitions.
760 for (Value definition : definitions) {
761 LDBG() << " * definition = " << definition;
762
763 // No conflict if the conflicting write happens before the definition.
764 if (Operation *defOp = definition.getDefiningOp()) {
765 if (happensBefore(conflictingWritingOp, defOp, domInfo)) {
766 // conflictingWritingOp happens before defOp. No conflict.
767 LDBG() << " no conflict: write happens before definition";
768 continue;
769 }
770 // No conflict if conflictingWritingOp is contained in defOp.
771 if (defOp->isProperAncestor(conflictingWritingOp)) {
772 LDBG() << " no conflict: write is contained in definition";
773 continue;
774 }
775 } else {
776 auto bbArg = cast<BlockArgument>(definition);
777 Block *block = bbArg.getOwner();
778 if (!block->findAncestorOpInBlock(*conflictingWritingOp)) {
779 LDBG() << " no conflict: definition is bbArg "
780 "and write happens outside of block";
781 // conflictingWritingOp happens outside of the block. No
782 // conflict.
783 continue;
784 }
785 }
786
787 // No conflict if the conflicting write and the definition are the same
788 // use.
789 AliasingValueList aliases = state.getAliasingValues(*uConflictingWrite);
790 if (aliases.getNumAliases() == 1 &&
791 aliases.getAliases()[0].value == definition) {
792 LDBG() << " no conflict: definition and write are same";
793 continue;
794 }
795
796 // All requirements are met. Conflict found!
797
798 if (options.printConflicts)
799 annotateConflict(uRead, uConflictingWrite, definition);
800 LDBG() << " => RaW CONFLICT FOUND";
801 return true;
802 }
803 }
804 }
805
806 return false;
807}
808
809// Helper function to iterate on aliases of `root` and capture the writes.
811 const OneShotAnalysisState &state) {
812 state.applyOnAliases(root, [&](Value alias) {
813 for (auto &use : alias.getUses())
814 // Inplace write to a value that aliases root.
815 if (isInplaceMemoryWrite(use, state))
816 res.insert(&use);
817 });
818}
819
820// Helper function to iterate on aliases of `root` and capture the reads.
822 const OneShotAnalysisState &state) {
823 state.applyOnAliases(root, [&](Value alias) {
824 for (auto &use : alias.getUses()) {
825 // Read of a value that aliases root.
826 if (state.bufferizesToMemoryRead(use)) {
827 res.insert(&use);
828 continue;
829 }
830
831 // Read of a dependent value in the SSA use-def chain. E.g.:
832 //
833 // %0 = ...
834 // %1 = tensor.extract_slice %0 {not_analyzed_yet}
835 // "read"(%1)
836 //
837 // In the above example, getAliasingReads(%0) includes the first OpOperand
838 // of the tensor.extract_slice op. The extract_slice itself does not read
839 // but its aliasing result is eventually fed into an op that does.
840 //
841 // Note: This is considered a "read" only if the use does not bufferize to
842 // a memory write. (We already ruled out memory reads. In case of a memory
843 // write, the buffer would be entirely overwritten; in the above example
844 // there would then be no flow of data from the extract_slice operand to
845 // its result's uses.)
846 if (!state.bufferizesToMemoryWrite(use)) {
847 AliasingValueList aliases = state.getAliasingValues(use);
848 if (llvm::any_of(aliases, [&](AliasingValue a) {
849 return state.isValueRead(a.value);
850 }))
851 res.insert(&use);
852 }
853 }
854 });
855}
856
857/// Return true if bufferizing `operand` inplace would create a conflict. A read
858/// R and a write W of the same alias set is a conflict if inplace bufferization
859/// of W changes the value read by R to a value different from the one that
860/// would be expected by tracing back R's origin through SSA use-def chains.
861/// A conflict can only be introduced by a new alias and/or an inplace
862/// bufferization decision.
863///
864/// Example:
865/// %0 = tensor.extract_slice %t[...][...][1, 1] {inplace?}
866/// %1 = vector.transfer_write %v1, %t {inplace} : vector<5xf32>, tensor<?xf32>
867/// %e = tensor.extract_slice %1
868/// %2 = vector.transfer_write %v2, %0 {inplace} : vector<6xf32>, tensor<?xf32>
869/// %3 = vector.transfer_read %e, %cst : tensor<?xf32>, vector<7xf32>
870///
871/// In the above example, the two TransferWriteOps have already been decided to
872/// bufferize inplace. Bufferizing the ExtractSliceOp inplace would create a
873/// conflict because:
874/// * According to SSA use-def chains, we expect to read the result of %1.
875/// * However, adding an alias {%0, %t} would mean that the second
876/// TransferWriteOp overwrites the result of the first one. Therefore, the
877/// TransferReadOp would no longer be reading the result of %1.
878///
879/// If `checkConsistencyOnly` is true, this function checks if there is a
880/// read-after-write conflict without bufferizing `operand` inplace. This would
881/// indicate a problem with the current inplace bufferization decisions.
882///
883/// Note: If `checkConsistencyOnly`, this function may be called with a null
884/// OpResult. In that case, only the consistency of bufferization decisions
885/// involving aliases of the given OpOperand are checked.
887 OpOperand &operand, const DominanceInfo &domInfo,
888 OneShotAnalysisState &state, bool checkConsistencyOnly = false) {
889 // Collect reads and writes of all aliases of OpOperand and OpResult.
890 DenseSet<OpOperand *> usesRead, usesWrite;
891 getAliasingReads(usesRead, operand.get(), state);
892 getAliasingInplaceWrites(usesWrite, operand.get(), state);
893 for (AliasingValue alias : state.getAliasingValues(operand)) {
894 getAliasingReads(usesRead, alias.value, state);
895 getAliasingInplaceWrites(usesWrite, alias.value, state);
896 }
897 if (!checkConsistencyOnly && state.bufferizesToMemoryWrite(operand))
898 usesWrite.insert(&operand);
899
900 return hasReadAfterWriteInterference(usesRead, usesWrite, domInfo, state);
901}
902
903/// Annotate IR with details about the detected non-writability conflict.
905 static int64_t counter = 0;
906 OpBuilder b(value.getContext());
907 std::string id = "W_" + std::to_string(counter++);
908 if (auto opResult = dyn_cast<OpResult>(value)) {
909 std::string attr = id + "[NOT-WRITABLE: result " +
910 std::to_string(opResult.getResultNumber()) + "]";
911 opResult.getDefiningOp()->setAttr(attr, b.getUnitAttr());
912 } else {
913 auto bbArg = cast<BlockArgument>(value);
914 std::string attr = id + "[NOT-WRITABLE: bbArg " +
915 std::to_string(bbArg.getArgNumber()) + "]";
916 bbArg.getOwner()->getParentOp()->setAttr(attr, b.getUnitAttr());
917 }
918}
919
920/// Return true if bufferizing `operand` inplace would create a write to a
921/// non-writable buffer.
922static bool
925 bool checkConsistencyOnly = false) {
926 bool foundWrite =
927 !checkConsistencyOnly && state.bufferizesToMemoryWrite(operand);
928
929 if (!foundWrite) {
930 // Collect writes of all aliases of OpOperand and OpResult.
931 DenseSet<OpOperand *> usesWrite;
932 getAliasingInplaceWrites(usesWrite, operand.get(), state);
933 for (AliasingValue alias : state.getAliasingValues(operand))
934 getAliasingInplaceWrites(usesWrite, alias.value, state);
935 foundWrite = !usesWrite.empty();
936 }
937
938 if (!foundWrite)
939 return false;
940
941 // Look for a read-only tensor among all aliases.
942 bool foundReadOnly = false;
943 auto checkReadOnly = [&](Value v) {
944 if (!state.isWritable(v)) {
945 foundReadOnly = true;
946 if (state.getOptions().printConflicts)
948 }
949 };
950 state.applyOnAliases(operand.get(), checkReadOnly);
951 for (AliasingValue alias : state.getAliasingValues(operand))
952 state.applyOnAliases(alias.value, checkReadOnly);
953 if (foundReadOnly) {
954 LDBG() << "=> NOT WRITABLE";
955 return true;
956 }
957
958 return false;
959}
960
961//===----------------------------------------------------------------------===//
962// Bufferization analyses.
963//===----------------------------------------------------------------------===//
964
965// Find the values that define the contents of the given operand's value.
966const llvm::SetVector<Value> &
968 Value value = opOperand->get();
969 if (!cachedDefinitions.count(value))
970 cachedDefinitions[value] = findDefinitions(opOperand);
971 return cachedDefinitions[value];
972}
973
975 AnalysisState::resetCache();
976 cachedDefinitions.clear();
977}
978
979/// Determine if `operand` can be bufferized in-place.
980static LogicalResult
982 const DominanceInfo &domInfo) {
983 LDBG() << "//===-------------------------------------------===//\n"
984 << "Analyzing operand #" << operand.getOperandNumber() << " of "
985 << OpWithFlags(operand.getOwner(), OpPrintingFlags().skipRegions());
986
987 bool foundInterference =
988 wouldCreateWriteToNonWritableBuffer(operand, state) ||
989 wouldCreateReadAfterWriteInterference(operand, domInfo, state);
990
991 if (foundInterference)
992 state.bufferizeOutOfPlace(operand);
993 else
994 state.bufferizeInPlace(operand);
995
996 LDBG() << "//===-------------------------------------------===//";
997 return success();
998}
999
1000LogicalResult
1002 const DominanceInfo &domInfo) {
1003 for (OpOperand &opOperand : op->getOpOperands())
1004 if (isa<TensorType>(opOperand.get().getType()))
1005 if (failed(bufferizableInPlaceAnalysisImpl(opOperand, *this, domInfo)))
1006 return failure();
1007 return success();
1008}
1009
1010/// Analyze equivalence of tied OpResult/OpOperand pairs of the given ops.
1012 OneShotAnalysisState &state) {
1013 for (Operation *op : ops) {
1014 if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op)) {
1015 for (OpResult opResult : op->getOpResults()) {
1016 if (!isa<TensorType>(opResult.getType()))
1017 continue;
1018 AliasingOpOperandList aliases = state.getAliasingOpOperands(opResult);
1019 if (aliases.getNumAliases() == 0)
1020 // Nothing to do if there are no aliasing OpOperands.
1021 continue;
1022
1023 Value firstOperand = aliases.begin()->opOperand->get();
1024 bool allEquivalent = true;
1025 for (AliasingOpOperand alias : aliases) {
1026 bool isEquiv = alias.relation == BufferRelation::Equivalent;
1027 bool isInPlace = state.isInPlace(*alias.opOperand);
1028 Value operand = alias.opOperand->get();
1029 if (isEquiv && isInPlace && alias.isDefinite) {
1030 // Found a definite, equivalent alias. Merge equivalence sets.
1031 // There can only be one definite alias, so we can stop here.
1032 state.unionEquivalenceClasses(opResult, operand);
1033 allEquivalent = false;
1034 break;
1035 }
1036 if (!isEquiv || !isInPlace)
1037 allEquivalent = false;
1038 if (!state.areEquivalentBufferizedValues(operand, firstOperand))
1039 allEquivalent = false;
1040 }
1041
1042 // If all "maybe" aliases are equivalent and the OpResult is not a new
1043 // allocation, it is a definite, equivalent alias. E.g.:
1044 //
1045 // aliasingOpOperands(%r) = {(%t0, EQUIV, MAYBE), (%t1, EQUIV, MAYBE)}
1046 // aliasingValues(%t0) = {(%r, EQUIV, MAYBE)}
1047 // aliasingValues(%t1) = {(%r, EQUIV, MAYBE)}
1048 // %r = arith.select %c, %t0, %t1 : tensor<?xf32>
1049 //
1050 // If %t0 and %t1 are equivalent, it is safe to union the equivalence
1051 // classes of %r, %t0 and %t1.
1052 if (allEquivalent && !bufferizableOp.bufferizesToAllocation(opResult))
1053 state.unionEquivalenceClasses(opResult, firstOperand);
1054 }
1055 }
1056 }
1057}
1058
1059/// Analyze equivalence of tied OpResult/OpOperand pairs of all ops contained
1060/// in `op`.
1062 // Traverse ops in PostOrder: Nested ops first, then enclosing ops.
1064 op->walk<WalkOrder::PostOrder>([&](Operation *op) {
1065 // No tensors => no buffers.
1066 if (none_of(op->getResultTypes(), isaTensor))
1067 return;
1068 ops.push_back(op);
1069 });
1070
1071 equivalenceAnalysis(ops, state);
1072}
1073
1074/// "Bottom-up from terminators" heuristic.
1075static SmallVector<Operation *>
1077 const OneShotAnalysisState &state) {
1078 SetVector<Operation *> traversedOps;
1079
1080 // Find region terminators.
1081 op->walk<WalkOrder::PostOrder>([&](RegionBranchTerminatorOpInterface term) {
1082 if (!traversedOps.insert(term))
1083 return;
1084 // Follow the reverse SSA use-def chain from each yielded value as long as
1085 // we stay within the same region.
1086 SmallVector<OpResult> worklist;
1087 for (Value v : term->getOperands()) {
1088 if (!isa<TensorType>(v.getType()))
1089 continue;
1090 auto opResult = dyn_cast<OpResult>(v);
1091 if (!opResult)
1092 continue;
1093 worklist.push_back(opResult);
1094 }
1095 while (!worklist.empty()) {
1096 OpResult opResult = worklist.pop_back_val();
1097 Operation *defOp = opResult.getDefiningOp();
1098 if (!traversedOps.insert(defOp))
1099 continue;
1100 if (!term->getParentRegion()->findAncestorOpInRegion(*defOp))
1101 continue;
1102 AliasingOpOperandList aliases = state.getAliasingOpOperands(opResult);
1103 for (auto alias : aliases) {
1104 Value v = alias.opOperand->get();
1105 if (!isa<TensorType>(v.getType()))
1106 continue;
1107 auto opResult = dyn_cast<OpResult>(v);
1108 if (!opResult)
1109 continue;
1110 worklist.push_back(opResult);
1111 }
1112 }
1113 });
1114
1115 // Analyze traversed ops, then all remaining ops.
1116 SmallVector<Operation *> result(traversedOps.begin(), traversedOps.end());
1118 if (!traversedOps.contains(op) && hasTensorSemantics(op))
1119 result.push_back(op);
1120 });
1121 return result;
1122}
1123
1125 const DominanceInfo &domInfo) {
1128
1129 SmallVector<Operation *> orderedOps;
1130 if (heuristic ==
1132 orderedOps = bottomUpFromTerminatorsHeuristic(op, *this);
1133 } else {
1134 op->walk([&](Operation *op) {
1135 // No tensors => no buffers.
1136 if (!hasTensorSemantics(op))
1137 return;
1138 orderedOps.push_back(op);
1139 });
1140 switch (heuristic) {
1142 // Default: Walk ops in reverse for better interference analysis.
1143 std::reverse(orderedOps.begin(), orderedOps.end());
1144 break;
1145 }
1147 // Ops are already sorted top-down in `orderedOps`.
1148 break;
1149 }
1151 assert(getOptions().analysisFuzzerSeed &&
1152 "expected that fuzzer seed it set");
1153 // This is a fuzzer. For testing purposes only. Randomize the order in
1154 // which operations are analyzed. The bufferization quality is likely
1155 // worse, but we want to make sure that no assertions are triggered
1156 // anywhere.
1157 std::mt19937 g(getOptions().analysisFuzzerSeed);
1158 llvm::shuffle(orderedOps.begin(), orderedOps.end(), g);
1159 break;
1160 }
1161 default: {
1162 llvm_unreachable("unsupported heuristic");
1163 }
1164 }
1165 }
1166
1167 // Analyze ops in the computed order.
1168 for (Operation *op : orderedOps)
1169 if (failed(analyzeSingleOp(op, domInfo)))
1170 return failure();
1171
1172 equivalenceAnalysis(op, *this);
1173 return success();
1174}
1175
1176/// Perform various checks on the input IR to see if it contains IR constructs
1177/// that are unsupported by One-Shot Bufferize.
1178static LogicalResult
1180 OneShotAnalysisState &state) {
1181 const BufferizationOptions &options = state.getOptions();
1182
1183 // Note: This walk cannot be combined with the one below because interface
1184 // methods of invalid/unsupported ops may be called during the second walk.
1185 // (On ops different from `op`.)
1186 WalkResult walkResult = op->walk([&](BufferizableOpInterface op) {
1187 // Skip ops that are not in the filter.
1188 if (!options.isOpAllowed(op.getOperation()))
1189 return WalkResult::advance();
1190
1191 // Check for unsupported unstructured control flow.
1192 if (!op.supportsUnstructuredControlFlow()) {
1193 for (Region &r : op->getRegions()) {
1194 if (r.getBlocks().size() > 1) {
1195 op->emitOpError("op or BufferizableOpInterface implementation does "
1196 "not support unstructured control flow, but at least "
1197 "one region has multiple blocks");
1198 return WalkResult::interrupt();
1199 }
1200 }
1201 }
1202
1203 return WalkResult::advance();
1204 });
1205 if (walkResult.wasInterrupted())
1206 return failure();
1207
1208 walkResult = op->walk([&](BufferizableOpInterface op) {
1209 // Skip ops that are not in the filter.
1210 if (!options.isOpAllowed(op.getOperation()))
1211 return WalkResult::advance();
1212
1213 // Input IR may not contain any ToTensorOps without the "restrict"
1214 // attribute. Such tensors may alias any other tensor, which is currently
1215 // not handled in the analysis.
1216 if (auto toTensorOp = dyn_cast<ToTensorOp>(op.getOperation())) {
1217 if (!toTensorOp.getRestrict() && !toTensorOp->getUses().empty()) {
1218 op->emitOpError("to_tensor ops without `restrict` are not supported by "
1219 "One-Shot Analysis");
1220 return WalkResult::interrupt();
1221 }
1222 }
1223
1224 for (OpOperand &opOperand : op->getOpOperands()) {
1225 if (isa<TensorType>(opOperand.get().getType())) {
1227 opOperand, domInfo, state,
1228 /*checkConsistencyOnly=*/true)) {
1229 // This error can happen if certain "mustBufferizeInPlace" interface
1230 // methods are implemented incorrectly, such that the IR already has
1231 // a RaW conflict before making any bufferization decisions. It can
1232 // also happen if the bufferization.materialize_in_destination is used
1233 // in such a way that a RaW conflict is not avoidable.
1234 op->emitOpError("not bufferizable under the given constraints: "
1235 "cannot avoid RaW conflict");
1236 return WalkResult::interrupt();
1237 }
1238
1239 if (state.isInPlace(opOperand) &&
1241 opOperand, state, /*checkConsistencyOnly=*/true)) {
1242 op->emitOpError("not bufferizable under the given constraints: would "
1243 "write to read-only buffer");
1244 return WalkResult::interrupt();
1245 }
1246 }
1247 }
1248
1249 return WalkResult::advance();
1250 });
1251
1252 return success(!walkResult.wasInterrupted());
1253}
1254
1255/// Annotate the IR with the result of the analysis. For testing/debugging only.
1256static void
1258 const OneShotAnalysisState &state) {
1259 // Add __inplace_operands_attr__.
1260 op->walk([&](Operation *op) {
1261 for (OpOperand &opOperand : op->getOpOperands())
1262 if (isa<TensorType>(opOperand.get().getType()))
1263 setInPlaceOpOperand(opOperand, state.isInPlace(opOperand));
1264 });
1265}
1266
1268 const OneShotAnalysisState &state) {
1269 AsmState asmState(op);
1270 Builder b(op->getContext());
1271 // Helper function to build an array attribute of aliasing SSA value strings.
1272 auto buildAliasesArray = [&](Value v) {
1273 SmallVector<Attribute> aliases;
1274 state.applyOnAliases(v, [&](Value alias) {
1275 std::string buffer;
1276 llvm::raw_string_ostream stream(buffer);
1277 alias.printAsOperand(stream, asmState);
1278 aliases.push_back(b.getStringAttr(buffer));
1279 });
1280 return b.getArrayAttr(aliases);
1281 };
1282
1283 op->walk([&](Operation *op) {
1284 // Build alias set array for every OpResult.
1285 SmallVector<Attribute> opResultAliasSets;
1286 for (OpResult opResult : op->getOpResults()) {
1287 if (llvm::isa<TensorType>(opResult.getType())) {
1288 opResultAliasSets.push_back(buildAliasesArray(opResult));
1289 }
1290 }
1291 if (!opResultAliasSets.empty())
1292 op->setAttr(kOpResultAliasSetAttrName, b.getArrayAttr(opResultAliasSets));
1293
1294 // Build alias set array for every BlockArgument.
1295 SmallVector<Attribute> regionAliasSets;
1296 bool hasTensorBbArg = false;
1297 for (Region &r : op->getRegions()) {
1298 SmallVector<Attribute> blockAliasSets;
1299 for (Block &block : r.getBlocks()) {
1300 SmallVector<Attribute> bbArgAliasSets;
1301 for (BlockArgument bbArg : block.getArguments()) {
1302 if (llvm::isa<TensorType>(bbArg.getType())) {
1303 bbArgAliasSets.push_back(buildAliasesArray(bbArg));
1304 hasTensorBbArg = true;
1305 }
1306 }
1307 blockAliasSets.push_back(b.getArrayAttr(bbArgAliasSets));
1308 }
1309 regionAliasSets.push_back(b.getArrayAttr(blockAliasSets));
1310 }
1311 if (hasTensorBbArg)
1312 op->setAttr(kBbArgAliasSetAttrName, b.getArrayAttr(regionAliasSets));
1313 });
1314}
1315
1317 OneShotAnalysisState &state,
1318 BufferizationStatistics *statistics) {
1319 DominanceInfo domInfo(op);
1321
1322 if (failed(checkPreBufferizationAssumptions(op, domInfo, state)))
1323 return failure();
1324
1325 // If the analysis fails, just return.
1326 if (failed(state.analyzeOp(op, domInfo)))
1327 return failure();
1328
1329 if (statistics) {
1330 statistics->numTensorInPlace = state.getStatNumTensorInPlace();
1331 statistics->numTensorOutOfPlace = state.getStatNumTensorOutOfPlace();
1332 }
1333
1334 bool failedAnalysis = false;
1335
1336 // Gather some extra analysis data.
1337 state.gatherUndefinedTensorUses(op);
1338
1339 // Analysis verification: After setting up alias/equivalence sets, each op
1340 // can check for expected invariants/limitations and fail the analysis if
1341 // necessary.
1342 op->walk([&](Operation *op) {
1343 if (BufferizableOpInterface bufferizableOp =
1344 options.dynCastBufferizableOp(op))
1345 failedAnalysis |= failed(bufferizableOp.verifyAnalysis(state));
1346 });
1347
1348 // Annotate operations if we only want to report the analysis.
1349 if (options.testAnalysisOnly)
1351 if (options.dumpAliasSets)
1352 annotateOpsWithAliasSets(op, state);
1353
1354 return success(!failedAnalysis);
1355}
1356
1359 BufferizationState &state, BufferizationStatistics *statistics) {
1360 // copy-before-write deactivates the analysis. It cannot be used together with
1361 // test-analysis-only.
1362 assert(!(options.copyBeforeWrite && options.testAnalysisOnly) &&
1363 "invalid combination of bufferization flags");
1364
1365 if (options.copyBeforeWrite) {
1366 // Copy buffer before each write. No analysis is needed.
1367 } else {
1368 // Run One-Shot Analysis and insert buffer copies (on the tensor level)
1369 // only where needed. This is the default and much more efficient than
1370 // copy-before-write.
1371 if (failed(insertTensorCopies(op, options, state, statistics)))
1372 return failure();
1373
1374 // If test-analysis-only is set, the IR was annotated with RaW conflict
1375 // markers (attributes) during One-Shot Analysis.
1376 if (options.testAnalysisOnly)
1377 return success();
1378 }
1379
1380 // Bufferize the op and its nested ops. If options.copyBeforeWrite is set,
1381 // a new buffer copy is allocated every time a buffer is written to.
1382 return bufferizeOp(op, options, state, statistics);
1383}
return success()
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static bool hasReadAfterWriteInterference(const DenseSet< OpOperand * > &usesRead, const DenseSet< OpOperand * > &usesWrite, const DominanceInfo &domInfo, OneShotAnalysisState &state)
Given sets of uses and writes, return true if there is a RaW conflict under the assumption that all g...
static void getAliasingReads(DenseSet< OpOperand * > &res, Value root, const OneShotAnalysisState &state)
static void equivalenceAnalysis(SmallVector< Operation * > &ops, OneShotAnalysisState &state)
Analyze equivalence of tied OpResult/OpOperand pairs of the given ops.
static void setInPlaceOpOperand(OpOperand &opOperand, bool inPlace)
Mark whether OpOperand will be bufferized inplace.
constexpr StringLiteral kInPlaceOperandsAttrName
Attribute marker to specify op operands that bufferize in-place.
static bool isaTensor(Type t)
static void annotateNonWritableTensor(Value value)
Annotate IR with details about the detected non-writability conflict.
static SmallVector< Operation * > bottomUpFromTerminatorsHeuristic(Operation *op, const OneShotAnalysisState &state)
"Bottom-up from terminators" heuristic.
static bool canUseOpDominanceDueToRegions(OpOperand *uRead, OpOperand *uWrite, const SetVector< Value > &definitions, AnalysisState &state)
Return true if op dominance can be used to rule out a read-after-write conflicts based on the orderin...
static LogicalResult bufferizableInPlaceAnalysisImpl(OpOperand &operand, OneShotAnalysisState &state, const DominanceInfo &domInfo)
Determine if operand can be bufferized in-place.
constexpr StringLiteral kOpResultAliasSetAttrName
static bool happensBefore(Operation *a, Operation *b, const DominanceInfo &domInfo)
Return true if a happens before b, i.e., a or one of its ancestors properly dominates b and b is not ...
static bool canUseOpDominance(OpOperand *uRead, OpOperand *uWrite, const SetVector< Value > &definitions, AnalysisState &state)
static bool matchesInsertDestination(const AnalysisState &state, OpOperand *opOperand, SubsetInsertionOpInterface subsetOp)
Return "true" if the given operand's value is originating from a subset that is equivalent to the sub...
static bool wouldCreateWriteToNonWritableBuffer(OpOperand &operand, OneShotAnalysisState &state, bool checkConsistencyOnly=false)
Return true if bufferizing operand inplace would create a write to a non-writable buffer.
static void annotateOpsWithAliasSets(Operation *op, const OneShotAnalysisState &state)
static LogicalResult checkPreBufferizationAssumptions(Operation *op, const DominanceInfo &domInfo, OneShotAnalysisState &state)
Perform various checks on the input IR to see if it contains IR constructs that are unsupported by On...
static void annotateOpsWithBufferizationMarkers(Operation *op, const OneShotAnalysisState &state)
Annotate the IR with the result of the analysis. For testing/debugging only.
static bool wouldCreateReadAfterWriteInterference(OpOperand &operand, const DominanceInfo &domInfo, OneShotAnalysisState &state, bool checkConsistencyOnly=false)
Return true if bufferizing operand inplace would create a conflict.
constexpr StringLiteral kBbArgAliasSetAttrName
static bool canUseOpDominanceDueToBlocks(OpOperand *uRead, OpOperand *uWrite, const SetVector< Value > &definitions, AnalysisState &state)
Return true if op dominance can be used to rule out a read-after-write conflicts based on the orderin...
static void getAliasingInplaceWrites(DenseSet< OpOperand * > &res, Value root, const OneShotAnalysisState &state)
static bool areNonConflictingSubsets(OpOperand *uRead, OpOperand *uConflictingWrite, const AnalysisState &state)
Return "true" if the given "read" and potentially conflicting "write" are not conflicting due to thei...
static void annotateConflict(OpOperand *uRead, OpOperand *uConflictingWrite, Value definition)
Annotate IR with details about the detected RaW conflict.
static bool hasEquivalentValueInReverseUseDefChain(AnalysisState &state, OpOperand *start, Value other)
Return 'true' if a tensor that is equivalent to other can be found in the reverse use-def chain of st...
static bool isInplaceMemoryWrite(OpOperand &opOperand, const OneShotAnalysisState &state)
Return true if opOperand has been decided to bufferize in-place.
static llvm::ManagedStatic< PassManagerOptions > options
#define MLIR_DEFINE_EXPLICIT_TYPE_ID(CLASS_NAME)
Definition TypeID.h:323
static Operation * getOwnerOfValue(Value value)
Base class for generic analysis states.
AnalysisState(LatticeAnchor anchor)
Create the analysis state on the given lattice anchor.
This class provides management for the lifetime of the state used when printing the IR.
Definition AsmState.h:542
This class represents an argument of a Block.
Definition Value.h:306
Block represents an ordered list of Operations.
Definition Block.h:33
Operation * findAncestorOpInBlock(Operation &op)
Returns 'op' if 'op' lies in this block, or otherwise finds the ancestor operation of 'op' that lies ...
Definition Block.cpp:74
bool isReachable(Block *other, SmallPtrSet< Block *, 16 > &&except={})
Return "true" if there is a path from this block to the given block (according to the successors rela...
Definition Block.cpp:368
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
A class for computing basic dominance information.
Definition Dominance.h:140
bool properlyDominates(Operation *a, Operation *b, bool enclosingOpOk=true) const
Return true if operation A properly dominates operation B, i.e.
IRValueT get() const
Return the current value being used by this operand.
This class helps build Operations.
Definition Builders.h:209
This class represents an operand of an operation.
Definition Value.h:254
unsigned getOperandNumber()
Return which operand this is in the OpOperand list of the Operation.
Definition Value.cpp:226
Set of flags used to control the behavior of the various IR print methods (e.g.
This is a value defined by a result of an operation.
Definition Value.h:454
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Definition Operation.h:1140
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
Attribute getAttr(StringAttr name)
Return the specified attribute if present, null otherwise.
Definition Operation.h:563
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:234
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:255
MutableArrayRef< OpOperand > getOpOperands()
Definition Operation.h:412
unsigned getNumOperands()
Definition Operation.h:375
void setAttr(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
Definition Operation.h:611
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:706
result_type_range getResultTypes()
Definition Operation.h:457
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
Definition Operation.h:292
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:826
result_range getOpResults()
Definition Operation.h:449
result_range getResults()
Definition Operation.h:444
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition Operation.h:251
bool isProperAncestor(Operation *other)
Return true if this operation is a proper ancestor of the other operation.
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:237
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition Region.h:200
This class provides an efficient unique identifier for a specific C++ type.
Definition TypeID.h:107
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
MLIRContext * getContext() const
Utility to get the associated MLIRContext that this value is defined in.
Definition Value.h:108
Type getType() const
Return the type of this value.
Definition Value.h:105
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition Value.h:188
void printAsOperand(raw_ostream &os, AsmState &state) const
Print this value as if it were an operand.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
A utility result that is used to signal how to proceed with an ongoing walk:
Definition WalkResult.h:29
static WalkResult skip()
Definition WalkResult.h:48
static WalkResult advance()
Definition WalkResult.h:47
bool wasInterrupted() const
Returns true if the walk was interrupted.
Definition WalkResult.h:51
static WalkResult interrupt()
Definition WalkResult.h:46
virtual ~Extension()
Base virtual destructor.
State for analysis-enabled bufferization.
void bufferizeOutOfPlace(OpOperand &operand)
Mark the given OpOperand as out-of-place.
bool isWritable(Value value) const
Return true if the buffer of the given tensor value is writable.
const SetVector< Value > & findDefinitionsCached(OpOperand *opOperand)
Find the definitions of the given operand's value or retrieve them from the cache.
bool isInPlace(OpOperand &opOperand) const override
Return true if the given OpResult has been decided to bufferize inplace.
LogicalResult analyzeOp(Operation *op, const DominanceInfo &domInfo)
Analyze the given op and its nested ops.
bool isValueWritten(Value value) const
Return true if the buffer of the given tensor value is written to.
void unionEquivalenceClasses(Value v1, Value v2)
Union the equivalence classes of v1 and v2.
void gatherUndefinedTensorUses(Operation *op)
Find all tensor values in the given operation that have undefined contents and store them in undefine...
void resetCache() override
Reset cached data structures.
const OneShotBufferizationOptions & getOptions() const
Return a reference to the BufferizationOptions.
LogicalResult analyzeSingleOp(Operation *op, const DominanceInfo &domInfo)
Analyze a single op (without nested ops).
void applyOnEquivalenceClass(Value v, function_ref< void(Value)> fun) const
Apply fun to all the members of the equivalence class of v.
bool hasUndefinedContents(OpOperand *opOperand) const override
Return true if the given tensor has undefined contents.
void bufferizeInPlace(OpOperand &operand)
Mark the given OpOperand as in-place and merge the results' and operand's aliasing sets.
void applyOnAliases(Value v, function_ref< void(Value)> fun) const
Apply fun to all aliases of v.
bool areEquivalentBufferizedValues(Value v1, Value v2) const override
Return true if v1 and v2 bufferize to equivalent buffers.
OneShotAnalysisState(Operation *op, const OneShotBufferizationOptions &options)
bool areAliasingBufferizedValues(Value v1, Value v2) const override
Return true if v1 and v2 may bufferize to aliasing buffers.
void unionAliasSets(Value v1, Value v2)
Union the alias sets of v1 and v2.
void createAliasInfoEntry(Value v)
Add a new entry for v in the aliasInfo and equivalentInfo.
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
LogicalResult bufferizeOp(Operation *op, const BufferizationOptions &options, BufferizationState &bufferizationState, BufferizationStatistics *statistics=nullptr)
Bufferize op and its nested ops that implement BufferizableOpInterface.
LogicalResult analyzeOp(Operation *op, OneShotAnalysisState &state, BufferizationStatistics *statistics=nullptr)
Analyze op and its nested ops.
LogicalResult insertTensorCopies(Operation *op, const OneShotBufferizationOptions &options, const BufferizationState &bufferizationState, BufferizationStatistics *statistics=nullptr)
Resolve RaW and other conflicts by inserting bufferization.alloc_tensor ops.
LogicalResult runOneShotBufferize(Operation *op, const OneShotBufferizationOptions &options, BufferizationState &state, BufferizationStatistics *statistics=nullptr)
Run One-Shot Bufferize on the given op: Analysis + Bufferization.
Include the generated interface declarations.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:122
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:125
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
llvm::function_ref< Fn > function_ref
Definition LLVM.h:147
This iterator enumerates elements in "reverse" order.
Definition Iterators.h:29
Bufferization statistics for debugging.
Definition Bufferize.h:35
Options for analysis-enabled bufferization.
AnalysisHeuristic analysisHeuristic
The heuristic controls the order in which ops are traversed during the analysis.