MLIR  19.0.0git
BufferizableOpInterface.h
Go to the documentation of this file.
1 //===- BufferizableOpInterface.h - Bufferizable Ops -------------*- C++ -*-===//
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 #ifndef MLIR_DIALECT_BUFFERIZATION_IR_BUFFERIZABLEOPINTERFACE_H_
10 #define MLIR_DIALECT_BUFFERIZATION_IR_BUFFERIZABLEOPINTERFACE_H_
11 
12 #include "mlir/IR/Operation.h"
13 #include "mlir/IR/PatternMatch.h"
14 #include "mlir/Support/LLVM.h"
15 #include "llvm/ADT/DenseMapInfoVariant.h"
16 #include "llvm/ADT/SetVector.h"
17 #include <optional>
18 
19 #include "mlir/Dialect/Bufferization/IR/BufferizationEnums.h.inc"
20 
21 namespace mlir {
22 class OpBuilder;
23 namespace func {
24 class FuncOp;
25 }
26 
27 namespace bufferization {
28 
29 class AnalysisState;
30 class BufferizableOpInterface;
31 
32 /// Specifies a fine-grain relationship between buffers to enable more analysis.
33 enum class BufferRelation {
34  Unknown,
35  // TODO: ResultContainsOperand,
36  // TODO: OperandContainsResult,
38 };
39 
40 /// A maybe aliasing OpOperand. If `isDefinite` is `true`, the OpOperand is
41 /// guaranteed to alias at runtime.
44  bool isDefinite = true)
46 
49  bool isDefinite;
50 };
51 
52 /// A maybe aliasing Value. If `isDefinite` is `true`, the Value is guaranteed
53 /// to alias at runtime.
54 struct AliasingValue {
57 
60  bool isDefinite;
61 };
62 
63 template <typename T> class AliasList {
64 public:
65  /// Create an empty list of aliases.
66  AliasList() = default;
67 
68  /// Create a list of aliases.
69  AliasList(std::initializer_list<T> elems) {
70  for (T alias : elems)
71  addAlias(alias);
72  }
73 
74  /// Create a list of aliases.
75  AliasList(SmallVector<T> &&aliases) : aliases(std::move(aliases)) {}
76 
77  ArrayRef<T> getAliases() const { return aliases; }
78 
79  size_t getNumAliases() const { return aliases.size(); }
80 
81  void addAlias(T alias) { aliases.push_back(alias); }
82 
83  auto begin() const { return aliases.begin(); }
84  auto end() const { return aliases.end(); }
85 
86 private:
87  /// The list of aliases.
88  SmallVector<T> aliases;
89 };
90 
91 /// A list of possible aliasing OpOperands. This list models the runtime
92 /// aliasing relationship for a Value.
94 
95 /// A list of possible aliasing Values. This list models the runtime aliasing
96 /// relationship for an OpOperand.
98 
99 class OpFilter {
100 public:
101  /// An op filter entry. Filters can be used to specify which ops should be
102  /// processed by the bufferization.
103  struct Entry {
104  /// If the filter function evaluates to `true`, the filter matches.
105  using FilterFn = std::function<bool(Operation *)>;
106 
107  /// Filter type: A filter can either be a DENY filter or an ALLOW filter.
108  enum FilterType : int8_t { DENY = 0, ALLOW = 1 };
109 
112  };
113 
114  /// Return whether the op is allowed or not.
115  ///
116  /// If the filter does not have an ALLOW rule, ops are allowed by default,
117  /// unless they are explicitly marked as DENY. If the filter has at least one
118  /// ALLOW rule, ops are denied by default and only allowed if they match
119  /// an ALLOW rule and no DENY rule.
120  bool isOpAllowed(Operation *op) const;
121 
122  /// Allow the given dialects.
123  ///
124  /// This function adds one or multiple ALLOW entries.
125  template <typename... DialectTs>
126  void allowDialect() {
127  // The following expands a call to allowDialectImpl for each dialect
128  // in 'DialectTs'.
129  (allowDialectImpl<DialectTs>(), ...);
130  }
131 
132  /// Deny the given dialects.
133  ///
134  /// This function adds one or multiple DENY entries.
135  template <typename... DialectTs>
136  void denyDialect() {
137  (denyDialectImpl<DialectTs>(), ...);
138  }
139 
140  /// Allow the given dialect.
141  ///
142  /// This function adds an ALLOW entry.
143  void allowDialect(StringRef dialectNamespace) {
144  Entry::FilterFn filterFn = [=](Operation *op) {
145  return op->getDialect()->getNamespace() == dialectNamespace;
146  };
147  entries.push_back(Entry{filterFn, Entry::FilterType::ALLOW});
148  }
149 
150  /// Allow the given ops.
151  ///
152  /// This function adds one or multiple ALLOW entries.
153  template <typename... OpTys>
154  void allowOperation() {
155  (allowOperationImpl<OpTys>(), ...);
156  }
157 
158  /// Deny the given ops.
159  ///
160  /// This function adds one or multiple DENY entries.
161  template <typename... OpTys>
162  void denyOperation() {
163  (denyOperationImpl<OpTys>(), ...);
164  }
165 
166  /// Allow the given op.
167  ///
168  /// This function adds an ALLOW entry.
169  void allowOperation(StringRef opName) {
170  Entry::FilterFn filterFn = [=](Operation *op) {
171  return op->getName().getStringRef() == opName;
172  };
173  allowOperation(filterFn);
174  }
175 
176  /// Deny the given op.
177  ///
178  /// This function adds a DENY entry.
179  void denyOperation(StringRef opName) {
180  Entry::FilterFn filterFn = [=](Operation *op) {
181  return op->getName().getStringRef() == opName;
182  };
183  denyOperation(filterFn);
184  }
185 
186  /// Allow ops that are matched by `fn`.
187  ///
188  /// This function adds an ALLOW entry.
190  entries.push_back(Entry{fn, Entry::FilterType::ALLOW});
191  }
192 
193  /// Deny ops that are matched by `fn`.
194  ///
195  /// This function adds a DENY entry.
197  entries.push_back(Entry{fn, Entry::FilterType::DENY});
198  }
199 
200 private:
201  /// Return `true` if the filter has at least one ALLOW rule.
202  bool hasAllowRule() const {
203  for (const Entry &e : entries)
204  if (e.type == Entry::FilterType::ALLOW)
205  return true;
206  return false;
207  }
208 
209  /// Allow a dialect.
210  template <typename DialectT>
211  void allowDialectImpl() {
212  allowDialect(DialectT::getDialectNamespace());
213  }
214 
215  /// Deny a dialect.
216  template <typename DialectT>
217  void denyDialectImpl() {
218  denyDialect(DialectT::getDialectNamespace());
219  }
220 
221  /// Allow an op.
222  template <typename OpTy>
223  void allowOperationImpl() {
224  allowOperation(OpTy::getOperationName());
225  }
226 
227  /// Deny an op.
228  template <typename OpTy>
229  void denyOperationImpl() {
230  denyOperation(OpTy::getOperationName());
231  }
232 
233  /// A list of filter entries that determine whether an op should be allowed or
234  /// denied. If the filter has an ALLOW rule, only ops that are allowed and not
235  /// denied are allowed. If the filter does not have an ALLOW rule, only ops
236  /// that are not denied are allowed.
237  SmallVector<Entry> entries;
238 };
239 
240 /// Options for BufferizableOpInterface-based bufferization.
242  /// Allocator function: Generate a memref allocation with the given type,
243  /// dynamic extents and alignment.
244  using AllocationFn = std::function<FailureOr<Value>(
245  OpBuilder &, Location, MemRefType, ValueRange, unsigned int)>;
246  /// Memcpy function: Generate a memcpy between two buffers.
247  using MemCpyFn =
248  std::function<LogicalResult(OpBuilder &, Location, Value, Value)>;
249  /// Initializer function for analysis state.
250  using AnalysisStateInitFn = std::function<void(AnalysisState &)>;
251  /// Tensor -> MemRef type converter.
252  /// Parameters: Value, memory space, func op, bufferization options
254  std::function<BaseMemRefType(TensorType, Attribute memorySpace,
255  func::FuncOp, const BufferizationOptions &)>;
256  /// Tensor -> MemRef type converter.
257  /// Parameters: Value, memory space, bufferization options
258  using UnknownTypeConverterFn = std::function<BaseMemRefType(
259  Value, Attribute memorySpace, const BufferizationOptions &)>;
260  // Produce a MemorySpace attribute from a tensor type
262  std::function<std::optional<Attribute>(TensorType t)>;
263 
265 
266  /// Try to cast the given op to BufferizableOpInterface if the op is allow
267  /// listed.
268  BufferizableOpInterface dynCastBufferizableOp(Operation *op) const;
269 
270  /// Try to cast the given value to BufferizableOpInterface if the op is allow
271  /// listed.
272  BufferizableOpInterface dynCastBufferizableOp(Value value) const;
273 
274  /// A filter that specifies which ops should be bufferized and which ops
275  /// should be ignored.
277 
278  /// Return `true` if the given op should be bufferized.
279  bool isOpAllowed(Operation *op) const;
280 
281  /// Helper functions for allocation and memory copying.
282  std::optional<AllocationFn> allocationFn;
283  std::optional<MemCpyFn> memCpyFn;
284 
285  /// Create a memref allocation with the given type and dynamic extents.
286  FailureOr<Value> createAlloc(OpBuilder &b, Location loc, MemRefType type,
287  ValueRange dynShape) const;
288 
289  /// Creates a memcpy between two given buffers.
291  Value to) const;
292 
293  /// Specifies whether not bufferizable ops are allowed in the input. If so,
294  /// bufferization.to_memref and bufferization.to_tensor ops are inserted at
295  /// the boundaries.
296  bool allowUnknownOps = false;
297 
298  /// Specifies whether function boundaries (ops in the func dialect) should be
299  /// bufferized or not.
301 
302  /// Certain ops have aliasing OpOperand/OpResult invariants (e.g., scf.for).
303  /// If this flag is set to `false`, those invariants are no longer enforced
304  /// with buffer copies.
305  ///
306  /// Note: Deactivating this flag can lead to incorrect bufferization results
307  /// when used incorrectly. This flag is useful with
308  /// `AlwaysCopyAnalysisState` which bufferizes all writing tensor
309  /// OpOperands out-of-place.
311 
312  /// This function controls buffer types on function signatures. Sets
313  /// `functionArgTypeConverterFn` and `inferFunctionResultLayout` accordingly.
314  ///
315  /// * InferLayoutMap: All function parameter types have a fully dynamic layout
316  /// map, but function result types are inferred from the body of the
317  /// function.
318  /// * FullyDynamicLayoutMap: All function parameter types and result types
319  /// have a fully dynamic layout map. This option is most efficient because
320  /// any layout map can be casted to a fully dynamic one.
321  /// * IdentityLayoutMap: All function parameter types and result types have a
322  /// static identity layout (i.e., no layout map). This option may introduce
323  /// additional buffer allocs and copies because layout maps cannot be casted
324  /// away.
325  ///
326  /// Note: Inferred layout maps may not be desireable when interacting with
327  /// external functions, because the generated function signatures will be less
328  /// predictable.
329  void setFunctionBoundaryTypeConversion(LayoutMapOption layoutMapOption);
330 
331  /// Type converter from tensors to memrefs. This type converter is used to
332  /// determine bufferized function argument types. By default, a type
333  /// converter that returns a memref type with a fully dynamic layout map is
334  /// used.
335  ///
336  /// If `bufferizeFunctionBoundaries` is not set, this function isn't used.
338 
339  /// If true, function result types are inferred from the body of the function.
340  /// Otherwise, function result type is determined by
341  /// `functionArgTypeConverterFn`.
342  ///
343  /// If `bufferizeFunctionBoundaries` is not set, this flag has no effect.
345 
346  /// Type converter from tensors to memrefs. This type converter is used if no
347  /// memref type could be inferred during bufferization. By default, a type
348  /// converter that returns a memref type with a fully dynamic layout map is
349  /// used.
351 
352  // Use during type conversion to determine the memory space for memref based
353  // on the original tensor type if the memory space cannot be inferred.
354  // Returning std::nullopt will cause bufferization to fail (useful to indicate
355  // failure to determine memory space for a tensor type).
357  [](TensorType t) -> std::optional<Attribute> { return Attribute(); };
358 
359  /// Seed for the analysis fuzzer. If set to `0`, the fuzzer is deactivated.
360  /// Should be used only with `testAnalysisOnly = true`.
361  unsigned analysisFuzzerSeed = 0;
362 
363  /// If set to `true`, the analysis is skipped. A buffer is copied before every
364  /// write. This flag cannot be used together with `testAnalysisOnly = true`.
365  bool copyBeforeWrite = false;
366 
367  /// If set to `true`, does not modify the IR apart from adding attributes (for
368  /// checking the results of the analysis) and post analysis steps.
369  bool testAnalysisOnly = false;
370 
371  /// If set to `true`, the IR is annotated with details about RaW conflicts.
372  /// For debugging only. Should be used together with `testAnalysisOnly`.
373  bool printConflicts = false;
374 
375  /// Buffer alignment for new memory allocations.
376  unsigned int bufferAlignment = 64;
377 
378  /// Initializer functions for analysis state. These can be used to
379  /// initialize dialect-specific analysis state.
381 };
382 
383 /// Traversal parameters for `findValueInReverseUseDefChain`.
385  /// Specifies if leaves (that do not have further OpOperands to follow)
386  /// should be returned even if they do not match the specified filter.
387  bool alwaysIncludeLeaves = true;
388 
389  /// Specifies whether out-of-place/undecided OpOperands should be followed.
390  bool followInPlaceOnly = false;
391 
392  /// Specifies whether non-equivalent OpOperands should be followed.
393  bool followEquivalentOnly = false;
394 
395  /// Specifies whether unknown/non-bufferizable/ops not included in the
396  /// OpFilter of BufferizationOptions should be followed.
397  bool followUnknownOps = false;
398 
399  /// Specifies whether OpOperands with a different type that are not the result
400  /// of a CastOpInterface op should be followed.
402 
403  /// Specifies whether already visited values should be visited again.
404  /// (Note: This can result in infinite looping.)
406 };
407 
408 /// AnalysisState provides a variety of helper functions for dealing with
409 /// tensor values.
411 public:
412  /// Determine which OpOperand* will alias with `value` if the op is
413  /// bufferized in place. Return all tensor OpOperand* if the op is not
414  /// bufferizable.
416 
417  /// Determine which Value will alias with `opOperand` if the op is bufferized
418  /// in place. Return all tensor Values if the op is not bufferizable.
420 
421  /// Return true if `opOperand` bufferizes to a memory read. Return `true` if
422  /// the op is not bufferizable.
423  bool bufferizesToMemoryRead(OpOperand &opOperand) const;
424 
425  /// Return true if `opOperand` bufferizes to a memory write. Return true` if
426  /// the op is not bufferizable.
427  bool bufferizesToMemoryWrite(OpOperand &opOperand) const;
428 
429  /// Return true if the given `value` bufferizes to a memory write. Return
430  /// true if the value is a block argument. Return `true` if the defining op is
431  /// not bufferizable. Otherwise, consult the BufferizableOpInterface.
432  bool bufferizesToMemoryWrite(Value value) const;
433 
434  /// Return true if `opOperand` does neither read nor write but bufferizes to
435  /// an alias. Return false if the op is not bufferizable.
436  bool bufferizesToAliasOnly(OpOperand &opOperand) const;
437 
438  /// Return true if a copy can always be avoided when allocating a new tensor
439  /// for the given OpOperand.
440  bool canOmitTensorCopy(OpOperand &opOperand) const;
441 
442  /// Return true if the given value is read by an op that bufferizes to a
443  /// memory read. Also takes into account ops that create an alias but do not
444  /// read by themselves (e.g., ExtractSliceOp).
445  bool isValueRead(Value value) const;
446 
447  /// Starting from `value`, follow the use-def chain in reverse, always
448  /// selecting the aliasing OpOperands. Find and return Values for which
449  /// `condition` evaluates to true. OpOperands of such matching Values are not
450  /// traversed any further.
451  ///
452  /// When reaching the end of a chain, also return the last Value of that
453  /// chain if `config.alwaysIncludeLeaves` is set.
454  ///
455  /// Example:
456  ///
457  /// 8
458  /// |
459  /// 6* 7* +-----+----+
460  /// | | | |
461  /// 2* 3 4* 5
462  /// | | | |
463  /// +----------+----------+----------+
464  /// |
465  /// 1
466  ///
467  /// In the above example, Values with a star satisfy the condition. When
468  /// starting the traversal from Value 1, the resulting SetVector is:
469  /// { 2, 7, 8, 5 }
470  ///
471  /// Additional stopping conditions for the traversal can be specified in
472  /// `config`.
474  Value value, llvm::function_ref<bool(Value)> condition,
475  TraversalConfig config = TraversalConfig()) const;
476 
477  /// Find the values that may define the contents of the given value at
478  /// runtime. A block argument is always a definition. An OpResult is a
479  /// definition if it bufferizes to memory write. If it does not bufferize to
480  /// a memory write but has aliasing operands, we continue the lookup on these
481  /// values.
482  ///
483  /// Example: %r = tensor.insert %f into %t[%c0] : tensor<?xf32>
484  /// findDefinitions(%r) = {%r} because %r bufferizes to memory write.
485  ///
486  /// Example: %r = tensor.empty() : tensor<10xf32>
487  /// findDefinitions(%r) = {} because tensor.empty does not the define the
488  /// contents of its result (i.e., it does not bufferize to a memory write)
489  /// and it has no aliasing OpOperands.
490  ///
491  /// Example:
492  /// %a = arith.constant ... : tensor<10xf32>
493  /// %b1 = tensor.insert %f into %t : tensor<50xf32>
494  /// %b2 = tensor.extract_slice %b1[0][10][1] : tensor<50xf32> tensor<10xf32>
495  /// %r = arith.select %cond, %a, %b : tensor<10xf32>
496  /// findDefinitions(%r) = {%a, %b1}. %r and %b2 are skipped (lookup continues
497  /// in the operands) because their defining ops do not define the contents of
498  /// the tensor.
499  ///
500  /// Example:
501  /// %a = tensor.empty() : tensor<10xf32>
502  /// %b = arith.constant ... : tensor<10xf32>
503  /// %r = arith.select %cond, %a, %b : tensor<10xf32>
504  /// findDefinitions(%r) = {%b}. %a is excluded because it does not define the
505  /// contents of the tensor.
506  ///
507  /// Note: OpResults of unknown ops are handled conservatively and assumed to
508  /// be definitions.
510 
511  /// Return `true` if the given OpResult has been decided to bufferize inplace.
512  virtual bool isInPlace(OpOperand &opOperand) const;
513 
514  /// Return true if `v1` and `v2` bufferize to equivalent buffers.
515  virtual bool areEquivalentBufferizedValues(Value v1, Value v2) const;
516 
517  /// Return true if `v1` and `v2` may bufferize to aliasing buffers.
518  virtual bool areAliasingBufferizedValues(Value v1, Value v2) const;
519 
520  /// Return `true` if the given tensor has undefined contents.
521  virtual bool hasUndefinedContents(OpOperand *opOperand) const;
522 
523  /// Return a reference to the BufferizationOptions.
524  const BufferizationOptions &getOptions() const { return options; }
525 
526  AnalysisState(const BufferizationOptions &options);
527 
528  // AnalysisState should be passed as a reference.
529  AnalysisState(const AnalysisState &) = delete;
530 
531  virtual ~AnalysisState() = default;
532 
533  static bool classof(const AnalysisState *base) { return true; }
534 
535  TypeID getType() const { return type; }
536 
537  /// Return the closest enclosing repetitive region around the given op.
539  const BufferizationOptions &options);
540 
541  /// Return the closest enclosing repetitive region around the place where the
542  /// given value is defined.
544  const BufferizationOptions &options);
545 
546  /// Return the closest enclosing repetitive region around the given block.
548  const BufferizationOptions &options);
549 
550  virtual void resetCache();
551 
552 protected:
553  AnalysisState(const BufferizationOptions &options, TypeID type);
554 
555 private:
556  /// A reference to current bufferization options.
557  const BufferizationOptions &options;
558 
559  /// The type of analysis.
560  TypeID type;
561 
562  /// Cache containing closest ancestor repetitive Region.
564  enclosingRepetitiveRegionCache;
565 };
566 
567 /// Create an AllocTensorOp for the given shaped value (memref or tensor).
568 /// If `copy` is set, the shaped value is copied. Otherwise, a tensor with
569 /// undefined contents is allocated.
572  const BufferizationOptions &options,
573  bool copy = true);
574 
575 /// Lookup the buffer for the given value. If the value was not bufferized
576 /// yet, wrap it in a ToMemrefOp. Otherwise, it is the result of a ToTensorOp,
577 /// from which the memref operand is returned.
579  const BufferizationOptions &options);
580 
581 /// Return the buffer type for a given Value (tensor) after bufferization
582 /// without bufferizing any IR.
583 ///
584 /// Note: It should be sufficient to call `getBuffer()->getType()` in most
585 /// cases. However, when a buffer type should be predicted without modifying any
586 /// IR, this function can be used.
587 ///
588 /// This function is a wrapper around BufferizableOpInterface::getBufferType.
590  const BufferizationOptions &options);
591 
592 /// Return the buffer type for a given Value (tensor) after bufferization
593 /// without bufferizing any IR. This function (and not the other overload
594 /// without `invocationStack`) can be used from `getBufferType` implementations
595 /// of the `BufferizableOpInterface`.
596 ///
597 /// Note: It should be sufficient to call `getBuffer()->getType()` in most
598 /// cases. However, when a buffer type should be predicted without modifying any
599 /// IR, this function can be used.
600 ///
601 /// This function is a wrapper around `BufferizableOpInterface::getBufferType`.
603  const BufferizationOptions &options,
604  SmallVector<Value> &invocationStack);
605 
606 /// Return "true" if the given op has tensor semantics and should be bufferized.
607 /// If the op is bufferizable, the BufferizableOpInterface is queried.
608 /// Otherwise, an op has tensor semantics if it has tensor operands, tensor
609 /// op results and/or tensor block arguments.
610 bool hasTensorSemantics(Operation *op);
611 
612 /// Replace an op with replacement values. The op is deleted. Tensor OpResults
613 /// must be replaced with memref values.
615  ValueRange values);
616 
617 /// Replace an op with a new op. The new op must have the same number of
618 /// results as the replaced op. The new op may not return any tensor values.
619 template <typename OpTy, typename... Args>
621  Args &&...args) {
622  auto newOp = rewriter.create<OpTy>(op->getLoc(), std::forward<Args>(args)...);
623  replaceOpWithBufferizedValues(rewriter, op, newOp->getResults());
624  return newOp;
625 }
626 
627 /// Return a MemRefType to which the type of the given value can be bufferized.
628 ///
629 /// If possible, op bufferization implementations should not use this function
630 /// and instead infer precise memref types for tensor results by themselves.
631 ///
632 /// Unless a layout map was specified, `options.unknownTypeConverterFn`
633 /// determines what kind of layout map will be used. For best composability
634 /// (without copies), the fully dynamic layout map is used by default.
635 ///
636 /// Note: Canonicalization patterns could clean up layout maps and infer more
637 /// precise layout maps after bufferization. However, many possible
638 /// canonicalizations are currently not implemented.
639 BaseMemRefType getMemRefType(Value value, const BufferizationOptions &options,
640  MemRefLayoutAttrInterface layout = {},
641  Attribute memorySpace = nullptr);
642 
643 /// Return a MemRef type with fully dynamic layout. If the given tensor type
644 /// is unranked, return an unranked MemRef type.
645 BaseMemRefType
646 getMemRefTypeWithFullyDynamicLayout(TensorType tensorType,
647  Attribute memorySpace = nullptr);
648 
649 /// Return a MemRef type with a static identity layout (i.e., no layout map). If
650 /// the given tensor type is unranked, return an unranked MemRef type.
651 BaseMemRefType
652 getMemRefTypeWithStaticIdentityLayout(TensorType tensorType,
653  Attribute memorySpace = nullptr);
654 
655 /// Return the owner of the given value. In case of a BlockArgument that is the
656 /// owner of the block. In case of an OpResult that is the defining op.
657 Operation *getOwnerOfValue(Value value);
658 
659 /// Assuming that the given region is repetitive, find the next enclosing
660 /// repetitive region.
661 Region *getNextEnclosingRepetitiveRegion(Region *region,
662  const BufferizationOptions &options);
663 
664 /// If `region` is a parallel region, return `region`. Otherwise, find the first
665 /// enclosing parallel region of `region`. If there is no such region, return
666 /// "nullptr".
667 ///
668 /// Note: Whether a region is parallel or sequential is queried from the
669 /// `BufferizableOpInterface`.
670 Region *getParallelRegion(Region *region, const BufferizationOptions &options);
671 
672 namespace detail {
673 /// This is the default implementation of
674 /// BufferizableOpInterface::getAliasingOpOperands. Should not be called from
675 /// other places.
677  const AnalysisState &state);
678 
679 /// This is the default implementation of
680 /// BufferizableOpInterface::getBufferType. Should not be called from other
681 /// places.
684  SmallVector<Value> &invocationStack);
685 
686 /// This is the default implementation of
687 /// BufferizableOpInterface::resultBufferizesToMemoryWrite. Should not be called
688 /// from other places.
690  const AnalysisState &state);
691 
692 /// This is the default implementation of
693 /// BufferizableOpInterface::isRepetitiveRegion. Should not be called from other
694 /// places.
695 bool defaultIsRepetitiveRegion(BufferizableOpInterface bufferizableOp,
696  unsigned index);
697 
698 /// This is the default implementation of getAliasingOpOperands in case the
699 /// defining op does not implement the BufferizableOpInterface.
701 
702 /// This is the default implementation of getAliasingValues in case the owner
703 /// op does not implement the BufferizableOpInterface.
705 
706 /// This is the default implementation of
707 /// BufferizableOpInterface::hasTensorSemantics
709 } // namespace detail
710 
711 } // namespace bufferization
712 } // namespace mlir
713 
715 
716 //===----------------------------------------------------------------------===//
717 // Bufferization Interfaces
718 //===----------------------------------------------------------------------===//
719 
720 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h.inc"
721 
722 #endif // MLIR_DIALECT_BUFFERIZATION_IR_BUFFERIZABLEOPINTERFACE_H_
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
static llvm::ManagedStatic< PassManagerOptions > options
#define MLIR_DECLARE_EXPLICIT_TYPE_ID(CLASS_NAME)
Definition: TypeID.h:249
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class provides a shared interface for ranked and unranked memref types.
Definition: BuiltinTypes.h:138
Block represents an ordered list of Operations.
Definition: Block.h:30
This class provides support for representing a failure result, or a valid value of type T.
Definition: LogicalResult.h:78
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:63
This class helps build Operations.
Definition: Builders.h:209
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:464
This class represents an operand of an operation.
Definition: Value.h:263
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
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:399
Tensor types represent multi-dimensional arrays, and have two variants: RankedTensorType and Unranked...
Definition: BuiltinTypes.h:91
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:104
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:378
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
AliasList(std::initializer_list< T > elems)
Create a list of aliases.
AliasList()=default
Create an empty list of aliases.
AliasList(SmallVector< T > &&aliases)
Create a list of aliases.
AnalysisState provides a variety of helper functions for dealing with tensor values.
bool isValueRead(Value value) const
Return true if the given value is read by an op that bufferizes to a memory read.
AliasingValueList getAliasingValues(OpOperand &opOperand) const
Determine which Value will alias with opOperand if the op is bufferized in place.
virtual bool areAliasingBufferizedValues(Value v1, Value v2) const
Return true if v1 and v2 may bufferize to aliasing buffers.
virtual bool hasUndefinedContents(OpOperand *opOperand) const
Return true if the given tensor has undefined contents.
bool canOmitTensorCopy(OpOperand &opOperand) const
Return true if a copy can always be avoided when allocating a new tensor for the given OpOperand.
bool bufferizesToMemoryWrite(OpOperand &opOperand) const
Return true if opOperand bufferizes to a memory write.
virtual bool isInPlace(OpOperand &opOperand) const
Return true if the given OpResult has been decided to bufferize inplace.
bool bufferizesToAliasOnly(OpOperand &opOperand) const
Return true if opOperand does neither read nor write but bufferizes to an alias.
AliasingOpOperandList getAliasingOpOperands(Value value) const
Determine which OpOperand* will alias with value if the op is bufferized in place.
AnalysisState(const BufferizationOptions &options)
Region * getEnclosingRepetitiveRegion(Operation *op, const BufferizationOptions &options)
Return the closest enclosing repetitive region around the given op.
const BufferizationOptions & getOptions() const
Return a reference to the BufferizationOptions.
bool bufferizesToMemoryRead(OpOperand &opOperand) const
Return true if opOperand bufferizes to a memory read.
SetVector< Value > findValueInReverseUseDefChain(Value value, llvm::function_ref< bool(Value)> condition, TraversalConfig config=TraversalConfig()) const
Starting from value, follow the use-def chain in reverse, always selecting the aliasing OpOperands.
SetVector< Value > findDefinitions(Value value) const
Find the values that may define the contents of the given value at runtime.
static bool classof(const AnalysisState *base)
virtual bool areEquivalentBufferizedValues(Value v1, Value v2) const
Return true if v1 and v2 bufferize to equivalent buffers.
AnalysisState(const AnalysisState &)=delete
void denyOperation()
Deny the given ops.
void allowOperation(StringRef opName)
Allow the given op.
void denyOperation(StringRef opName)
Deny the given op.
void denyDialect()
Deny the given dialects.
void allowOperation(Entry::FilterFn fn)
Allow ops that are matched by fn.
void allowDialect()
Allow the given dialects.
void allowDialect(StringRef dialectNamespace)
Allow the given dialect.
void denyOperation(Entry::FilterFn fn)
Deny ops that are matched by fn.
bool isOpAllowed(Operation *op) const
Return whether the op is allowed or not.
void allowOperation()
Allow the given ops.
AliasingOpOperandList defaultGetAliasingOpOperands(Value value, const AnalysisState &state)
This is the default implementation of BufferizableOpInterface::getAliasingOpOperands.
bool defaultResultBufferizesToMemoryWrite(OpResult opResult, const AnalysisState &state)
This is the default implementation of BufferizableOpInterface::resultBufferizesToMemoryWrite.
AliasingValueList unknownGetAliasingValues(OpOperand &opOperand)
This is the default implementation of getAliasingValues in case the owner op does not implement the B...
bool defaultIsRepetitiveRegion(BufferizableOpInterface bufferizableOp, unsigned index)
This is the default implementation of BufferizableOpInterface::isRepetitiveRegion.
AliasingOpOperandList unknownGetAliasingOpOperands(Value value)
This is the default implementation of getAliasingOpOperands in case the defining op does not implemen...
bool defaultHasTensorSemantics(Operation *op)
This is the default implementation of BufferizableOpInterface::hasTensorSemantics.
FailureOr< BaseMemRefType > defaultGetBufferType(Value value, const BufferizationOptions &options, SmallVector< Value > &invocationStack)
This is the default implementation of BufferizableOpInterface::getBufferType.
void replaceOpWithBufferizedValues(RewriterBase &rewriter, Operation *op, ValueRange values)
Replace an op with replacement values.
BaseMemRefType getMemRefTypeWithStaticIdentityLayout(TensorType tensorType, Attribute memorySpace=nullptr)
Return a MemRef type with a static identity layout (i.e., no layout map).
Operation * getOwnerOfValue(Value value)
Return the owner of the given value.
BaseMemRefType getMemRefType(Value value, const BufferizationOptions &options, MemRefLayoutAttrInterface layout={}, Attribute memorySpace=nullptr)
Return a MemRefType to which the type of the given value can be bufferized.
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.
OpTy replaceOpWithNewBufferizedOp(RewriterBase &rewriter, Operation *op, Args &&...args)
Replace an op with a new op.
FailureOr< Value > allocateTensorForShapedValue(OpBuilder &b, Location loc, Value shapedValue, const BufferizationOptions &options, bool copy=true)
Create an AllocTensorOp for the given shaped value (memref or tensor).
FailureOr< BaseMemRefType > getBufferType(Value value, const BufferizationOptions &options)
Return the buffer type for a given Value (tensor) after bufferization without bufferizing any IR.
FailureOr< Value > getBuffer(RewriterBase &rewriter, Value value, const BufferizationOptions &options)
Lookup the buffer for the given value.
BaseMemRefType getMemRefTypeWithFullyDynamicLayout(TensorType tensorType, Attribute memorySpace=nullptr)
Return a MemRef type with fully dynamic layout.
bool hasTensorSemantics(Operation *op)
Return "true" if the given op has tensor semantics and should be bufferized.
BufferRelation
Specifies a fine-grain relationship between buffers to enable more analysis.
Include the generated interface declarations.
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26
AliasingOpOperand(OpOperand *opOperand, BufferRelation relation, bool isDefinite=true)
AliasingValue(Value value, BufferRelation relation, bool isDefinite=true)
Options for BufferizableOpInterface-based bufferization.
bool copyBeforeWrite
If set to true, the analysis is skipped.
unsigned analysisFuzzerSeed
Seed for the analysis fuzzer.
std::function< void(AnalysisState &)> AnalysisStateInitFn
Initializer function for analysis state.
void setFunctionBoundaryTypeConversion(LayoutMapOption layoutMapOption)
This function controls buffer types on function signatures.
bool allowUnknownOps
Specifies whether not bufferizable ops are allowed in the input.
BufferizableOpInterface dynCastBufferizableOp(Operation *op) const
Try to cast the given op to BufferizableOpInterface if the op is allow listed.
bool inferFunctionResultLayout
If true, function result types are inferred from the body of the function.
std::function< BaseMemRefType(Value, Attribute memorySpace, const BufferizationOptions &)> UnknownTypeConverterFn
Tensor -> MemRef type converter.
unsigned int bufferAlignment
Buffer alignment for new memory allocations.
FunctionArgTypeConverterFn functionArgTypeConverterFn
Type converter from tensors to memrefs.
bool printConflicts
If set to true, the IR is annotated with details about RaW conflicts.
std::function< std::optional< Attribute >(TensorType t)> DefaultMemorySpaceFn
std::function< BaseMemRefType(TensorType, Attribute memorySpace, func::FuncOp, const BufferizationOptions &)> FunctionArgTypeConverterFn
Tensor -> MemRef type converter.
std::optional< AllocationFn > allocationFn
Helper functions for allocation and memory copying.
bool testAnalysisOnly
If set to true, does not modify the IR apart from adding attributes (for checking the results of the ...
bool enforceAliasingInvariants
Certain ops have aliasing OpOperand/OpResult invariants (e.g., scf.for).
OpFilter opFilter
A filter that specifies which ops should be bufferized and which ops should be ignored.
bool isOpAllowed(Operation *op) const
Return true if the given op should be bufferized.
UnknownTypeConverterFn unknownTypeConverterFn
Type converter from tensors to memrefs.
bool bufferizeFunctionBoundaries
Specifies whether function boundaries (ops in the func dialect) should be bufferized or not.
std::function< LogicalResult(OpBuilder &, Location, Value, Value)> MemCpyFn
Memcpy function: Generate a memcpy between two buffers.
FailureOr< Value > createAlloc(OpBuilder &b, Location loc, MemRefType type, ValueRange dynShape) const
Create a memref allocation with the given type and dynamic extents.
std::function< FailureOr< Value >(OpBuilder &, Location, MemRefType, ValueRange, unsigned int)> AllocationFn
Allocator function: Generate a memref allocation with the given type, dynamic extents and alignment.
LogicalResult createMemCpy(OpBuilder &b, Location loc, Value from, Value to) const
Creates a memcpy between two given buffers.
SmallVector< AnalysisStateInitFn > stateInitializers
Initializer functions for analysis state.
FilterType
Filter type: A filter can either be a DENY filter or an ALLOW filter.
std::function< bool(Operation *)> FilterFn
If the filter function evaluates to true, the filter matches.
Traversal parameters for findValueInReverseUseDefChain.
bool followUnknownOps
Specifies whether unknown/non-bufferizable/ops not included in the OpFilter of BufferizationOptions s...
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 followInPlaceOnly
Specifies whether out-of-place/undecided OpOperands should be followed.
bool followEquivalentOnly
Specifies whether non-equivalent OpOperands should be followed.
bool revisitAlreadyVisitedValues
Specifies whether already visited values should be visited again.