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