MLIR  21.0.0git
PatternMatch.h
Go to the documentation of this file.
1 //===- PatternMatch.h - PatternMatcher classes -------==---------*- 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_IR_PATTERNMATCH_H
10 #define MLIR_IR_PATTERNMATCH_H
11 
12 #include "mlir/IR/Builders.h"
13 #include "mlir/IR/BuiltinOps.h"
14 #include "llvm/ADT/FunctionExtras.h"
15 #include "llvm/Support/TypeName.h"
16 #include <optional>
17 
19 namespace mlir {
20 
21 class PatternRewriter;
22 
23 //===----------------------------------------------------------------------===//
24 // PatternBenefit class
25 //===----------------------------------------------------------------------===//
26 
27 /// This class represents the benefit of a pattern match in a unitless scheme
28 /// that ranges from 0 (very little benefit) to 65K. The most common unit to
29 /// use here is the "number of operations matched" by the pattern.
30 ///
31 /// This also has a sentinel representation that can be used for patterns that
32 /// fail to match.
33 ///
35  enum { ImpossibleToMatchSentinel = 65535 };
36 
37 public:
38  PatternBenefit() = default;
39  PatternBenefit(unsigned benefit);
40  PatternBenefit(const PatternBenefit &) = default;
42 
44  bool isImpossibleToMatch() const { return *this == impossibleToMatch(); }
45 
46  /// If the corresponding pattern can match, return its benefit. If the
47  // corresponding pattern isImpossibleToMatch() then this aborts.
48  unsigned short getBenefit() const;
49 
50  bool operator==(const PatternBenefit &rhs) const {
51  return representation == rhs.representation;
52  }
53  bool operator!=(const PatternBenefit &rhs) const { return !(*this == rhs); }
54  bool operator<(const PatternBenefit &rhs) const {
55  return representation < rhs.representation;
56  }
57  bool operator>(const PatternBenefit &rhs) const { return rhs < *this; }
58  bool operator<=(const PatternBenefit &rhs) const { return !(*this > rhs); }
59  bool operator>=(const PatternBenefit &rhs) const { return !(*this < rhs); }
60 
61 private:
62  unsigned short representation{ImpossibleToMatchSentinel};
63 };
64 
65 //===----------------------------------------------------------------------===//
66 // Pattern
67 //===----------------------------------------------------------------------===//
68 
69 /// This class contains all of the data related to a pattern, but does not
70 /// contain any methods or logic for the actual matching. This class is solely
71 /// used to interface with the metadata of a pattern, such as the benefit or
72 /// root operation.
73 class Pattern {
74  /// This enum represents the kind of value used to select the root operations
75  /// that match this pattern.
76  enum class RootKind {
77  /// The pattern root matches "any" operation.
78  Any,
79  /// The pattern root is matched using a concrete operation name.
81  /// The pattern root is matched using an interface ID.
82  InterfaceID,
83  /// The patter root is matched using a trait ID.
84  TraitID
85  };
86 
87 public:
88  /// Return a list of operations that may be generated when rewriting an
89  /// operation instance with this pattern.
90  ArrayRef<OperationName> getGeneratedOps() const { return generatedOps; }
91 
92  /// Return the root node that this pattern matches. Patterns that can match
93  /// multiple root types return std::nullopt.
94  std::optional<OperationName> getRootKind() const {
95  if (rootKind == RootKind::OperationName)
96  return OperationName::getFromOpaquePointer(rootValue);
97  return std::nullopt;
98  }
99 
100  /// Return the interface ID used to match the root operation of this pattern.
101  /// If the pattern does not use an interface ID for deciding the root match,
102  /// this returns std::nullopt.
103  std::optional<TypeID> getRootInterfaceID() const {
104  if (rootKind == RootKind::InterfaceID)
105  return TypeID::getFromOpaquePointer(rootValue);
106  return std::nullopt;
107  }
108 
109  /// Return the trait ID used to match the root operation of this pattern.
110  /// If the pattern does not use a trait ID for deciding the root match, this
111  /// returns std::nullopt.
112  std::optional<TypeID> getRootTraitID() const {
113  if (rootKind == RootKind::TraitID)
114  return TypeID::getFromOpaquePointer(rootValue);
115  return std::nullopt;
116  }
117 
118  /// Return the benefit (the inverse of "cost") of matching this pattern. The
119  /// benefit of a Pattern is always static - rewrites that may have dynamic
120  /// benefit can be instantiated multiple times (different Pattern instances)
121  /// for each benefit that they may return, and be guarded by different match
122  /// condition predicates.
123  PatternBenefit getBenefit() const { return benefit; }
124 
125  /// Returns true if this pattern is known to result in recursive application,
126  /// i.e. this pattern may generate IR that also matches this pattern, but is
127  /// known to bound the recursion. This signals to a rewrite driver that it is
128  /// safe to apply this pattern recursively to generated IR.
130  return contextAndHasBoundedRecursion.getInt();
131  }
132 
133  /// Return the MLIRContext used to create this pattern.
135  return contextAndHasBoundedRecursion.getPointer();
136  }
137 
138  /// Return a readable name for this pattern. This name should only be used for
139  /// debugging purposes, and may be empty.
140  StringRef getDebugName() const { return debugName; }
141 
142  /// Set the human readable debug name used for this pattern. This name will
143  /// only be used for debugging purposes.
144  void setDebugName(StringRef name) { debugName = name; }
145 
146  /// Return the set of debug labels attached to this pattern.
147  ArrayRef<StringRef> getDebugLabels() const { return debugLabels; }
148 
149  /// Add the provided debug labels to this pattern.
151  debugLabels.append(labels.begin(), labels.end());
152  }
153  void addDebugLabels(StringRef label) { debugLabels.push_back(label); }
154 
155 protected:
156  /// This class acts as a special tag that makes the desire to match "any"
157  /// operation type explicit. This helps to avoid unnecessary usages of this
158  /// feature, and ensures that the user is making a conscious decision.
159  struct MatchAnyOpTypeTag {};
160  /// This class acts as a special tag that makes the desire to match any
161  /// operation that implements a given interface explicit. This helps to avoid
162  /// unnecessary usages of this feature, and ensures that the user is making a
163  /// conscious decision.
165  /// This class acts as a special tag that makes the desire to match any
166  /// operation that implements a given trait explicit. This helps to avoid
167  /// unnecessary usages of this feature, and ensures that the user is making a
168  /// conscious decision.
170 
171  /// Construct a pattern with a certain benefit that matches the operation
172  /// with the given root name.
173  Pattern(StringRef rootName, PatternBenefit benefit, MLIRContext *context,
174  ArrayRef<StringRef> generatedNames = {});
175  /// Construct a pattern that may match any operation type. `generatedNames`
176  /// contains the names of operations that may be generated during a successful
177  /// rewrite. `MatchAnyOpTypeTag` is just a tag to ensure that the "match any"
178  /// behavior is what the user actually desired, `MatchAnyOpTypeTag()` should
179  /// always be supplied here.
180  Pattern(MatchAnyOpTypeTag tag, PatternBenefit benefit, MLIRContext *context,
181  ArrayRef<StringRef> generatedNames = {});
182  /// Construct a pattern that may match any operation that implements the
183  /// interface defined by the provided `interfaceID`. `generatedNames` contains
184  /// the names of operations that may be generated during a successful rewrite.
185  /// `MatchInterfaceOpTypeTag` is just a tag to ensure that the "match
186  /// interface" behavior is what the user actually desired,
187  /// `MatchInterfaceOpTypeTag()` should always be supplied here.
188  Pattern(MatchInterfaceOpTypeTag tag, TypeID interfaceID,
189  PatternBenefit benefit, MLIRContext *context,
190  ArrayRef<StringRef> generatedNames = {});
191  /// Construct a pattern that may match any operation that implements the
192  /// trait defined by the provided `traitID`. `generatedNames` contains the
193  /// names of operations that may be generated during a successful rewrite.
194  /// `MatchTraitOpTypeTag` is just a tag to ensure that the "match trait"
195  /// behavior is what the user actually desired, `MatchTraitOpTypeTag()` should
196  /// always be supplied here.
197  Pattern(MatchTraitOpTypeTag tag, TypeID traitID, PatternBenefit benefit,
198  MLIRContext *context, ArrayRef<StringRef> generatedNames = {});
199 
200  /// Set the flag detailing if this pattern has bounded rewrite recursion or
201  /// not.
202  void setHasBoundedRewriteRecursion(bool hasBoundedRecursionArg = true) {
203  contextAndHasBoundedRecursion.setInt(hasBoundedRecursionArg);
204  }
205 
206 private:
207  Pattern(const void *rootValue, RootKind rootKind,
208  ArrayRef<StringRef> generatedNames, PatternBenefit benefit,
209  MLIRContext *context);
210 
211  /// The value used to match the root operation of the pattern.
212  const void *rootValue;
213  RootKind rootKind;
214 
215  /// The expected benefit of matching this pattern.
216  const PatternBenefit benefit;
217 
218  /// The context this pattern was created from, and a boolean flag indicating
219  /// whether this pattern has bounded recursion or not.
220  llvm::PointerIntPair<MLIRContext *, 1, bool> contextAndHasBoundedRecursion;
221 
222  /// A list of the potential operations that may be generated when rewriting
223  /// an op with this pattern.
224  SmallVector<OperationName, 2> generatedOps;
225 
226  /// A readable name for this pattern. May be empty.
227  StringRef debugName;
228 
229  /// The set of debug labels attached to this pattern.
230  SmallVector<StringRef, 0> debugLabels;
231 };
232 
233 //===----------------------------------------------------------------------===//
234 // RewritePattern
235 //===----------------------------------------------------------------------===//
236 
237 namespace detail {
238 /// Helper class that derives from a RewritePattern class and provides separate
239 /// `match` and `rewrite` entry points instead of a combined `matchAndRewrite`.
240 ///
241 /// This class is deprecated. Use `matchAndRewrite` instead of separate `match`
242 /// and `rewrite`.
243 template <typename PatternT>
245  using PatternT::PatternT;
246 
247  /// Attempt to match against IR rooted at the specified operation, which is
248  /// the same operation kind as getRootKind().
249  ///
250  /// Note: This function must not modify the IR.
251  virtual LogicalResult match(typename PatternT::OperationT op) const = 0;
252 
253  /// Rewrite the IR rooted at the specified operation with the result of
254  /// this pattern, generating any new operations with the specified
255  /// rewriter.
256  virtual void rewrite(typename PatternT::OperationT op,
257  PatternRewriter &rewriter) const = 0;
258 
259  LogicalResult matchAndRewrite(typename PatternT::OperationT op,
260  PatternRewriter &rewriter) const final {
261  if (succeeded(match(op))) {
262  rewrite(op, rewriter);
263  return success();
264  }
265  return failure();
266  }
267 };
268 } // namespace detail
269 
270 /// RewritePattern is the common base class for all DAG to DAG replacements.
271 class RewritePattern : public Pattern {
272 public:
274 
275  /// `SplitMatchAndRewrite` is deprecated. Use `matchAndRewrite` instead of
276  /// separate `match` and `rewrite`.
278 
279  virtual ~RewritePattern() = default;
280 
281  /// Attempt to match against code rooted at the specified operation,
282  /// which is the same operation code as getRootKind(). If successful, perform
283  /// the rewrite.
284  ///
285  /// Note: Implementations must modify the IR if and only if the function
286  /// returns "success".
287  virtual LogicalResult matchAndRewrite(Operation *op,
288  PatternRewriter &rewriter) const = 0;
289 
290  /// This method provides a convenient interface for creating and initializing
291  /// derived rewrite patterns of the given type `T`.
292  template <typename T, typename... Args>
293  static std::unique_ptr<T> create(Args &&...args) {
294  std::unique_ptr<T> pattern =
295  std::make_unique<T>(std::forward<Args>(args)...);
296  initializePattern<T>(*pattern);
297 
298  // Set a default debug name if one wasn't provided.
299  if (pattern->getDebugName().empty())
300  pattern->setDebugName(llvm::getTypeName<T>());
301  return pattern;
302  }
303 
304 protected:
305  /// Inherit the base constructors from `Pattern`.
306  using Pattern::Pattern;
307 
308 private:
309  /// Trait to check if T provides a `initialize` method.
310  template <typename T, typename... Args>
311  using has_initialize = decltype(std::declval<T>().initialize());
312  template <typename T>
313  using detect_has_initialize = llvm::is_detected<has_initialize, T>;
314 
315  /// Initialize the derived pattern by calling its `initialize` method.
316  template <typename T>
317  static std::enable_if_t<detect_has_initialize<T>::value>
318  initializePattern(T &pattern) {
319  pattern.initialize();
320  }
321  /// Empty derived pattern initializer for patterns that do not have an
322  /// initialize method.
323  template <typename T>
324  static std::enable_if_t<!detect_has_initialize<T>::value>
325  initializePattern(T &) {}
326 
327  /// An anchor for the virtual table.
328  virtual void anchor();
329 };
330 
331 namespace detail {
332 /// OpOrInterfaceRewritePatternBase is a wrapper around RewritePattern that
333 /// allows for matching and rewriting against an instance of a derived operation
334 /// class or Interface.
335 template <typename SourceOp>
337  using OperationT = SourceOp;
338  using RewritePattern::RewritePattern;
339 
340  /// Wrapper around the RewritePattern method that passes the derived op type.
341  LogicalResult matchAndRewrite(Operation *op,
342  PatternRewriter &rewriter) const final {
343  return matchAndRewrite(cast<SourceOp>(op), rewriter);
344  }
345 
346  /// Method that operates on the SourceOp type. Must be overridden by the
347  /// derived pattern class.
348  virtual LogicalResult matchAndRewrite(SourceOp op,
349  PatternRewriter &rewriter) const = 0;
350 };
351 } // namespace detail
352 
353 /// OpRewritePattern is a wrapper around RewritePattern that allows for
354 /// matching and rewriting against an instance of a derived operation class as
355 /// opposed to a raw Operation.
356 template <typename SourceOp>
358  : public detail::OpOrInterfaceRewritePatternBase<SourceOp> {
359 
360  /// `SplitMatchAndRewrite` is deprecated. Use `matchAndRewrite` instead of
361  /// separate `match` and `rewrite`.
364 
365  /// Patterns must specify the root operation name they match against, and can
366  /// also specify the benefit of the pattern matching and a list of generated
367  /// ops.
369  ArrayRef<StringRef> generatedNames = {})
371  SourceOp::getOperationName(), benefit, context, generatedNames) {}
372 };
373 
374 /// OpInterfaceRewritePattern is a wrapper around RewritePattern that allows for
375 /// matching and rewriting against an instance of an operation interface instead
376 /// of a raw Operation.
377 template <typename SourceOp>
379  : public detail::OpOrInterfaceRewritePatternBase<SourceOp> {
380 
381  /// `SplitMatchAndRewrite` is deprecated. Use `matchAndRewrite` instead of
382  /// separate `match` and `rewrite`.
385 
387  : detail::OpOrInterfaceRewritePatternBase<SourceOp>(
388  Pattern::MatchInterfaceOpTypeTag(), SourceOp::getInterfaceID(),
389  benefit, context) {}
390 };
391 
392 /// OpTraitRewritePattern is a wrapper around RewritePattern that allows for
393 /// matching and rewriting against instances of an operation that possess a
394 /// given trait.
395 template <template <typename> class TraitType>
397 public:
400  benefit, context) {}
401 };
402 
403 //===----------------------------------------------------------------------===//
404 // RewriterBase
405 //===----------------------------------------------------------------------===//
406 
407 /// This class coordinates the application of a rewrite on a set of IR,
408 /// providing a way for clients to track mutations and create new operations.
409 /// This class serves as a common API for IR mutation between pattern rewrites
410 /// and non-pattern rewrites, and facilitates the development of shared
411 /// IR transformation utilities.
412 class RewriterBase : public OpBuilder {
413 public:
414  struct Listener : public OpBuilder::Listener {
416  : OpBuilder::Listener(ListenerBase::Kind::RewriterBaseListener) {}
417 
418  /// Notify the listener that the specified block is about to be erased.
419  /// At this point, the block has zero uses.
420  virtual void notifyBlockErased(Block *block) {}
421 
422  /// Notify the listener that the specified operation was modified in-place.
423  virtual void notifyOperationModified(Operation *op) {}
424 
425  /// Notify the listener that all uses of the specified operation's results
426  /// are about to be replaced with the results of another operation. This is
427  /// called before the uses of the old operation have been changed.
428  ///
429  /// By default, this function calls the "operation replaced with values"
430  /// notification.
432  Operation *replacement) {
433  notifyOperationReplaced(op, replacement->getResults());
434  }
435 
436  /// Notify the listener that all uses of the specified operation's results
437  /// are about to be replaced with the a range of values, potentially
438  /// produced by other operations. This is called before the uses of the
439  /// operation have been changed.
441  ValueRange replacement) {}
442 
443  /// Notify the listener that the specified operation is about to be erased.
444  /// At this point, the operation has zero uses.
445  ///
446  /// Note: This notification is not triggered when unlinking an operation.
447  virtual void notifyOperationErased(Operation *op) {}
448 
449  /// Notify the listener that the specified pattern is about to be applied
450  /// at the specified root operation.
451  virtual void notifyPatternBegin(const Pattern &pattern, Operation *op) {}
452 
453  /// Notify the listener that a pattern application finished with the
454  /// specified status. "success" indicates that the pattern was applied
455  /// successfully. "failure" indicates that the pattern could not be
456  /// applied. The pattern may have communicated the reason for the failure
457  /// with `notifyMatchFailure`.
458  virtual void notifyPatternEnd(const Pattern &pattern,
459  LogicalResult status) {}
460 
461  /// Notify the listener that the pattern failed to match, and provide a
462  /// callback to populate a diagnostic with the reason why the failure
463  /// occurred. This method allows for derived listeners to optionally hook
464  /// into the reason why a rewrite failed, and display it to users.
465  virtual void
467  function_ref<void(Diagnostic &)> reasonCallback) {}
468 
469  static bool classof(const OpBuilder::Listener *base);
470  };
471 
472  /// A listener that forwards all notifications to another listener. This
473  /// struct can be used as a base to create listener chains, so that multiple
474  /// listeners can be notified of IR changes.
477  : listener(listener),
478  rewriteListener(
479  dyn_cast_if_present<RewriterBase::Listener>(listener)) {}
480 
481  void notifyOperationInserted(Operation *op, InsertPoint previous) override {
482  if (listener)
483  listener->notifyOperationInserted(op, previous);
484  }
485  void notifyBlockInserted(Block *block, Region *previous,
486  Region::iterator previousIt) override {
487  if (listener)
488  listener->notifyBlockInserted(block, previous, previousIt);
489  }
490  void notifyBlockErased(Block *block) override {
491  if (rewriteListener)
492  rewriteListener->notifyBlockErased(block);
493  }
494  void notifyOperationModified(Operation *op) override {
495  if (rewriteListener)
496  rewriteListener->notifyOperationModified(op);
497  }
498  void notifyOperationReplaced(Operation *op, Operation *newOp) override {
499  if (rewriteListener)
500  rewriteListener->notifyOperationReplaced(op, newOp);
501  }
503  ValueRange replacement) override {
504  if (rewriteListener)
505  rewriteListener->notifyOperationReplaced(op, replacement);
506  }
507  void notifyOperationErased(Operation *op) override {
508  if (rewriteListener)
509  rewriteListener->notifyOperationErased(op);
510  }
511  void notifyPatternBegin(const Pattern &pattern, Operation *op) override {
512  if (rewriteListener)
513  rewriteListener->notifyPatternBegin(pattern, op);
514  }
515  void notifyPatternEnd(const Pattern &pattern,
516  LogicalResult status) override {
517  if (rewriteListener)
518  rewriteListener->notifyPatternEnd(pattern, status);
519  }
521  Location loc,
522  function_ref<void(Diagnostic &)> reasonCallback) override {
523  if (rewriteListener)
524  rewriteListener->notifyMatchFailure(loc, reasonCallback);
525  }
526 
527  private:
528  OpBuilder::Listener *listener;
529  RewriterBase::Listener *rewriteListener;
530  };
531 
532  /// Move the blocks that belong to "region" before the given position in
533  /// another region "parent". The two regions must be different. The caller
534  /// is responsible for creating or updating the operation transferring flow
535  /// of control to the region and passing it the correct block arguments.
536  void inlineRegionBefore(Region &region, Region &parent,
537  Region::iterator before);
538  void inlineRegionBefore(Region &region, Block *before);
539 
540  /// Replace the results of the given (original) operation with the specified
541  /// list of values (replacements). The result types of the given op and the
542  /// replacements must match. The original op is erased.
543  virtual void replaceOp(Operation *op, ValueRange newValues);
544 
545  /// Replace the results of the given (original) operation with the specified
546  /// new op (replacement). The result types of the two ops must match. The
547  /// original op is erased.
548  virtual void replaceOp(Operation *op, Operation *newOp);
549 
550  /// Replace the results of the given (original) op with a new op that is
551  /// created without verification (replacement). The result values of the two
552  /// ops must match. The original op is erased.
553  template <typename OpTy, typename... Args>
554  OpTy replaceOpWithNewOp(Operation *op, Args &&...args) {
555  auto newOp = create<OpTy>(op->getLoc(), std::forward<Args>(args)...);
556  replaceOp(op, newOp.getOperation());
557  return newOp;
558  }
559 
560  /// This method erases an operation that is known to have no uses.
561  virtual void eraseOp(Operation *op);
562 
563  /// This method erases all operations in a block.
564  virtual void eraseBlock(Block *block);
565 
566  /// Inline the operations of block 'source' into block 'dest' before the given
567  /// position. The source block will be deleted and must have no uses.
568  /// 'argValues' is used to replace the block arguments of 'source'.
569  ///
570  /// If the source block is inserted at the end of the dest block, the dest
571  /// block must have no successors. Similarly, if the source block is inserted
572  /// somewhere in the middle (or beginning) of the dest block, the source block
573  /// must have no successors. Otherwise, the resulting IR would have
574  /// unreachable operations.
575  virtual void inlineBlockBefore(Block *source, Block *dest,
576  Block::iterator before,
577  ValueRange argValues = std::nullopt);
578 
579  /// Inline the operations of block 'source' before the operation 'op'. The
580  /// source block will be deleted and must have no uses. 'argValues' is used to
581  /// replace the block arguments of 'source'
582  ///
583  /// The source block must have no successors. Otherwise, the resulting IR
584  /// would have unreachable operations.
585  void inlineBlockBefore(Block *source, Operation *op,
586  ValueRange argValues = std::nullopt);
587 
588  /// Inline the operations of block 'source' into the end of block 'dest'. The
589  /// source block will be deleted and must have no uses. 'argValues' is used to
590  /// replace the block arguments of 'source'
591  ///
592  /// The dest block must have no successors. Otherwise, the resulting IR would
593  /// have unreachable operation.
594  void mergeBlocks(Block *source, Block *dest,
595  ValueRange argValues = std::nullopt);
596 
597  /// Split the operations starting at "before" (inclusive) out of the given
598  /// block into a new block, and return it.
599  Block *splitBlock(Block *block, Block::iterator before);
600 
601  /// Unlink this operation from its current block and insert it right before
602  /// `existingOp` which may be in the same or another block in the same
603  /// function.
604  void moveOpBefore(Operation *op, Operation *existingOp);
605 
606  /// Unlink this operation from its current block and insert it right before
607  /// `iterator` in the specified block.
608  void moveOpBefore(Operation *op, Block *block, Block::iterator iterator);
609 
610  /// Unlink this operation from its current block and insert it right after
611  /// `existingOp` which may be in the same or another block in the same
612  /// function.
613  void moveOpAfter(Operation *op, Operation *existingOp);
614 
615  /// Unlink this operation from its current block and insert it right after
616  /// `iterator` in the specified block.
617  void moveOpAfter(Operation *op, Block *block, Block::iterator iterator);
618 
619  /// Unlink this block and insert it right before `existingBlock`.
620  void moveBlockBefore(Block *block, Block *anotherBlock);
621 
622  /// Unlink this block and insert it right before the location that the given
623  /// iterator points to in the given region.
624  void moveBlockBefore(Block *block, Region *region, Region::iterator iterator);
625 
626  /// This method is used to notify the rewriter that an in-place operation
627  /// modification is about to happen. A call to this function *must* be
628  /// followed by a call to either `finalizeOpModification` or
629  /// `cancelOpModification`. This is a minor efficiency win (it avoids creating
630  /// a new operation and removing the old one) but also often allows simpler
631  /// code in the client.
632  virtual void startOpModification(Operation *op) {}
633 
634  /// This method is used to signal the end of an in-place modification of the
635  /// given operation. This can only be called on operations that were provided
636  /// to a call to `startOpModification`.
637  virtual void finalizeOpModification(Operation *op);
638 
639  /// This method cancels a pending in-place modification. This can only be
640  /// called on operations that were provided to a call to
641  /// `startOpModification`.
642  virtual void cancelOpModification(Operation *op) {}
643 
644  /// This method is a utility wrapper around an in-place modification of an
645  /// operation. It wraps calls to `startOpModification` and
646  /// `finalizeOpModification` around the given callable.
647  template <typename CallableT>
648  void modifyOpInPlace(Operation *root, CallableT &&callable) {
649  startOpModification(root);
650  callable();
652  }
653 
654  /// Find uses of `from` and replace them with `to`. Also notify the listener
655  /// about every in-place op modification (for every use that was replaced).
656  void replaceAllUsesWith(Value from, Value to) {
657  for (OpOperand &operand : llvm::make_early_inc_range(from.getUses())) {
658  Operation *op = operand.getOwner();
659  modifyOpInPlace(op, [&]() { operand.set(to); });
660  }
661  }
662  void replaceAllUsesWith(Block *from, Block *to) {
663  for (BlockOperand &operand : llvm::make_early_inc_range(from->getUses())) {
664  Operation *op = operand.getOwner();
665  modifyOpInPlace(op, [&]() { operand.set(to); });
666  }
667  }
669  assert(from.size() == to.size() && "incorrect number of replacements");
670  for (auto it : llvm::zip(from, to))
671  replaceAllUsesWith(std::get<0>(it), std::get<1>(it));
672  }
673 
674  /// Find uses of `from` and replace them with `to`. Also notify the listener
675  /// about every in-place op modification (for every use that was replaced)
676  /// and that the `from` operation is about to be replaced.
677  ///
678  /// Note: This function cannot be called `replaceAllUsesWith` because the
679  /// overload resolution, when called with an op that can be implicitly
680  /// converted to a Value, would be ambiguous.
681  void replaceAllOpUsesWith(Operation *from, ValueRange to);
682  void replaceAllOpUsesWith(Operation *from, Operation *to);
683 
684  /// Find uses of `from` and replace them with `to` if the `functor` returns
685  /// true. Also notify the listener about every in-place op modification (for
686  /// every use that was replaced). The optional `allUsesReplaced` flag is set
687  /// to "true" if all uses were replaced.
688  void replaceUsesWithIf(Value from, Value to,
689  function_ref<bool(OpOperand &)> functor,
690  bool *allUsesReplaced = nullptr);
692  function_ref<bool(OpOperand &)> functor,
693  bool *allUsesReplaced = nullptr);
694  // Note: This function cannot be called `replaceOpUsesWithIf` because the
695  // overload resolution, when called with an op that can be implicitly
696  // converted to a Value, would be ambiguous.
698  function_ref<bool(OpOperand &)> functor,
699  bool *allUsesReplaced = nullptr) {
700  replaceUsesWithIf(from->getResults(), to, functor, allUsesReplaced);
701  }
702 
703  /// Find uses of `from` within `block` and replace them with `to`. Also notify
704  /// the listener about every in-place op modification (for every use that was
705  /// replaced). The optional `allUsesReplaced` flag is set to "true" if all
706  /// uses were replaced.
708  Block *block, bool *allUsesReplaced = nullptr) {
710  op, newValues,
711  [block](OpOperand &use) {
712  return block->getParentOp()->isProperAncestor(use.getOwner());
713  },
714  allUsesReplaced);
715  }
716 
717  /// Find uses of `from` and replace them with `to` except if the user is
718  /// `exceptedUser`. Also notify the listener about every in-place op
719  /// modification (for every use that was replaced).
720  void replaceAllUsesExcept(Value from, Value to, Operation *exceptedUser) {
721  return replaceUsesWithIf(from, to, [&](OpOperand &use) {
722  Operation *user = use.getOwner();
723  return user != exceptedUser;
724  });
725  }
726  void replaceAllUsesExcept(Value from, Value to,
727  const SmallPtrSetImpl<Operation *> &preservedUsers);
728 
729  /// Used to notify the listener that the IR failed to be rewritten because of
730  /// a match failure, and provide a callback to populate a diagnostic with the
731  /// reason why the failure occurred. This method allows for derived rewriters
732  /// to optionally hook into the reason why a rewrite failed, and display it to
733  /// users.
734  template <typename CallbackT>
735  std::enable_if_t<!std::is_convertible<CallbackT, Twine>::value, LogicalResult>
736  notifyMatchFailure(Location loc, CallbackT &&reasonCallback) {
737  if (auto *rewriteListener = dyn_cast_if_present<Listener>(listener))
738  rewriteListener->notifyMatchFailure(
739  loc, function_ref<void(Diagnostic &)>(reasonCallback));
740  return failure();
741  }
742  template <typename CallbackT>
743  std::enable_if_t<!std::is_convertible<CallbackT, Twine>::value, LogicalResult>
744  notifyMatchFailure(Operation *op, CallbackT &&reasonCallback) {
745  if (auto *rewriteListener = dyn_cast_if_present<Listener>(listener))
746  rewriteListener->notifyMatchFailure(
747  op->getLoc(), function_ref<void(Diagnostic &)>(reasonCallback));
748  return failure();
749  }
750  template <typename ArgT>
751  LogicalResult notifyMatchFailure(ArgT &&arg, const Twine &msg) {
752  return notifyMatchFailure(std::forward<ArgT>(arg),
753  [&](Diagnostic &diag) { diag << msg; });
754  }
755  template <typename ArgT>
756  LogicalResult notifyMatchFailure(ArgT &&arg, const char *msg) {
757  return notifyMatchFailure(std::forward<ArgT>(arg), Twine(msg));
758  }
759 
760 protected:
761  /// Initialize the builder.
762  explicit RewriterBase(MLIRContext *ctx,
763  OpBuilder::Listener *listener = nullptr)
764  : OpBuilder(ctx, listener) {}
765  explicit RewriterBase(const OpBuilder &otherBuilder)
766  : OpBuilder(otherBuilder) {}
768  : OpBuilder(op, listener) {}
769  virtual ~RewriterBase();
770 
771 private:
772  void operator=(const RewriterBase &) = delete;
773  RewriterBase(const RewriterBase &) = delete;
774 };
775 
776 //===----------------------------------------------------------------------===//
777 // IRRewriter
778 //===----------------------------------------------------------------------===//
779 
780 /// This class coordinates rewriting a piece of IR outside of a pattern rewrite,
781 /// providing a way to keep track of the mutations made to the IR. This class
782 /// should only be used in situations where another `RewriterBase` instance,
783 /// such as a `PatternRewriter`, is not available.
784 class IRRewriter : public RewriterBase {
785 public:
787  : RewriterBase(ctx, listener) {}
788  explicit IRRewriter(const OpBuilder &builder) : RewriterBase(builder) {}
790  : RewriterBase(op, listener) {}
791 };
792 
793 //===----------------------------------------------------------------------===//
794 // PatternRewriter
795 //===----------------------------------------------------------------------===//
796 
797 /// A special type of `RewriterBase` that coordinates the application of a
798 /// rewrite pattern on the current IR being matched, providing a way to keep
799 /// track of any mutations made. This class should be used to perform all
800 /// necessary IR mutations within a rewrite pattern, as the pattern driver may
801 /// be tracking various state that would be invalidated when a mutation takes
802 /// place.
804 public:
805  explicit PatternRewriter(MLIRContext *ctx) : RewriterBase(ctx) {}
807 
808  /// A hook used to indicate if the pattern rewriter can recover from failure
809  /// during the rewrite stage of a pattern. For example, if the pattern
810  /// rewriter supports rollback, it may progress smoothly even if IR was
811  /// changed during the rewrite.
812  virtual bool canRecoverFromRewriteFailure() const { return false; }
813 };
814 
815 } // namespace mlir
816 
817 // Optionally expose PDL pattern matching methods.
818 #include "PDLPatternMatch.h.inc"
819 
820 namespace mlir {
821 
822 //===----------------------------------------------------------------------===//
823 // RewritePatternSet
824 //===----------------------------------------------------------------------===//
825 
827  using NativePatternListT = std::vector<std::unique_ptr<RewritePattern>>;
828 
829 public:
830  RewritePatternSet(MLIRContext *context) : context(context) {}
831 
832  /// Construct a RewritePatternSet populated with the given pattern.
834  std::unique_ptr<RewritePattern> pattern)
835  : context(context) {
836  nativePatterns.emplace_back(std::move(pattern));
837  }
838  RewritePatternSet(PDLPatternModule &&pattern)
839  : context(pattern.getContext()), pdlPatterns(std::move(pattern)) {}
840 
841  MLIRContext *getContext() const { return context; }
842 
843  /// Return the native patterns held in this list.
844  NativePatternListT &getNativePatterns() { return nativePatterns; }
845 
846  /// Return the PDL patterns held in this list.
847  PDLPatternModule &getPDLPatterns() { return pdlPatterns; }
848 
849  /// Clear out all of the held patterns in this list.
850  void clear() {
851  nativePatterns.clear();
852  pdlPatterns.clear();
853  }
854 
855  //===--------------------------------------------------------------------===//
856  // 'add' methods for adding patterns to the set.
857  //===--------------------------------------------------------------------===//
858 
859  /// Add an instance of each of the pattern types 'Ts' to the pattern list with
860  /// the given arguments. Return a reference to `this` for chaining insertions.
861  /// Note: ConstructorArg is necessary here to separate the two variadic lists.
862  template <typename... Ts, typename ConstructorArg,
863  typename... ConstructorArgs,
864  typename = std::enable_if_t<sizeof...(Ts) != 0>>
865  RewritePatternSet &add(ConstructorArg &&arg, ConstructorArgs &&...args) {
866  // The following expands a call to emplace_back for each of the pattern
867  // types 'Ts'.
868  (addImpl<Ts>(/*debugLabels=*/std::nullopt,
869  std::forward<ConstructorArg>(arg),
870  std::forward<ConstructorArgs>(args)...),
871  ...);
872  return *this;
873  }
874  /// An overload of the above `add` method that allows for attaching a set
875  /// of debug labels to the attached patterns. This is useful for labeling
876  /// groups of patterns that may be shared between multiple different
877  /// passes/users.
878  template <typename... Ts, typename ConstructorArg,
879  typename... ConstructorArgs,
880  typename = std::enable_if_t<sizeof...(Ts) != 0>>
882  ConstructorArg &&arg,
883  ConstructorArgs &&...args) {
884  // The following expands a call to emplace_back for each of the pattern
885  // types 'Ts'.
886  (addImpl<Ts>(debugLabels, arg, args...), ...);
887  return *this;
888  }
889 
890  /// Add an instance of each of the pattern types 'Ts'. Return a reference to
891  /// `this` for chaining insertions.
892  template <typename... Ts>
894  (addImpl<Ts>(), ...);
895  return *this;
896  }
897 
898  /// Add the given native pattern to the pattern list. Return a reference to
899  /// `this` for chaining insertions.
900  RewritePatternSet &add(std::unique_ptr<RewritePattern> pattern) {
901  nativePatterns.emplace_back(std::move(pattern));
902  return *this;
903  }
904 
905  /// Add the given PDL pattern to the pattern list. Return a reference to
906  /// `this` for chaining insertions.
907  RewritePatternSet &add(PDLPatternModule &&pattern) {
908  pdlPatterns.mergeIn(std::move(pattern));
909  return *this;
910  }
911 
912  // Add a matchAndRewrite style pattern represented as a C function pointer.
913  template <typename OpType>
915  add(LogicalResult (*implFn)(OpType, PatternRewriter &rewriter),
916  PatternBenefit benefit = 1, ArrayRef<StringRef> generatedNames = {}) {
917  struct FnPattern final : public OpRewritePattern<OpType> {
918  FnPattern(LogicalResult (*implFn)(OpType, PatternRewriter &rewriter),
919  MLIRContext *context, PatternBenefit benefit,
920  ArrayRef<StringRef> generatedNames)
921  : OpRewritePattern<OpType>(context, benefit, generatedNames),
922  implFn(implFn) {}
923 
924  LogicalResult matchAndRewrite(OpType op,
925  PatternRewriter &rewriter) const override {
926  return implFn(op, rewriter);
927  }
928 
929  private:
930  LogicalResult (*implFn)(OpType, PatternRewriter &rewriter);
931  };
932  add(std::make_unique<FnPattern>(std::move(implFn), getContext(), benefit,
933  generatedNames));
934  return *this;
935  }
936 
937  //===--------------------------------------------------------------------===//
938  // Pattern Insertion
939  //===--------------------------------------------------------------------===//
940 
941  // TODO: These are soft deprecated in favor of the 'add' methods above.
942 
943  /// Add an instance of each of the pattern types 'Ts' to the pattern list with
944  /// the given arguments. Return a reference to `this` for chaining insertions.
945  /// Note: ConstructorArg is necessary here to separate the two variadic lists.
946  template <typename... Ts, typename ConstructorArg,
947  typename... ConstructorArgs,
948  typename = std::enable_if_t<sizeof...(Ts) != 0>>
949  RewritePatternSet &insert(ConstructorArg &&arg, ConstructorArgs &&...args) {
950  // The following expands a call to emplace_back for each of the pattern
951  // types 'Ts'.
952  (addImpl<Ts>(/*debugLabels=*/std::nullopt, arg, args...), ...);
953  return *this;
954  }
955 
956  /// Add an instance of each of the pattern types 'Ts'. Return a reference to
957  /// `this` for chaining insertions.
958  template <typename... Ts>
960  (addImpl<Ts>(), ...);
961  return *this;
962  }
963 
964  /// Add the given native pattern to the pattern list. Return a reference to
965  /// `this` for chaining insertions.
966  RewritePatternSet &insert(std::unique_ptr<RewritePattern> pattern) {
967  nativePatterns.emplace_back(std::move(pattern));
968  return *this;
969  }
970 
971  /// Add the given PDL pattern to the pattern list. Return a reference to
972  /// `this` for chaining insertions.
973  RewritePatternSet &insert(PDLPatternModule &&pattern) {
974  pdlPatterns.mergeIn(std::move(pattern));
975  return *this;
976  }
977 
978  // Add a matchAndRewrite style pattern represented as a C function pointer.
979  template <typename OpType>
981  insert(LogicalResult (*implFn)(OpType, PatternRewriter &rewriter)) {
982  struct FnPattern final : public OpRewritePattern<OpType> {
983  FnPattern(LogicalResult (*implFn)(OpType, PatternRewriter &rewriter),
984  MLIRContext *context)
985  : OpRewritePattern<OpType>(context), implFn(implFn) {
986  this->setDebugName(llvm::getTypeName<FnPattern>());
987  }
988 
989  LogicalResult matchAndRewrite(OpType op,
990  PatternRewriter &rewriter) const override {
991  return implFn(op, rewriter);
992  }
993 
994  private:
995  LogicalResult (*implFn)(OpType, PatternRewriter &rewriter);
996  };
997  add(std::make_unique<FnPattern>(std::move(implFn), getContext()));
998  return *this;
999  }
1000 
1001 private:
1002  /// Add an instance of the pattern type 'T'. Return a reference to `this` for
1003  /// chaining insertions.
1004  template <typename T, typename... Args>
1005  std::enable_if_t<std::is_base_of<RewritePattern, T>::value>
1006  addImpl(ArrayRef<StringRef> debugLabels, Args &&...args) {
1007  std::unique_ptr<T> pattern =
1008  RewritePattern::create<T>(std::forward<Args>(args)...);
1009  pattern->addDebugLabels(debugLabels);
1010  nativePatterns.emplace_back(std::move(pattern));
1011  }
1012 
1013  template <typename T, typename... Args>
1014  std::enable_if_t<std::is_base_of<PDLPatternModule, T>::value>
1015  addImpl(ArrayRef<StringRef> debugLabels, Args &&...args) {
1016  // TODO: Add the provided labels to the PDL pattern when PDL supports
1017  // labels.
1018  pdlPatterns.mergeIn(T(std::forward<Args>(args)...));
1019  }
1020 
1021  MLIRContext *const context;
1022  NativePatternListT nativePatterns;
1023 
1024  // Patterns expressed with PDL. This will compile to a stub class when PDL is
1025  // not enabled.
1026  PDLPatternModule pdlPatterns;
1027 };
1028 
1029 } // namespace mlir
1030 
1031 #endif // MLIR_IR_PATTERNMATCH_H
static std::string diag(const llvm::Value &value)
A block operand represents an operand that holds a reference to a Block, e.g.
Definition: BlockSupport.h:30
Block represents an ordered list of Operations.
Definition: Block.h:33
OpListType::iterator iterator
Definition: Block.h:140
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition: Block.cpp:33
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
Definition: Diagnostics.h:155
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition: UseDefLists.h:253
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
Definition: PatternMatch.h:784
IRRewriter(MLIRContext *ctx, OpBuilder::Listener *listener=nullptr)
Definition: PatternMatch.h:786
IRRewriter(const OpBuilder &builder)
Definition: PatternMatch.h:788
IRRewriter(Operation *op, OpBuilder::Listener *listener=nullptr)
Definition: PatternMatch.h:789
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:66
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
This class represents a saved insertion point.
Definition: Builders.h:325
This class helps build Operations.
Definition: Builders.h:205
Listener * listener
The optional listener for events of this builder.
Definition: Builders.h:605
This class represents an operand of an operation.
Definition: Value.h:267
OpTraitRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting again...
Definition: PatternMatch.h:396
OpTraitRewritePattern(MLIRContext *context, PatternBenefit benefit=1)
Definition: PatternMatch.h:398
static OperationName getFromOpaquePointer(const void *pointer)
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:415
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
Definition: PatternMatch.h:34
PatternBenefit & operator=(const PatternBenefit &)=default
bool operator<(const PatternBenefit &rhs) const
Definition: PatternMatch.h:54
bool operator==(const PatternBenefit &rhs) const
Definition: PatternMatch.h:50
static PatternBenefit impossibleToMatch()
Definition: PatternMatch.h:43
bool operator>=(const PatternBenefit &rhs) const
Definition: PatternMatch.h:59
bool operator<=(const PatternBenefit &rhs) const
Definition: PatternMatch.h:58
PatternBenefit(const PatternBenefit &)=default
bool isImpossibleToMatch() const
Definition: PatternMatch.h:44
bool operator!=(const PatternBenefit &rhs) const
Definition: PatternMatch.h:53
PatternBenefit()=default
bool operator>(const PatternBenefit &rhs) const
Definition: PatternMatch.h:57
unsigned short getBenefit() const
If the corresponding pattern can match, return its benefit. If the.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:803
PatternRewriter(MLIRContext *ctx)
Definition: PatternMatch.h:805
virtual bool canRecoverFromRewriteFailure() const
A hook used to indicate if the pattern rewriter can recover from failure during the rewrite stage of ...
Definition: PatternMatch.h:812
This class contains all of the data related to a pattern, but does not contain any methods or logic f...
Definition: PatternMatch.h:73
std::optional< TypeID > getRootInterfaceID() const
Return the interface ID used to match the root operation of this pattern.
Definition: PatternMatch.h:103
Pattern(StringRef rootName, PatternBenefit benefit, MLIRContext *context, ArrayRef< StringRef > generatedNames={})
Construct a pattern with a certain benefit that matches the operation with the given root name.
bool hasBoundedRewriteRecursion() const
Returns true if this pattern is known to result in recursive application, i.e.
Definition: PatternMatch.h:129
std::optional< OperationName > getRootKind() const
Return the root node that this pattern matches.
Definition: PatternMatch.h:94
MLIRContext * getContext() const
Return the MLIRContext used to create this pattern.
Definition: PatternMatch.h:134
ArrayRef< StringRef > getDebugLabels() const
Return the set of debug labels attached to this pattern.
Definition: PatternMatch.h:147
void setHasBoundedRewriteRecursion(bool hasBoundedRecursionArg=true)
Set the flag detailing if this pattern has bounded rewrite recursion or not.
Definition: PatternMatch.h:202
ArrayRef< OperationName > getGeneratedOps() const
Return a list of operations that may be generated when rewriting an operation instance with this patt...
Definition: PatternMatch.h:90
PatternBenefit getBenefit() const
Return the benefit (the inverse of "cost") of matching this pattern.
Definition: PatternMatch.h:123
std::optional< TypeID > getRootTraitID() const
Return the trait ID used to match the root operation of this pattern.
Definition: PatternMatch.h:112
void setDebugName(StringRef name)
Set the human readable debug name used for this pattern.
Definition: PatternMatch.h:144
void addDebugLabels(StringRef label)
Definition: PatternMatch.h:153
void addDebugLabels(ArrayRef< StringRef > labels)
Add the provided debug labels to this pattern.
Definition: PatternMatch.h:150
StringRef getDebugName() const
Return a readable name for this pattern.
Definition: PatternMatch.h:140
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
BlockListType::iterator iterator
Definition: Region.h:52
RewritePatternSet & add(PDLPatternModule &&pattern)
Add the given PDL pattern to the pattern list.
Definition: PatternMatch.h:907
RewritePatternSet & add(LogicalResult(*implFn)(OpType, PatternRewriter &rewriter), PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Definition: PatternMatch.h:915
NativePatternListT & getNativePatterns()
Return the native patterns held in this list.
Definition: PatternMatch.h:844
RewritePatternSet & add(std::unique_ptr< RewritePattern > pattern)
Add the given native pattern to the pattern list.
Definition: PatternMatch.h:900
RewritePatternSet(PDLPatternModule &&pattern)
Definition: PatternMatch.h:838
RewritePatternSet & insert(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
Definition: PatternMatch.h:949
MLIRContext * getContext() const
Definition: PatternMatch.h:841
void clear()
Clear out all of the held patterns in this list.
Definition: PatternMatch.h:850
RewritePatternSet(MLIRContext *context)
Definition: PatternMatch.h:830
RewritePatternSet & add()
Add an instance of each of the pattern types 'Ts'.
Definition: PatternMatch.h:893
RewritePatternSet(MLIRContext *context, std::unique_ptr< RewritePattern > pattern)
Construct a RewritePatternSet populated with the given pattern.
Definition: PatternMatch.h:833
RewritePatternSet & insert(PDLPatternModule &&pattern)
Add the given PDL pattern to the pattern list.
Definition: PatternMatch.h:973
RewritePatternSet & insert(std::unique_ptr< RewritePattern > pattern)
Add the given native pattern to the pattern list.
Definition: PatternMatch.h:966
PDLPatternModule & getPDLPatterns()
Return the PDL patterns held in this list.
Definition: PatternMatch.h:847
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
Definition: PatternMatch.h:865
RewritePatternSet & insert()
Add an instance of each of the pattern types 'Ts'.
Definition: PatternMatch.h:959
RewritePatternSet & addWithLabel(ArrayRef< StringRef > debugLabels, ConstructorArg &&arg, ConstructorArgs &&...args)
An overload of the above add method that allows for attaching a set of debug labels to the attached p...
Definition: PatternMatch.h:881
RewritePatternSet & insert(LogicalResult(*implFn)(OpType, PatternRewriter &rewriter))
Definition: PatternMatch.h:981
RewritePattern is the common base class for all DAG to DAG replacements.
Definition: PatternMatch.h:271
static std::unique_ptr< T > create(Args &&...args)
This method provides a convenient interface for creating and initializing derived rewrite patterns of...
Definition: PatternMatch.h:293
virtual ~RewritePattern()=default
virtual LogicalResult matchAndRewrite(Operation *op, PatternRewriter &rewriter) const =0
Attempt to match against code rooted at the specified operation, which is the same operation code as ...
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:412
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
Definition: PatternMatch.h:736
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Operation *op, CallbackT &&reasonCallback)
Definition: PatternMatch.h:744
void replaceOpUsesWithIf(Operation *from, ValueRange to, function_ref< bool(OpOperand &)> functor, bool *allUsesReplaced=nullptr)
Definition: PatternMatch.h:697
virtual void eraseBlock(Block *block)
This method erases all operations in a block.
LogicalResult notifyMatchFailure(ArgT &&arg, const Twine &msg)
Definition: PatternMatch.h:751
Block * splitBlock(Block *block, Block::iterator before)
Split the operations starting at "before" (inclusive) out of the given block into a new block,...
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
RewriterBase(const OpBuilder &otherBuilder)
Definition: PatternMatch.h:765
void replaceAllUsesWith(ValueRange from, ValueRange to)
Definition: PatternMatch.h:668
void moveBlockBefore(Block *block, Block *anotherBlock)
Unlink this block and insert it right before existingBlock.
void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
Definition: PatternMatch.h:656
void mergeBlocks(Block *source, Block *dest, ValueRange argValues=std::nullopt)
Inline the operations of block 'source' into the end of block 'dest'.
virtual void finalizeOpModification(Operation *op)
This method is used to signal the end of an in-place modification of the given operation.
RewriterBase(Operation *op, OpBuilder::Listener *listener=nullptr)
Definition: PatternMatch.h:767
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
virtual void cancelOpModification(Operation *op)
This method cancels a pending in-place modification.
Definition: PatternMatch.h:642
void replaceAllUsesWith(Block *from, Block *to)
Definition: PatternMatch.h:662
void replaceUsesWithIf(Value from, Value to, function_ref< bool(OpOperand &)> functor, bool *allUsesReplaced=nullptr)
Find uses of from and replace them with to if the functor returns true.
void replaceAllUsesExcept(Value from, Value to, Operation *exceptedUser)
Find uses of from and replace them with to except if the user is exceptedUser.
Definition: PatternMatch.h:720
RewriterBase(MLIRContext *ctx, OpBuilder::Listener *listener=nullptr)
Initialize the builder.
Definition: PatternMatch.h:762
void moveOpBefore(Operation *op, Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
LogicalResult notifyMatchFailure(ArgT &&arg, const char *msg)
Definition: PatternMatch.h:756
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
Definition: PatternMatch.h:648
void moveOpAfter(Operation *op, Operation *existingOp)
Unlink this operation from its current block and insert it right after existingOp which may be in the...
void inlineRegionBefore(Region &region, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
void replaceOpUsesWithinBlock(Operation *op, ValueRange newValues, Block *block, bool *allUsesReplaced=nullptr)
Find uses of from within block and replace them with to.
Definition: PatternMatch.h:707
virtual void inlineBlockBefore(Block *source, Block *dest, Block::iterator before, ValueRange argValues=std::nullopt)
Inline the operations of block 'source' into block 'dest' before the given position.
void replaceAllOpUsesWith(Operation *from, ValueRange to)
Find uses of from and replace them with to.
virtual void startOpModification(Operation *op)
This method is used to notify the rewriter that an in-place operation modification is about to happen...
Definition: PatternMatch.h:632
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Definition: PatternMatch.h:554
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:107
static TypeID getFromOpaquePointer(const void *pointer)
Definition: TypeID.h:135
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
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition: Value.h:212
Operation * getOwner() const
Return the owner of this operand.
Definition: UseDefLists.h:38
Helper class that derives from a RewritePattern class and provides separate match and rewrite entry p...
Definition: PatternMatch.h:244
Include the generated interface declarations.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
Base class for listeners.
Definition: Builders.h:262
Kind
The kind of listener.
Definition: Builders.h:264
This class represents a listener that may be used to hook into various actions within an OpBuilder.
Definition: Builders.h:283
virtual void notifyBlockInserted(Block *block, Region *previous, Region::iterator previousIt)
Notify the listener that the specified block was inserted.
Definition: Builders.h:306
virtual void notifyOperationInserted(Operation *op, InsertPoint previous)
Notify the listener that the specified operation was inserted.
Definition: Builders.h:296
OpInterfaceRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting a...
Definition: PatternMatch.h:379
OpInterfaceRewritePattern(MLIRContext *context, PatternBenefit benefit=1)
Definition: PatternMatch.h:386
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
Definition: PatternMatch.h:358
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
Definition: PatternMatch.h:368
This class acts as a special tag that makes the desire to match "any" operation type explicit.
Definition: PatternMatch.h:159
This class acts as a special tag that makes the desire to match any operation that implements a given...
Definition: PatternMatch.h:164
This class acts as a special tag that makes the desire to match any operation that implements a given...
Definition: PatternMatch.h:169
A listener that forwards all notifications to another listener.
Definition: PatternMatch.h:475
void notifyMatchFailure(Location loc, function_ref< void(Diagnostic &)> reasonCallback) override
Notify the listener that the pattern failed to match, and provide a callback to populate a diagnostic...
Definition: PatternMatch.h:520
void notifyOperationInserted(Operation *op, InsertPoint previous) override
Notify the listener that the specified operation was inserted.
Definition: PatternMatch.h:481
void notifyPatternEnd(const Pattern &pattern, LogicalResult status) override
Notify the listener that a pattern application finished with the specified status.
Definition: PatternMatch.h:515
void notifyOperationModified(Operation *op) override
Notify the listener that the specified operation was modified in-place.
Definition: PatternMatch.h:494
void notifyPatternBegin(const Pattern &pattern, Operation *op) override
Notify the listener that the specified pattern is about to be applied at the specified root operation...
Definition: PatternMatch.h:511
void notifyOperationReplaced(Operation *op, Operation *newOp) override
Notify the listener that all uses of the specified operation's results are about to be replaced with ...
Definition: PatternMatch.h:498
void notifyOperationErased(Operation *op) override
Notify the listener that the specified operation is about to be erased.
Definition: PatternMatch.h:507
void notifyBlockErased(Block *block) override
Notify the listener that the specified block is about to be erased.
Definition: PatternMatch.h:490
ForwardingListener(OpBuilder::Listener *listener)
Definition: PatternMatch.h:476
void notifyOperationReplaced(Operation *op, ValueRange replacement) override
Notify the listener that all uses of the specified operation's results are about to be replaced with ...
Definition: PatternMatch.h:502
void notifyBlockInserted(Block *block, Region *previous, Region::iterator previousIt) override
Notify the listener that the specified block was inserted.
Definition: PatternMatch.h:485
virtual void notifyMatchFailure(Location loc, function_ref< void(Diagnostic &)> reasonCallback)
Notify the listener that the pattern failed to match, and provide a callback to populate a diagnostic...
Definition: PatternMatch.h:466
virtual void notifyOperationModified(Operation *op)
Notify the listener that the specified operation was modified in-place.
Definition: PatternMatch.h:423
virtual void notifyOperationErased(Operation *op)
Notify the listener that the specified operation is about to be erased.
Definition: PatternMatch.h:447
virtual void notifyOperationReplaced(Operation *op, Operation *replacement)
Notify the listener that all uses of the specified operation's results are about to be replaced with ...
Definition: PatternMatch.h:431
virtual void notifyBlockErased(Block *block)
Notify the listener that the specified block is about to be erased.
Definition: PatternMatch.h:420
virtual void notifyPatternEnd(const Pattern &pattern, LogicalResult status)
Notify the listener that a pattern application finished with the specified status.
Definition: PatternMatch.h:458
virtual void notifyPatternBegin(const Pattern &pattern, Operation *op)
Notify the listener that the specified pattern is about to be applied at the specified root operation...
Definition: PatternMatch.h:451
virtual void notifyOperationReplaced(Operation *op, ValueRange replacement)
Notify the listener that all uses of the specified operation's results are about to be replaced with ...
Definition: PatternMatch.h:440
static bool classof(const OpBuilder::Listener *base)
OpOrInterfaceRewritePatternBase is a wrapper around RewritePattern that allows for matching and rewri...
Definition: PatternMatch.h:336
LogicalResult matchAndRewrite(Operation *op, PatternRewriter &rewriter) const final
Wrapper around the RewritePattern method that passes the derived op type.
Definition: PatternMatch.h:341
virtual LogicalResult matchAndRewrite(SourceOp op, PatternRewriter &rewriter) const =0
Method that operates on the SourceOp type.