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