MLIR  15.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 
17 namespace mlir {
18 
19 class PatternRewriter;
20 
21 //===----------------------------------------------------------------------===//
22 // PatternBenefit class
23 //===----------------------------------------------------------------------===//
24 
25 /// This class represents the benefit of a pattern match in a unitless scheme
26 /// that ranges from 0 (very little benefit) to 65K. The most common unit to
27 /// use here is the "number of operations matched" by the pattern.
28 ///
29 /// This also has a sentinel representation that can be used for patterns that
30 /// fail to match.
31 ///
33  enum { ImpossibleToMatchSentinel = 65535 };
34 
35 public:
36  PatternBenefit() = default;
37  PatternBenefit(unsigned benefit);
38  PatternBenefit(const PatternBenefit &) = default;
39  PatternBenefit &operator=(const PatternBenefit &) = default;
40 
42  bool isImpossibleToMatch() const { return *this == impossibleToMatch(); }
43 
44  /// If the corresponding pattern can match, return its benefit. If the
45  // corresponding pattern isImpossibleToMatch() then this aborts.
46  unsigned short getBenefit() const;
47 
48  bool operator==(const PatternBenefit &rhs) const {
49  return representation == rhs.representation;
50  }
51  bool operator!=(const PatternBenefit &rhs) const { return !(*this == rhs); }
52  bool operator<(const PatternBenefit &rhs) const {
53  return representation < rhs.representation;
54  }
55  bool operator>(const PatternBenefit &rhs) const { return rhs < *this; }
56  bool operator<=(const PatternBenefit &rhs) const { return !(*this > rhs); }
57  bool operator>=(const PatternBenefit &rhs) const { return !(*this < rhs); }
58 
59 private:
60  unsigned short representation{ImpossibleToMatchSentinel};
61 };
62 
63 //===----------------------------------------------------------------------===//
64 // Pattern
65 //===----------------------------------------------------------------------===//
66 
67 /// This class contains all of the data related to a pattern, but does not
68 /// contain any methods or logic for the actual matching. This class is solely
69 /// used to interface with the metadata of a pattern, such as the benefit or
70 /// root operation.
71 class Pattern {
72  /// This enum represents the kind of value used to select the root operations
73  /// that match this pattern.
74  enum class RootKind {
75  /// The pattern root matches "any" operation.
76  Any,
77  /// The pattern root is matched using a concrete operation name.
79  /// The pattern root is matched using an interface ID.
80  InterfaceID,
81  /// The patter root is matched using a trait ID.
82  TraitID
83  };
84 
85 public:
86  /// Return a list of operations that may be generated when rewriting an
87  /// operation instance with this pattern.
88  ArrayRef<OperationName> getGeneratedOps() const { return generatedOps; }
89 
90  /// Return the root node that this pattern matches. Patterns that can match
91  /// multiple root types return None.
93  if (rootKind == RootKind::OperationName)
94  return OperationName::getFromOpaquePointer(rootValue);
95  return llvm::None;
96  }
97 
98  /// Return the interface ID used to match the root operation of this pattern.
99  /// If the pattern does not use an interface ID for deciding the root match,
100  /// this returns None.
102  if (rootKind == RootKind::InterfaceID)
103  return TypeID::getFromOpaquePointer(rootValue);
104  return llvm::None;
105  }
106 
107  /// Return the trait ID used to match the root operation of this pattern.
108  /// If the pattern does not use a trait ID for deciding the root match, this
109  /// returns None.
111  if (rootKind == RootKind::TraitID)
112  return TypeID::getFromOpaquePointer(rootValue);
113  return llvm::None;
114  }
115 
116  /// Return the benefit (the inverse of "cost") of matching this pattern. The
117  /// benefit of a Pattern is always static - rewrites that may have dynamic
118  /// benefit can be instantiated multiple times (different Pattern instances)
119  /// for each benefit that they may return, and be guarded by different match
120  /// condition predicates.
121  PatternBenefit getBenefit() const { return benefit; }
122 
123  /// Returns true if this pattern is known to result in recursive application,
124  /// i.e. this pattern may generate IR that also matches this pattern, but is
125  /// known to bound the recursion. This signals to a rewrite driver that it is
126  /// safe to apply this pattern recursively to generated IR.
128  return contextAndHasBoundedRecursion.getInt();
129  }
130 
131  /// Return the MLIRContext used to create this pattern.
133  return contextAndHasBoundedRecursion.getPointer();
134  }
135 
136  /// Return a readable name for this pattern. This name should only be used for
137  /// debugging purposes, and may be empty.
138  StringRef getDebugName() const { return debugName; }
139 
140  /// Set the human readable debug name used for this pattern. This name will
141  /// only be used for debugging purposes.
142  void setDebugName(StringRef name) { debugName = name; }
143 
144  /// Return the set of debug labels attached to this pattern.
145  ArrayRef<StringRef> getDebugLabels() const { return debugLabels; }
146 
147  /// Add the provided debug labels to this pattern.
149  debugLabels.append(labels.begin(), labels.end());
150  }
151  void addDebugLabels(StringRef label) { debugLabels.push_back(label); }
152 
153 protected:
154  /// This class acts as a special tag that makes the desire to match "any"
155  /// operation type explicit. This helps to avoid unnecessary usages of this
156  /// feature, and ensures that the user is making a conscious decision.
157  struct MatchAnyOpTypeTag {};
158  /// This class acts as a special tag that makes the desire to match any
159  /// operation that implements a given interface explicit. This helps to avoid
160  /// unnecessary usages of this feature, and ensures that the user is making a
161  /// conscious decision.
163  /// This class acts as a special tag that makes the desire to match any
164  /// operation that implements a given trait explicit. This helps to avoid
165  /// unnecessary usages of this feature, and ensures that the user is making a
166  /// conscious decision.
168 
169  /// Construct a pattern with a certain benefit that matches the operation
170  /// with the given root name.
171  Pattern(StringRef rootName, PatternBenefit benefit, MLIRContext *context,
172  ArrayRef<StringRef> generatedNames = {});
173  /// Construct a pattern that may match any operation type. `generatedNames`
174  /// contains the names of operations that may be generated during a successful
175  /// rewrite. `MatchAnyOpTypeTag` is just a tag to ensure that the "match any"
176  /// behavior is what the user actually desired, `MatchAnyOpTypeTag()` should
177  /// always be supplied here.
178  Pattern(MatchAnyOpTypeTag tag, PatternBenefit benefit, MLIRContext *context,
179  ArrayRef<StringRef> generatedNames = {});
180  /// Construct a pattern that may match any operation that implements the
181  /// interface defined by the provided `interfaceID`. `generatedNames` contains
182  /// the names of operations that may be generated during a successful rewrite.
183  /// `MatchInterfaceOpTypeTag` is just a tag to ensure that the "match
184  /// interface" behavior is what the user actually desired,
185  /// `MatchInterfaceOpTypeTag()` should always be supplied here.
186  Pattern(MatchInterfaceOpTypeTag tag, TypeID interfaceID,
187  PatternBenefit benefit, MLIRContext *context,
188  ArrayRef<StringRef> generatedNames = {});
189  /// Construct a pattern that may match any operation that implements the
190  /// trait defined by the provided `traitID`. `generatedNames` contains the
191  /// names of operations that may be generated during a successful rewrite.
192  /// `MatchTraitOpTypeTag` is just a tag to ensure that the "match trait"
193  /// behavior is what the user actually desired, `MatchTraitOpTypeTag()` should
194  /// always be supplied here.
195  Pattern(MatchTraitOpTypeTag tag, TypeID traitID, PatternBenefit benefit,
196  MLIRContext *context, ArrayRef<StringRef> generatedNames = {});
197 
198  /// Set the flag detailing if this pattern has bounded rewrite recursion or
199  /// not.
200  void setHasBoundedRewriteRecursion(bool hasBoundedRecursionArg = true) {
201  contextAndHasBoundedRecursion.setInt(hasBoundedRecursionArg);
202  }
203 
204 private:
205  Pattern(const void *rootValue, RootKind rootKind,
206  ArrayRef<StringRef> generatedNames, PatternBenefit benefit,
207  MLIRContext *context);
208 
209  /// The value used to match the root operation of the pattern.
210  const void *rootValue;
211  RootKind rootKind;
212 
213  /// The expected benefit of matching this pattern.
214  const PatternBenefit benefit;
215 
216  /// The context this pattern was created from, and a boolean flag indicating
217  /// whether this pattern has bounded recursion or not.
218  llvm::PointerIntPair<MLIRContext *, 1, bool> contextAndHasBoundedRecursion;
219 
220  /// A list of the potential operations that may be generated when rewriting
221  /// an op with this pattern.
222  SmallVector<OperationName, 2> generatedOps;
223 
224  /// A readable name for this pattern. May be empty.
225  StringRef debugName;
226 
227  /// The set of debug labels attached to this pattern.
228  SmallVector<StringRef, 0> debugLabels;
229 };
230 
231 //===----------------------------------------------------------------------===//
232 // RewritePattern
233 //===----------------------------------------------------------------------===//
234 
235 /// RewritePattern is the common base class for all DAG to DAG replacements.
236 /// There are two possible usages of this class:
237 /// * Multi-step RewritePattern with "match" and "rewrite"
238 /// - By overloading the "match" and "rewrite" functions, the user can
239 /// separate the concerns of matching and rewriting.
240 /// * Single-step RewritePattern with "matchAndRewrite"
241 /// - By overloading the "matchAndRewrite" function, the user can perform
242 /// the rewrite in the same call as the match.
243 ///
244 class RewritePattern : public Pattern {
245 public:
246  virtual ~RewritePattern() = default;
247 
248  /// Rewrite the IR rooted at the specified operation with the result of
249  /// this pattern, generating any new operations with the specified
250  /// builder. If an unexpected error is encountered (an internal
251  /// compiler error), it is emitted through the normal MLIR diagnostic
252  /// hooks and the IR is left in a valid state.
253  virtual void rewrite(Operation *op, PatternRewriter &rewriter) const;
254 
255  /// Attempt to match against code rooted at the specified operation,
256  /// which is the same operation code as getRootKind().
257  virtual LogicalResult match(Operation *op) const;
258 
259  /// Attempt to match against code rooted at the specified operation,
260  /// which is the same operation code as getRootKind(). If successful, this
261  /// function will automatically perform the rewrite.
263  PatternRewriter &rewriter) const {
264  if (succeeded(match(op))) {
265  rewrite(op, rewriter);
266  return success();
267  }
268  return failure();
269  }
270 
271  /// This method provides a convenient interface for creating and initializing
272  /// derived rewrite patterns of the given type `T`.
273  template <typename T, typename... Args>
274  static std::unique_ptr<T> create(Args &&... args) {
275  std::unique_ptr<T> pattern =
276  std::make_unique<T>(std::forward<Args>(args)...);
277  initializePattern<T>(*pattern);
278 
279  // Set a default debug name if one wasn't provided.
280  if (pattern->getDebugName().empty())
281  pattern->setDebugName(llvm::getTypeName<T>());
282  return pattern;
283  }
284 
285 protected:
286  /// Inherit the base constructors from `Pattern`.
287  using Pattern::Pattern;
288 
289 private:
290  /// Trait to check if T provides a `getOperationName` method.
291  template <typename T, typename... Args>
292  using has_initialize = decltype(std::declval<T>().initialize());
293  template <typename T>
294  using detect_has_initialize = llvm::is_detected<has_initialize, T>;
295 
296  /// Initialize the derived pattern by calling its `initialize` method.
297  template <typename T>
299  initializePattern(T &pattern) {
300  pattern.initialize();
301  }
302  /// Empty derived pattern initializer for patterns that do not have an
303  /// initialize method.
304  template <typename T>
306  initializePattern(T &) {}
307 
308  /// An anchor for the virtual table.
309  virtual void anchor();
310 };
311 
312 namespace detail {
313 /// OpOrInterfaceRewritePatternBase is a wrapper around RewritePattern that
314 /// allows for matching and rewriting against an instance of a derived operation
315 /// class or Interface.
316 template <typename SourceOp>
318  using RewritePattern::RewritePattern;
319 
320  /// Wrappers around the RewritePattern methods that pass the derived op type.
321  void rewrite(Operation *op, PatternRewriter &rewriter) const final {
322  rewrite(cast<SourceOp>(op), rewriter);
323  }
324  LogicalResult match(Operation *op) const final {
325  return match(cast<SourceOp>(op));
326  }
328  PatternRewriter &rewriter) const final {
329  return matchAndRewrite(cast<SourceOp>(op), rewriter);
330  }
331 
332  /// Rewrite and Match methods that operate on the SourceOp type. These must be
333  /// overridden by the derived pattern class.
334  virtual void rewrite(SourceOp op, PatternRewriter &rewriter) const {
335  llvm_unreachable("must override rewrite or matchAndRewrite");
336  }
337  virtual LogicalResult match(SourceOp op) const {
338  llvm_unreachable("must override match or matchAndRewrite");
339  }
340  virtual LogicalResult matchAndRewrite(SourceOp op,
341  PatternRewriter &rewriter) const {
342  if (succeeded(match(op))) {
343  rewrite(op, rewriter);
344  return success();
345  }
346  return failure();
347  }
348 };
349 } // namespace detail
350 
351 /// OpRewritePattern is a wrapper around RewritePattern that allows for
352 /// matching and rewriting against an instance of a derived operation class as
353 /// opposed to a raw Operation.
354 template <typename SourceOp>
356  : public detail::OpOrInterfaceRewritePatternBase<SourceOp> {
357  /// Patterns must specify the root operation name they match against, and can
358  /// also specify the benefit of the pattern matching and a list of generated
359  /// ops.
361  ArrayRef<StringRef> generatedNames = {})
363  SourceOp::getOperationName(), benefit, context, generatedNames) {}
364 };
365 
366 /// OpInterfaceRewritePattern is a wrapper around RewritePattern that allows for
367 /// matching and rewriting against an instance of an operation interface instead
368 /// of a raw Operation.
369 template <typename SourceOp>
371  : public detail::OpOrInterfaceRewritePatternBase<SourceOp> {
373  : detail::OpOrInterfaceRewritePatternBase<SourceOp>(
374  Pattern::MatchInterfaceOpTypeTag(), SourceOp::getInterfaceID(),
375  benefit, context) {}
376 };
377 
378 /// OpTraitRewritePattern is a wrapper around RewritePattern that allows for
379 /// matching and rewriting against instances of an operation that possess a
380 /// given trait.
381 template <template <typename> class TraitType>
383 public:
385  : RewritePattern(Pattern::MatchTraitOpTypeTag(), TypeID::get<TraitType>(),
386  benefit, context) {}
387 };
388 
389 //===----------------------------------------------------------------------===//
390 // RewriterBase
391 //===----------------------------------------------------------------------===//
392 
393 /// This class coordinates the application of a rewrite on a set of IR,
394 /// providing a way for clients to track mutations and create new operations.
395 /// This class serves as a common API for IR mutation between pattern rewrites
396 /// and non-pattern rewrites, and facilitates the development of shared
397 /// IR transformation utilities.
399 public:
400  /// Move the blocks that belong to "region" before the given position in
401  /// another region "parent". The two regions must be different. The caller
402  /// is responsible for creating or updating the operation transferring flow
403  /// of control to the region and passing it the correct block arguments.
404  virtual void inlineRegionBefore(Region &region, Region &parent,
405  Region::iterator before);
406  void inlineRegionBefore(Region &region, Block *before);
407 
408  /// Clone the blocks that belong to "region" before the given position in
409  /// another region "parent". The two regions must be different. The caller is
410  /// responsible for creating or updating the operation transferring flow of
411  /// control to the region and passing it the correct block arguments.
412  virtual void cloneRegionBefore(Region &region, Region &parent,
413  Region::iterator before,
414  BlockAndValueMapping &mapping);
415  void cloneRegionBefore(Region &region, Region &parent,
416  Region::iterator before);
417  void cloneRegionBefore(Region &region, Block *before);
418 
419  /// This method replaces the uses of the results of `op` with the values in
420  /// `newValues` when the provided `functor` returns true for a specific use.
421  /// The number of values in `newValues` is required to match the number of
422  /// results of `op`. `allUsesReplaced`, if non-null, is set to true if all of
423  /// the uses of `op` were replaced. Note that in some rewriters, the given
424  /// 'functor' may be stored beyond the lifetime of the rewrite being applied.
425  /// As such, the function should not capture by reference and instead use
426  /// value capture as necessary.
427  virtual void
428  replaceOpWithIf(Operation *op, ValueRange newValues, bool *allUsesReplaced,
429  llvm::unique_function<bool(OpOperand &) const> functor);
430  void replaceOpWithIf(Operation *op, ValueRange newValues,
431  llvm::unique_function<bool(OpOperand &) const> functor) {
432  replaceOpWithIf(op, newValues, /*allUsesReplaced=*/nullptr,
433  std::move(functor));
434  }
435 
436  /// This method replaces the uses of the results of `op` with the values in
437  /// `newValues` when a use is nested within the given `block`. The number of
438  /// values in `newValues` is required to match the number of results of `op`.
439  /// If all uses of this operation are replaced, the operation is erased.
440  void replaceOpWithinBlock(Operation *op, ValueRange newValues, Block *block,
441  bool *allUsesReplaced = nullptr);
442 
443  /// This method replaces the results of the operation with the specified list
444  /// of values. The number of provided values must match the number of results
445  /// of the operation.
446  virtual void replaceOp(Operation *op, ValueRange newValues);
447 
448  /// Replaces the result op with a new op that is created without verification.
449  /// The result values of the two ops must be the same types.
450  template <typename OpTy, typename... Args>
451  OpTy replaceOpWithNewOp(Operation *op, Args &&...args) {
452  auto newOp = create<OpTy>(op->getLoc(), std::forward<Args>(args)...);
453  replaceOpWithResultsOfAnotherOp(op, newOp.getOperation());
454  return newOp;
455  }
456 
457  /// This method erases an operation that is known to have no uses.
458  virtual void eraseOp(Operation *op);
459 
460  /// This method erases all operations in a block.
461  virtual void eraseBlock(Block *block);
462 
463  /// Merge the operations of block 'source' into the end of block 'dest'.
464  /// 'source's predecessors must either be empty or only contain 'dest`.
465  /// 'argValues' is used to replace the block arguments of 'source' after
466  /// merging.
467  virtual void mergeBlocks(Block *source, Block *dest,
468  ValueRange argValues = llvm::None);
469 
470  // Merge the operations of block 'source' before the operation 'op'. Source
471  // block should not have existing predecessors or successors.
472  void mergeBlockBefore(Block *source, Operation *op,
473  ValueRange argValues = llvm::None);
474 
475  /// Split the operations starting at "before" (inclusive) out of the given
476  /// block into a new block, and return it.
477  virtual Block *splitBlock(Block *block, Block::iterator before);
478 
479  /// This method is used to notify the rewriter that an in-place operation
480  /// modification is about to happen. A call to this function *must* be
481  /// followed by a call to either `finalizeRootUpdate` or `cancelRootUpdate`.
482  /// This is a minor efficiency win (it avoids creating a new operation and
483  /// removing the old one) but also often allows simpler code in the client.
484  virtual void startRootUpdate(Operation *op) {}
485 
486  /// This method is used to signal the end of a root update on the given
487  /// operation. This can only be called on operations that were provided to a
488  /// call to `startRootUpdate`.
489  virtual void finalizeRootUpdate(Operation *op) {}
490 
491  /// This method cancels a pending root update. This can only be called on
492  /// operations that were provided to a call to `startRootUpdate`.
493  virtual void cancelRootUpdate(Operation *op) {}
494 
495  /// This method is a utility wrapper around a root update of an operation. It
496  /// wraps calls to `startRootUpdate` and `finalizeRootUpdate` around the given
497  /// callable.
498  template <typename CallableT>
499  void updateRootInPlace(Operation *root, CallableT &&callable) {
500  startRootUpdate(root);
501  callable();
502  finalizeRootUpdate(root);
503  }
504 
505  /// Used to notify the rewriter that the IR failed to be rewritten because of
506  /// a match failure, and provide a callback to populate a diagnostic with the
507  /// reason why the failure occurred. This method allows for derived rewriters
508  /// to optionally hook into the reason why a rewrite failed, and display it to
509  /// users.
510  template <typename CallbackT>
512  notifyMatchFailure(Location loc, CallbackT &&reasonCallback) {
513 #ifndef NDEBUG
514  return notifyMatchFailure(loc,
515  function_ref<void(Diagnostic &)>(reasonCallback));
516 #else
517  return failure();
518 #endif
519  }
520  template <typename CallbackT>
522  notifyMatchFailure(Operation *op, CallbackT &&reasonCallback) {
523  return notifyMatchFailure(op->getLoc(),
524  function_ref<void(Diagnostic &)>(reasonCallback));
525  }
526  template <typename ArgT>
527  LogicalResult notifyMatchFailure(ArgT &&arg, const Twine &msg) {
528  return notifyMatchFailure(std::forward<ArgT>(arg),
529  [&](Diagnostic &diag) { diag << msg; });
530  }
531  template <typename ArgT>
532  LogicalResult notifyMatchFailure(ArgT &&arg, const char *msg) {
533  return notifyMatchFailure(std::forward<ArgT>(arg), Twine(msg));
534  }
535 
536 protected:
537  /// Initialize the builder with this rewriter as the listener.
538  explicit RewriterBase(MLIRContext *ctx) : OpBuilder(ctx, /*listener=*/this) {}
539  explicit RewriterBase(const OpBuilder &otherBuilder)
540  : OpBuilder(otherBuilder) {
541  setListener(this);
542  }
543  ~RewriterBase() override;
544 
545  /// These are the callback methods that subclasses can choose to implement if
546  /// they would like to be notified about certain types of mutations.
547 
548  /// Notify the rewriter that the specified operation is about to be replaced
549  /// with another set of operations. This is called before the uses of the
550  /// operation have been changed.
551  virtual void notifyRootReplaced(Operation *op) {}
552 
553  /// This is called on an operation that a rewrite is removing, right before
554  /// the operation is deleted. At this point, the operation has zero uses.
555  virtual void notifyOperationRemoved(Operation *op) {}
556 
557  /// Notify the rewriter that the pattern failed to match the given operation,
558  /// and provide a callback to populate a diagnostic with the reason why the
559  /// failure occurred. This method allows for derived rewriters to optionally
560  /// hook into the reason why a rewrite failed, and display it to users.
561  virtual LogicalResult
563  function_ref<void(Diagnostic &)> reasonCallback) {
564  return failure();
565  }
566 
567 private:
568  void operator=(const RewriterBase &) = delete;
569  RewriterBase(const RewriterBase &) = delete;
570 
571  /// 'op' and 'newOp' are known to have the same number of results, replace the
572  /// uses of op with uses of newOp.
573  void replaceOpWithResultsOfAnotherOp(Operation *op, Operation *newOp);
574 };
575 
576 //===----------------------------------------------------------------------===//
577 // IRRewriter
578 //===----------------------------------------------------------------------===//
579 
580 /// This class coordinates rewriting a piece of IR outside of a pattern rewrite,
581 /// providing a way to keep track of the mutations made to the IR. This class
582 /// should only be used in situations where another `RewriterBase` instance,
583 /// such as a `PatternRewriter`, is not available.
584 class IRRewriter : public RewriterBase {
585 public:
586  explicit IRRewriter(MLIRContext *ctx) : RewriterBase(ctx) {}
587  explicit IRRewriter(const OpBuilder &builder) : RewriterBase(builder) {}
588 };
589 
590 //===----------------------------------------------------------------------===//
591 // PatternRewriter
592 //===----------------------------------------------------------------------===//
593 
594 /// A special type of `RewriterBase` that coordinates the application of a
595 /// rewrite pattern on the current IR being matched, providing a way to keep
596 /// track of any mutations made. This class should be used to perform all
597 /// necessary IR mutations within a rewrite pattern, as the pattern driver may
598 /// be tracking various state that would be invalidated when a mutation takes
599 /// place.
601 public:
603 };
604 
605 //===----------------------------------------------------------------------===//
606 // PDLPatternModule
607 //===----------------------------------------------------------------------===//
608 
609 //===----------------------------------------------------------------------===//
610 // PDLValue
611 
612 /// Storage type of byte-code interpreter values. These are passed to constraint
613 /// functions as arguments.
614 class PDLValue {
615 public:
616  /// The underlying kind of a PDL value.
618 
619  /// Construct a new PDL value.
620  PDLValue(const PDLValue &other) = default;
621  PDLValue(std::nullptr_t = nullptr) {}
623  : value(value.getAsOpaquePointer()), kind(Kind::Attribute) {}
624  PDLValue(Operation *value) : value(value), kind(Kind::Operation) {}
625  PDLValue(Type value) : value(value.getAsOpaquePointer()), kind(Kind::Type) {}
626  PDLValue(TypeRange *value) : value(value), kind(Kind::TypeRange) {}
628  : value(value.getAsOpaquePointer()), kind(Kind::Value) {}
629  PDLValue(ValueRange *value) : value(value), kind(Kind::ValueRange) {}
630 
631  /// Returns true if the type of the held value is `T`.
632  template <typename T>
633  bool isa() const {
634  assert(value && "isa<> used on a null value");
635  return kind == getKindOf<T>();
636  }
637 
638  /// Attempt to dynamically cast this value to type `T`, returns null if this
639  /// value is not an instance of `T`.
640  template <typename T,
641  typename ResultT = std::conditional_t<
643  ResultT dyn_cast() const {
644  return isa<T>() ? castImpl<T>() : ResultT();
645  }
646 
647  /// Cast this value to type `T`, asserts if this value is not an instance of
648  /// `T`.
649  template <typename T>
650  T cast() const {
651  assert(isa<T>() && "expected value to be of type `T`");
652  return castImpl<T>();
653  }
654 
655  /// Get an opaque pointer to the value.
656  const void *getAsOpaquePointer() const { return value; }
657 
658  /// Return if this value is null or not.
659  explicit operator bool() const { return value; }
660 
661  /// Return the kind of this value.
662  Kind getKind() const { return kind; }
663 
664  /// Print this value to the provided output stream.
665  void print(raw_ostream &os) const;
666 
667  /// Print the specified value kind to an output stream.
668  static void print(raw_ostream &os, Kind kind);
669 
670 private:
671  /// Find the index of a given type in a range of other types.
672  template <typename...>
673  struct index_of_t;
674  template <typename T, typename... R>
675  struct index_of_t<T, T, R...> : std::integral_constant<size_t, 0> {};
676  template <typename T, typename F, typename... R>
677  struct index_of_t<T, F, R...>
678  : std::integral_constant<size_t, 1 + index_of_t<T, R...>::value> {};
679 
680  /// Return the kind used for the given T.
681  template <typename T>
682  static Kind getKindOf() {
683  return static_cast<Kind>(index_of_t<T, Attribute, Operation *, Type,
684  TypeRange, Value, ValueRange>::value);
685  }
686 
687  /// The internal implementation of `cast`, that returns the underlying value
688  /// as the given type `T`.
689  template <typename T>
691  castImpl() const {
692  return T::getFromOpaquePointer(value);
693  }
694  template <typename T>
696  castImpl() const {
697  return *reinterpret_cast<T *>(const_cast<void *>(value));
698  }
699  template <typename T>
700  std::enable_if_t<std::is_pointer<T>::value, T> castImpl() const {
701  return reinterpret_cast<T>(const_cast<void *>(value));
702  }
703 
704  /// The internal opaque representation of a PDLValue.
705  const void *value{nullptr};
706  /// The kind of the opaque value.
707  Kind kind{Kind::Attribute};
708 };
709 
710 inline raw_ostream &operator<<(raw_ostream &os, PDLValue value) {
711  value.print(os);
712  return os;
713 }
714 
715 inline raw_ostream &operator<<(raw_ostream &os, PDLValue::Kind kind) {
716  PDLValue::print(os, kind);
717  return os;
718 }
719 
720 //===----------------------------------------------------------------------===//
721 // PDLResultList
722 
723 /// The class represents a list of PDL results, returned by a native rewrite
724 /// method. It provides the mechanism with which to pass PDLValues back to the
725 /// PDL bytecode.
727 public:
728  /// Push a new Attribute value onto the result list.
729  void push_back(Attribute value) { results.push_back(value); }
730 
731  /// Push a new Operation onto the result list.
732  void push_back(Operation *value) { results.push_back(value); }
733 
734  /// Push a new Type onto the result list.
735  void push_back(Type value) { results.push_back(value); }
736 
737  /// Push a new TypeRange onto the result list.
739  // The lifetime of a TypeRange can't be guaranteed, so we'll need to
740  // allocate a storage for it.
741  llvm::OwningArrayRef<Type> storage(value.size());
742  llvm::copy(value, storage.begin());
743  allocatedTypeRanges.emplace_back(std::move(storage));
744  typeRanges.push_back(allocatedTypeRanges.back());
745  results.push_back(&typeRanges.back());
746  }
748  typeRanges.push_back(value);
749  results.push_back(&typeRanges.back());
750  }
752  typeRanges.push_back(value);
753  results.push_back(&typeRanges.back());
754  }
755 
756  /// Push a new Value onto the result list.
757  void push_back(Value value) { results.push_back(value); }
758 
759  /// Push a new ValueRange onto the result list.
761  // The lifetime of a ValueRange can't be guaranteed, so we'll need to
762  // allocate a storage for it.
763  llvm::OwningArrayRef<Value> storage(value.size());
764  llvm::copy(value, storage.begin());
765  allocatedValueRanges.emplace_back(std::move(storage));
766  valueRanges.push_back(allocatedValueRanges.back());
767  results.push_back(&valueRanges.back());
768  }
770  valueRanges.push_back(value);
771  results.push_back(&valueRanges.back());
772  }
774  valueRanges.push_back(value);
775  results.push_back(&valueRanges.back());
776  }
777 
778 protected:
779  /// Create a new result list with the expected number of results.
780  PDLResultList(unsigned maxNumResults) {
781  // For now just reserve enough space for all of the results. We could do
782  // separate counts per range type, but it isn't really worth it unless there
783  // are a "large" number of results.
784  typeRanges.reserve(maxNumResults);
785  valueRanges.reserve(maxNumResults);
786  }
787 
788  /// The PDL results held by this list.
790  /// Memory used to store ranges held by the list.
793  /// Memory allocated to store ranges in the result list whose lifetime was
794  /// generated in the native function.
797 };
798 
799 //===----------------------------------------------------------------------===//
800 // PDLPatternModule
801 
802 /// A generic PDL pattern constraint function. This function applies a
803 /// constraint to a given set of opaque PDLValue entities. Returns success if
804 /// the constraint successfully held, failure otherwise.
805 using PDLConstraintFunction =
806  std::function<LogicalResult(PatternRewriter &, ArrayRef<PDLValue>)>;
807 /// A native PDL rewrite function. This function performs a rewrite on the
808 /// given set of values. Any results from this rewrite that should be passed
809 /// back to PDL should be added to the provided result list. This method is only
810 /// invoked when the corresponding match was successful.
811 using PDLRewriteFunction =
812  std::function<void(PatternRewriter &, PDLResultList &, ArrayRef<PDLValue>)>;
813 
814 namespace detail {
815 namespace pdl_function_builder {
816 /// A utility variable that always resolves to false. This is useful for static
817 /// asserts that are always false, but only should fire in certain templated
818 /// constructs. For example, if a templated function should never be called, the
819 /// function could be defined as:
820 ///
821 /// template <typename T>
822 /// void foo() {
823 /// static_assert(always_false<T>, "This function should never be called");
824 /// }
825 ///
826 template <class... T>
827 constexpr bool always_false = false;
828 
829 //===----------------------------------------------------------------------===//
830 // PDL Function Builder: Type Processing
831 //===----------------------------------------------------------------------===//
832 
833 /// This struct provides a convenient way to determine how to process a given
834 /// type as either a PDL parameter, or a result value. This allows for
835 /// supporting complex types in constraint and rewrite functions, without
836 /// requiring the user to hand-write the necessary glue code themselves.
837 /// Specializations of this class should implement the following methods to
838 /// enable support as a PDL argument or result type:
839 ///
840 /// static LogicalResult verifyAsArg(
841 /// function_ref<LogicalResult(const Twine &)> errorFn, PDLValue pdlValue,
842 /// size_t argIdx);
843 ///
844 /// * This method verifies that the given PDLValue is valid for use as a
845 /// value of `T`.
846 ///
847 /// static T processAsArg(PDLValue pdlValue);
848 ///
849 /// * This method processes the given PDLValue as a value of `T`.
850 ///
851 /// static void processAsResult(PatternRewriter &, PDLResultList &results,
852 /// const T &value);
853 ///
854 /// * This method processes the given value of `T` as the result of a
855 /// function invocation. The method should package the value into an
856 /// appropriate form and append it to the given result list.
857 ///
858 /// If the type `T` is based on a higher order value, consider using
859 /// `ProcessPDLValueBasedOn` as a base class of the specialization to simplify
860 /// the implementation.
861 ///
862 template <typename T, typename Enable = void>
864 
865 /// This struct provides a simplified model for processing types that are based
866 /// on another type, e.g. APInt is based on the handling for IntegerAttr. This
867 /// allows for building the necessary processing functions on top of the base
868 /// value instead of a PDLValue. Derived users should implement the following
869 /// (which subsume the ProcessPDLValue variants):
870 ///
871 /// static LogicalResult verifyAsArg(
872 /// function_ref<LogicalResult(const Twine &)> errorFn,
873 /// const BaseT &baseValue, size_t argIdx);
874 ///
875 /// * This method verifies that the given PDLValue is valid for use as a
876 /// value of `T`.
877 ///
878 /// static T processAsArg(BaseT baseValue);
879 ///
880 /// * This method processes the given base value as a value of `T`.
881 ///
882 template <typename T, typename BaseT>
884  static LogicalResult
885  verifyAsArg(function_ref<LogicalResult(const Twine &)> errorFn,
886  PDLValue pdlValue, size_t argIdx) {
887  // Verify the base class before continuing.
888  if (failed(ProcessPDLValue<BaseT>::verifyAsArg(errorFn, pdlValue, argIdx)))
889  return failure();
891  errorFn, ProcessPDLValue<BaseT>::processAsArg(pdlValue), argIdx);
892  }
893  static T processAsArg(PDLValue pdlValue) {
896  }
897 
898  /// Explicitly add the expected parent API to ensure the parent class
899  /// implements the necessary API (and doesn't implicitly inherit it from
900  /// somewhere else).
901  static LogicalResult
903  size_t argIdx) {
904  return success();
905  }
906  static T processAsArg(BaseT baseValue);
907 };
908 
909 /// This struct provides a simplified model for processing types that have
910 /// "builtin" PDLValue support:
911 /// * Attribute, Operation *, Type, TypeRange, ValueRange
912 template <typename T>
914  static LogicalResult
915  verifyAsArg(function_ref<LogicalResult(const Twine &)> errorFn,
916  PDLValue pdlValue, size_t argIdx) {
917  if (pdlValue)
918  return success();
919  return errorFn("expected a non-null value for argument " + Twine(argIdx) +
920  " of type: " + llvm::getTypeName<T>());
921  }
922 
923  static T processAsArg(PDLValue pdlValue) { return pdlValue.cast<T>(); }
925  T value) {
926  results.push_back(value);
927  }
928 };
929 
930 /// This struct provides a simplified model for processing types that inherit
931 /// from builtin PDLValue types. For example, derived attributes like
932 /// IntegerAttr, derived types like IntegerType, derived operations like
933 /// ModuleOp, Interfaces, etc.
934 template <typename T, typename BaseT>
936  static LogicalResult
937  verifyAsArg(function_ref<LogicalResult(const Twine &)> errorFn,
938  BaseT baseValue, size_t argIdx) {
939  return TypeSwitch<BaseT, LogicalResult>(baseValue)
940  .Case([&](T) { return success(); })
941  .Default([&](BaseT) {
942  return errorFn("expected argument " + Twine(argIdx) +
943  " to be of type: " + llvm::getTypeName<T>());
944  });
945  }
947 
948  static T processAsArg(BaseT baseValue) {
949  return baseValue.template cast<T>();
950  }
952 
954  T value) {
955  results.push_back(value);
956  }
957 };
958 
959 //===----------------------------------------------------------------------===//
960 // Attribute
961 
962 template <>
963 struct ProcessPDLValue<Attribute> : public ProcessBuiltinPDLValue<Attribute> {};
964 template <typename T>
966  std::enable_if_t<std::is_base_of<Attribute, T>::value>>
967  : public ProcessDerivedPDLValue<T, Attribute> {};
968 
969 /// Handling for various Attribute value types.
970 template <>
971 struct ProcessPDLValue<StringRef>
972  : public ProcessPDLValueBasedOn<StringRef, StringAttr> {
973  static StringRef processAsArg(StringAttr value) { return value.getValue(); }
975 
976  static void processAsResult(PatternRewriter &rewriter, PDLResultList &results,
977  StringRef value) {
978  results.push_back(rewriter.getStringAttr(value));
979  }
980 };
981 template <>
982 struct ProcessPDLValue<std::string>
983  : public ProcessPDLValueBasedOn<std::string, StringAttr> {
984  template <typename T>
985  static std::string processAsArg(T value) {
986  static_assert(always_false<T>,
987  "`std::string` arguments require a string copy, use "
988  "`StringRef` for string-like arguments instead");
989  return {};
990  }
991  static void processAsResult(PatternRewriter &rewriter, PDLResultList &results,
992  StringRef value) {
993  results.push_back(rewriter.getStringAttr(value));
994  }
995 };
996 
997 //===----------------------------------------------------------------------===//
998 // Operation
999 
1000 template <>
1003 template <typename T>
1004 struct ProcessPDLValue<T, std::enable_if_t<std::is_base_of<OpState, T>::value>>
1005  : public ProcessDerivedPDLValue<T, Operation *> {
1006  static T processAsArg(Operation *value) { return cast<T>(value); }
1007 };
1008 
1009 //===----------------------------------------------------------------------===//
1010 // Type
1011 
1012 template <>
1013 struct ProcessPDLValue<Type> : public ProcessBuiltinPDLValue<Type> {};
1014 template <typename T>
1015 struct ProcessPDLValue<T, std::enable_if_t<std::is_base_of<Type, T>::value>>
1016  : public ProcessDerivedPDLValue<T, Type> {};
1017 
1018 //===----------------------------------------------------------------------===//
1019 // TypeRange
1020 
1021 template <>
1022 struct ProcessPDLValue<TypeRange> : public ProcessBuiltinPDLValue<TypeRange> {};
1023 template <>
1027  results.push_back(types);
1028  }
1029 };
1030 template <>
1034  results.push_back(types);
1035  }
1036 };
1037 
1038 //===----------------------------------------------------------------------===//
1039 // Value
1040 
1041 template <>
1042 struct ProcessPDLValue<Value> : public ProcessBuiltinPDLValue<Value> {};
1043 
1044 //===----------------------------------------------------------------------===//
1045 // ValueRange
1046 
1047 template <>
1048 struct ProcessPDLValue<ValueRange> : public ProcessBuiltinPDLValue<ValueRange> {
1049 };
1050 template <>
1053  OperandRange values) {
1054  results.push_back(values);
1055  }
1056 };
1057 template <>
1060  ResultRange values) {
1061  results.push_back(values);
1062  }
1063 };
1064 
1065 //===----------------------------------------------------------------------===//
1066 // PDL Function Builder: Argument Handling
1067 //===----------------------------------------------------------------------===//
1068 
1069 /// Validate the given PDLValues match the constraints defined by the argument
1070 /// types of the given function. In the case of failure, a match failure
1071 /// diagnostic is emitted.
1072 /// FIXME: This should be completely removed in favor of `assertArgs`, but PDL
1073 /// does not currently preserve Constraint application ordering.
1074 template <typename PDLFnT, std::size_t... I>
1076  std::index_sequence<I...>) {
1077  using FnTraitsT = llvm::function_traits<PDLFnT>;
1078 
1079  auto errorFn = [&](const Twine &msg) {
1080  return rewriter.notifyMatchFailure(rewriter.getUnknownLoc(), msg);
1081  };
1082  LogicalResult result = success();
1083  (void)std::initializer_list<int>{
1084  (result =
1085  succeeded(result)
1087  verifyAsArg(errorFn, values[I], I)
1088  : failure(),
1089  0)...};
1090  return result;
1091 }
1092 
1093 /// Assert that the given PDLValues match the constraints defined by the
1094 /// arguments of the given function. In the case of failure, a fatal error
1095 /// is emitted.
1096 template <typename PDLFnT, std::size_t... I>
1098  std::index_sequence<I...>) {
1099  // We only want to do verification in debug builds, same as with `assert`.
1100 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
1101  using FnTraitsT = llvm::function_traits<PDLFnT>;
1102  auto errorFn = [&](const Twine &msg) -> LogicalResult {
1103  llvm::report_fatal_error(msg);
1104  };
1105  (void)std::initializer_list<int>{
1106  (assert(succeeded(ProcessPDLValue<typename FnTraitsT::template arg_t<
1107  I + 1>>::verifyAsArg(errorFn, values[I], I))),
1108  0)...};
1109 #endif
1110 }
1111 
1112 //===----------------------------------------------------------------------===//
1113 // PDL Function Builder: Results Handling
1114 //===----------------------------------------------------------------------===//
1115 
1116 /// Store a single result within the result list.
1117 template <typename T>
1118 static void processResults(PatternRewriter &rewriter, PDLResultList &results,
1119  T &&value) {
1120  ProcessPDLValue<T>::processAsResult(rewriter, results,
1121  std::forward<T>(value));
1122 }
1123 
1124 /// Store a std::pair<> as individual results within the result list.
1125 template <typename T1, typename T2>
1126 static void processResults(PatternRewriter &rewriter, PDLResultList &results,
1127  std::pair<T1, T2> &&pair) {
1128  processResults(rewriter, results, std::move(pair.first));
1129  processResults(rewriter, results, std::move(pair.second));
1130 }
1131 
1132 /// Store a std::tuple<> as individual results within the result list.
1133 template <typename... Ts>
1134 static void processResults(PatternRewriter &rewriter, PDLResultList &results,
1135  std::tuple<Ts...> &&tuple) {
1136  auto applyFn = [&](auto &&...args) {
1137  // TODO: Use proper fold expressions when we have C++17. For now we use a
1138  // bogus std::initializer_list to work around C++14 limitations.
1139  (void)std::initializer_list<int>{
1140  (processResults(rewriter, results, std::move(args)), 0)...};
1141  };
1142  llvm::apply_tuple(applyFn, std::move(tuple));
1143 }
1144 
1145 //===----------------------------------------------------------------------===//
1146 // PDL Constraint Builder
1147 //===----------------------------------------------------------------------===//
1148 
1149 /// Process the arguments of a native constraint and invoke it.
1150 template <typename PDLFnT, std::size_t... I,
1151  typename FnTraitsT = llvm::function_traits<PDLFnT>>
1152 typename FnTraitsT::result_t
1154  ArrayRef<PDLValue> values,
1155  std::index_sequence<I...>) {
1156  return fn(
1157  rewriter,
1158  (ProcessPDLValue<typename FnTraitsT::template arg_t<I + 1>>::processAsArg(
1159  values[I]))...);
1160 }
1161 
1162 /// Build a constraint function from the given function `ConstraintFnT`. This
1163 /// allows for enabling the user to define simpler, more direct constraint
1164 /// functions without needing to handle the low-level PDL goop.
1165 ///
1166 /// If the constraint function is already in the correct form, we just forward
1167 /// it directly.
1168 template <typename ConstraintFnT>
1169 std::enable_if_t<
1172 buildConstraintFn(ConstraintFnT &&constraintFn) {
1173  return std::forward<ConstraintFnT>(constraintFn);
1174 }
1175 /// Otherwise, we generate a wrapper that will unpack the PDLValues in the form
1176 /// we desire.
1177 template <typename ConstraintFnT>
1178 std::enable_if_t<
1179  !std::is_convertible<ConstraintFnT, PDLConstraintFunction>::value,
1181 buildConstraintFn(ConstraintFnT &&constraintFn) {
1182  return [constraintFn = std::forward<ConstraintFnT>(constraintFn)](
1183  PatternRewriter &rewriter,
1184  ArrayRef<PDLValue> values) -> LogicalResult {
1185  auto argIndices = std::make_index_sequence<
1186  llvm::function_traits<ConstraintFnT>::num_args - 1>();
1187  if (failed(verifyAsArgs<ConstraintFnT>(rewriter, values, argIndices)))
1188  return failure();
1189  return processArgsAndInvokeConstraint(constraintFn, rewriter, values,
1190  argIndices);
1191  };
1192 }
1193 
1194 //===----------------------------------------------------------------------===//
1195 // PDL Rewrite Builder
1196 //===----------------------------------------------------------------------===//
1197 
1198 /// Process the arguments of a native rewrite and invoke it.
1199 /// This overload handles the case of no return values.
1200 template <typename PDLFnT, std::size_t... I,
1201  typename FnTraitsT = llvm::function_traits<PDLFnT>>
1205  std::index_sequence<I...>) {
1206  fn(rewriter,
1207  (ProcessPDLValue<typename FnTraitsT::template arg_t<I + 1>>::processAsArg(
1208  values[I]))...);
1209 }
1210 /// This overload handles the case of return values, which need to be packaged
1211 /// into the result list.
1212 template <typename PDLFnT, std::size_t... I,
1213  typename FnTraitsT = llvm::function_traits<PDLFnT>>
1216  PDLResultList &results, ArrayRef<PDLValue> values,
1217  std::index_sequence<I...>) {
1219  rewriter, results,
1220  fn(rewriter, (ProcessPDLValue<typename FnTraitsT::template arg_t<I + 1>>::
1221  processAsArg(values[I]))...));
1222 }
1223 
1224 /// Build a rewrite function from the given function `RewriteFnT`. This
1225 /// allows for enabling the user to define simpler, more direct rewrite
1226 /// functions without needing to handle the low-level PDL goop.
1227 ///
1228 /// If the rewrite function is already in the correct form, we just forward
1229 /// it directly.
1230 template <typename RewriteFnT>
1233 buildRewriteFn(RewriteFnT &&rewriteFn) {
1234  return std::forward<RewriteFnT>(rewriteFn);
1235 }
1236 /// Otherwise, we generate a wrapper that will unpack the PDLValues in the form
1237 /// we desire.
1238 template <typename RewriteFnT>
1241 buildRewriteFn(RewriteFnT &&rewriteFn) {
1242  return [rewriteFn = std::forward<RewriteFnT>(rewriteFn)](
1243  PatternRewriter &rewriter, PDLResultList &results,
1244  ArrayRef<PDLValue> values) {
1245  auto argIndices =
1246  std::make_index_sequence<llvm::function_traits<RewriteFnT>::num_args -
1247  1>();
1248  assertArgs<RewriteFnT>(rewriter, values, argIndices);
1249  processArgsAndInvokeRewrite(rewriteFn, rewriter, results, values,
1250  argIndices);
1251  };
1252 }
1253 
1254 } // namespace pdl_function_builder
1255 } // namespace detail
1256 
1257 /// This class contains all of the necessary data for a set of PDL patterns, or
1258 /// pattern rewrites specified in the form of the PDL dialect. This PDL module
1259 /// contained by this pattern may contain any number of `pdl.pattern`
1260 /// operations.
1262 public:
1263  PDLPatternModule() = default;
1264 
1265  /// Construct a PDL pattern with the given module.
1267  : pdlModule(std::move(pdlModule)) {}
1268 
1269  /// Merge the state in `other` into this pattern module.
1270  void mergeIn(PDLPatternModule &&other);
1271 
1272  /// Return the internal PDL module of this pattern.
1273  ModuleOp getModule() { return pdlModule.get(); }
1274 
1275  //===--------------------------------------------------------------------===//
1276  // Function Registry
1277 
1278  /// Register a constraint function with PDL. A constraint function may be
1279  /// specified in one of two ways:
1280  ///
1281  /// * `LogicalResult (PatternRewriter &, ArrayRef<PDLValue>)`
1282  ///
1283  /// In this overload the arguments of the constraint function are passed via
1284  /// the low-level PDLValue form.
1285  ///
1286  /// * `LogicalResult (PatternRewriter &, ValueTs... values)`
1287  ///
1288  /// In this form the arguments of the constraint function are passed via the
1289  /// expected high level C++ type. In this form, the framework will
1290  /// automatically unwrap PDLValues and convert them to the expected ValueTs.
1291  /// For example, if the constraint function accepts a `Operation *`, the
1292  /// framework will automatically cast the input PDLValue. In the case of a
1293  /// `StringRef`, the framework will automatically unwrap the argument as a
1294  /// StringAttr and pass the underlying string value. To see the full list of
1295  /// supported types, or to see how to add handling for custom types, view
1296  /// the definition of `ProcessPDLValue` above.
1297  void registerConstraintFunction(StringRef name,
1298  PDLConstraintFunction constraintFn);
1299  template <typename ConstraintFnT>
1300  void registerConstraintFunction(StringRef name,
1301  ConstraintFnT &&constraintFn) {
1302  registerConstraintFunction(name,
1304  std::forward<ConstraintFnT>(constraintFn)));
1305  }
1306 
1307  /// Register a rewrite function with PDL. A rewrite function may be specified
1308  /// in one of two ways:
1309  ///
1310  /// * `void (PatternRewriter &, PDLResultList &, ArrayRef<PDLValue>)`
1311  ///
1312  /// In this overload the arguments of the constraint function are passed via
1313  /// the low-level PDLValue form, and the results are manually appended to
1314  /// the given result list.
1315  ///
1316  /// * `ResultT (PatternRewriter &, ValueTs... values)`
1317  ///
1318  /// In this form the arguments and result of the rewrite function are passed
1319  /// via the expected high level C++ type. In this form, the framework will
1320  /// automatically unwrap the PDLValues arguments and convert them to the
1321  /// expected ValueTs. It will also automatically handle the processing and
1322  /// packaging of the result value to the result list. For example, if the
1323  /// rewrite function takes a `Operation *`, the framework will automatically
1324  /// cast the input PDLValue. In the case of a `StringRef`, the framework
1325  /// will automatically unwrap the argument as a StringAttr and pass the
1326  /// underlying string value. In the reverse case, if the rewrite returns a
1327  /// StringRef or std::string, it will automatically package this as a
1328  /// StringAttr and append it to the result list. To see the full list of
1329  /// supported types, or to see how to add handling for custom types, view
1330  /// the definition of `ProcessPDLValue` above.
1331  void registerRewriteFunction(StringRef name, PDLRewriteFunction rewriteFn);
1332  template <typename RewriteFnT>
1333  void registerRewriteFunction(StringRef name, RewriteFnT &&rewriteFn) {
1334  registerRewriteFunction(name, detail::pdl_function_builder::buildRewriteFn(
1335  std::forward<RewriteFnT>(rewriteFn)));
1336  }
1337 
1338  /// Return the set of the registered constraint functions.
1339  const llvm::StringMap<PDLConstraintFunction> &getConstraintFunctions() const {
1340  return constraintFunctions;
1341  }
1342  llvm::StringMap<PDLConstraintFunction> takeConstraintFunctions() {
1343  return constraintFunctions;
1344  }
1345  /// Return the set of the registered rewrite functions.
1346  const llvm::StringMap<PDLRewriteFunction> &getRewriteFunctions() const {
1347  return rewriteFunctions;
1348  }
1349  llvm::StringMap<PDLRewriteFunction> takeRewriteFunctions() {
1350  return rewriteFunctions;
1351  }
1352 
1353  /// Clear out the patterns and functions within this module.
1354  void clear() {
1355  pdlModule = nullptr;
1356  constraintFunctions.clear();
1357  rewriteFunctions.clear();
1358  }
1359 
1360 private:
1361  /// The module containing the `pdl.pattern` operations.
1362  OwningOpRef<ModuleOp> pdlModule;
1363 
1364  /// The external functions referenced from within the PDL module.
1365  llvm::StringMap<PDLConstraintFunction> constraintFunctions;
1366  llvm::StringMap<PDLRewriteFunction> rewriteFunctions;
1367 };
1368 
1369 //===----------------------------------------------------------------------===//
1370 // RewritePatternSet
1371 //===----------------------------------------------------------------------===//
1372 
1374  using NativePatternListT = std::vector<std::unique_ptr<RewritePattern>>;
1375 
1376 public:
1377  RewritePatternSet(MLIRContext *context) : context(context) {}
1378 
1379  /// Construct a RewritePatternSet populated with the given pattern.
1381  std::unique_ptr<RewritePattern> pattern)
1382  : context(context) {
1383  nativePatterns.emplace_back(std::move(pattern));
1384  }
1386  : context(pattern.getModule()->getContext()),
1387  pdlPatterns(std::move(pattern)) {}
1388 
1389  MLIRContext *getContext() const { return context; }
1390 
1391  /// Return the native patterns held in this list.
1392  NativePatternListT &getNativePatterns() { return nativePatterns; }
1393 
1394  /// Return the PDL patterns held in this list.
1395  PDLPatternModule &getPDLPatterns() { return pdlPatterns; }
1396 
1397  /// Clear out all of the held patterns in this list.
1398  void clear() {
1399  nativePatterns.clear();
1400  pdlPatterns.clear();
1401  }
1402 
1403  //===--------------------------------------------------------------------===//
1404  // 'add' methods for adding patterns to the set.
1405  //===--------------------------------------------------------------------===//
1406 
1407  /// Add an instance of each of the pattern types 'Ts' to the pattern list with
1408  /// the given arguments. Return a reference to `this` for chaining insertions.
1409  /// Note: ConstructorArg is necessary here to separate the two variadic lists.
1410  template <typename... Ts, typename ConstructorArg,
1411  typename... ConstructorArgs,
1412  typename = std::enable_if_t<sizeof...(Ts) != 0>>
1413  RewritePatternSet &add(ConstructorArg &&arg, ConstructorArgs &&... args) {
1414  // The following expands a call to emplace_back for each of the pattern
1415  // types 'Ts'. This magic is necessary due to a limitation in the places
1416  // that a parameter pack can be expanded in c++11.
1417  // FIXME: In c++17 this can be simplified by using 'fold expressions'.
1418  (void)std::initializer_list<int>{
1419  0, (addImpl<Ts>(/*debugLabels=*/llvm::None, arg, args...), 0)...};
1420  return *this;
1421  }
1422  /// An overload of the above `add` method that allows for attaching a set
1423  /// of debug labels to the attached patterns. This is useful for labeling
1424  /// groups of patterns that may be shared between multiple different
1425  /// passes/users.
1426  template <typename... Ts, typename ConstructorArg,
1427  typename... ConstructorArgs,
1428  typename = std::enable_if_t<sizeof...(Ts) != 0>>
1430  ConstructorArg &&arg,
1431  ConstructorArgs &&... args) {
1432  // The following expands a call to emplace_back for each of the pattern
1433  // types 'Ts'. This magic is necessary due to a limitation in the places
1434  // that a parameter pack can be expanded in c++11.
1435  // FIXME: In c++17 this can be simplified by using 'fold expressions'.
1436  (void)std::initializer_list<int>{
1437  0, (addImpl<Ts>(debugLabels, arg, args...), 0)...};
1438  return *this;
1439  }
1440 
1441  /// Add an instance of each of the pattern types 'Ts'. Return a reference to
1442  /// `this` for chaining insertions.
1443  template <typename... Ts>
1445  (void)std::initializer_list<int>{0, (addImpl<Ts>(), 0)...};
1446  return *this;
1447  }
1448 
1449  /// Add the given native pattern to the pattern list. Return a reference to
1450  /// `this` for chaining insertions.
1451  RewritePatternSet &add(std::unique_ptr<RewritePattern> pattern) {
1452  nativePatterns.emplace_back(std::move(pattern));
1453  return *this;
1454  }
1455 
1456  /// Add the given PDL pattern to the pattern list. Return a reference to
1457  /// `this` for chaining insertions.
1459  pdlPatterns.mergeIn(std::move(pattern));
1460  return *this;
1461  }
1462 
1463  // Add a matchAndRewrite style pattern represented as a C function pointer.
1464  template <typename OpType>
1466  PatternRewriter &rewriter)) {
1467  struct FnPattern final : public OpRewritePattern<OpType> {
1468  FnPattern(LogicalResult (*implFn)(OpType, PatternRewriter &rewriter),
1469  MLIRContext *context)
1470  : OpRewritePattern<OpType>(context), implFn(implFn) {}
1471 
1472  LogicalResult matchAndRewrite(OpType op,
1473  PatternRewriter &rewriter) const override {
1474  return implFn(op, rewriter);
1475  }
1476 
1477  private:
1478  LogicalResult (*implFn)(OpType, PatternRewriter &rewriter);
1479  };
1480  add(std::make_unique<FnPattern>(std::move(implFn), getContext()));
1481  return *this;
1482  }
1483 
1484  //===--------------------------------------------------------------------===//
1485  // Pattern Insertion
1486  //===--------------------------------------------------------------------===//
1487 
1488  // TODO: These are soft deprecated in favor of the 'add' methods above.
1489 
1490  /// Add an instance of each of the pattern types 'Ts' to the pattern list with
1491  /// the given arguments. Return a reference to `this` for chaining insertions.
1492  /// Note: ConstructorArg is necessary here to separate the two variadic lists.
1493  template <typename... Ts, typename ConstructorArg,
1494  typename... ConstructorArgs,
1495  typename = std::enable_if_t<sizeof...(Ts) != 0>>
1496  RewritePatternSet &insert(ConstructorArg &&arg, ConstructorArgs &&... args) {
1497  // The following expands a call to emplace_back for each of the pattern
1498  // types 'Ts'. This magic is necessary due to a limitation in the places
1499  // that a parameter pack can be expanded in c++11.
1500  // FIXME: In c++17 this can be simplified by using 'fold expressions'.
1501  (void)std::initializer_list<int>{
1502  0, (addImpl<Ts>(/*debugLabels=*/llvm::None, arg, args...), 0)...};
1503  return *this;
1504  }
1505 
1506  /// Add an instance of each of the pattern types 'Ts'. Return a reference to
1507  /// `this` for chaining insertions.
1508  template <typename... Ts>
1510  (void)std::initializer_list<int>{0, (addImpl<Ts>(), 0)...};
1511  return *this;
1512  }
1513 
1514  /// Add the given native pattern to the pattern list. Return a reference to
1515  /// `this` for chaining insertions.
1516  RewritePatternSet &insert(std::unique_ptr<RewritePattern> pattern) {
1517  nativePatterns.emplace_back(std::move(pattern));
1518  return *this;
1519  }
1520 
1521  /// Add the given PDL pattern to the pattern list. Return a reference to
1522  /// `this` for chaining insertions.
1524  pdlPatterns.mergeIn(std::move(pattern));
1525  return *this;
1526  }
1527 
1528  // Add a matchAndRewrite style pattern represented as a C function pointer.
1529  template <typename OpType>
1531  insert(LogicalResult (*implFn)(OpType, PatternRewriter &rewriter)) {
1532  struct FnPattern final : public OpRewritePattern<OpType> {
1533  FnPattern(LogicalResult (*implFn)(OpType, PatternRewriter &rewriter),
1534  MLIRContext *context)
1535  : OpRewritePattern<OpType>(context), implFn(implFn) {
1536  this->setDebugName(llvm::getTypeName<FnPattern>());
1537  }
1538 
1539  LogicalResult matchAndRewrite(OpType op,
1540  PatternRewriter &rewriter) const override {
1541  return implFn(op, rewriter);
1542  }
1543 
1544  private:
1545  LogicalResult (*implFn)(OpType, PatternRewriter &rewriter);
1546  };
1547  add(std::make_unique<FnPattern>(std::move(implFn), getContext()));
1548  return *this;
1549  }
1550 
1551 private:
1552  /// Add an instance of the pattern type 'T'. Return a reference to `this` for
1553  /// chaining insertions.
1554  template <typename T, typename... Args>
1556  addImpl(ArrayRef<StringRef> debugLabels, Args &&... args) {
1557  std::unique_ptr<T> pattern =
1558  RewritePattern::create<T>(std::forward<Args>(args)...);
1559  pattern->addDebugLabels(debugLabels);
1560  nativePatterns.emplace_back(std::move(pattern));
1561  }
1562  template <typename T, typename... Args>
1564  addImpl(ArrayRef<StringRef> debugLabels, Args &&... args) {
1565  // TODO: Add the provided labels to the PDL pattern when PDL supports
1566  // labels.
1567  pdlPatterns.mergeIn(T(std::forward<Args>(args)...));
1568  }
1569 
1570  MLIRContext *const context;
1571  NativePatternListT nativePatterns;
1572  PDLPatternModule pdlPatterns;
1573 };
1574 
1575 } // namespace mlir
1576 
1577 #endif // MLIR_IR_PATTERNMATCH_H
T cast() const
Cast this value to type T, asserts if this value is not an instance of T.
Definition: PatternMatch.h:650
Location getUnknownLoc()
Definition: Builders.cpp:26
bool operator<(const PatternBenefit &rhs) const
Definition: PatternMatch.h:52
TODO: Remove this file when SCCP and integer range analysis have been ported to the new framework...
static LogicalResult verifyAsArg(function_ref< LogicalResult(const Twine &)> errorFn, PDLValue pdlValue, size_t argIdx)
Definition: PatternMatch.h:915
static void processAsResult(PatternRewriter &, PDLResultList &results, OperandRange values)
This class contains a list of basic blocks and a link to the parent operation it is attached to...
Definition: Region.h:26
PDLValue(TypeRange *value)
Definition: PatternMatch.h:626
static std::string diag(llvm::Value &v)
static void processAsResult(PatternRewriter &rewriter, PDLResultList &results, StringRef value)
Definition: PatternMatch.h:991
void push_back(ResultRange value)
Definition: PatternMatch.h:773
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:600
Optional< TypeID > getRootInterfaceID() const
Return the interface ID used to match the root operation of this pattern.
Definition: PatternMatch.h:101
This class acts as a special tag that makes the desire to match any operation that implements a given...
Definition: PatternMatch.h:162
Operation is a basic unit of execution within MLIR.
Definition: Operation.h:28
virtual void rewrite(SourceOp op, PatternRewriter &rewriter) const
Rewrite and Match methods that operate on the SourceOp type.
Definition: PatternMatch.h:334
bool isa() const
Returns true if the type of the held value is T.
Definition: PatternMatch.h:633
ResultT dyn_cast() const
Attempt to dynamically cast this value to type T, returns null if this value is not an instance of T...
Definition: PatternMatch.h:643
RewritePatternSet & insert(std::unique_ptr< RewritePattern > pattern)
Add the given native pattern to the pattern list.
void push_back(OperandRange value)
Definition: PatternMatch.h:769
const llvm::StringMap< PDLRewriteFunction > & getRewriteFunctions() const
Return the set of the registered rewrite functions.
SmallVector< PDLValue > results
The PDL results held by this list.
Definition: PatternMatch.h:789
Block represents an ordered list of Operations.
Definition: Block.h:29
static LogicalResult verifyAsArg(function_ref< LogicalResult(const Twine &)> errorFn, BaseT value, size_t argIdx)
Explicitly add the expected parent API to ensure the parent class implements the necessary API (and d...
Definition: PatternMatch.h:902
PDLResultList(unsigned maxNumResults)
Create a new result list with the expected number of results.
Definition: PatternMatch.h:780
PDLValue(Type value)
Definition: PatternMatch.h:625
IRRewriter(const OpBuilder &builder)
Definition: PatternMatch.h:587
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
This struct provides a simplified model for processing types that are based on another type...
Definition: PatternMatch.h:883
RewritePatternSet & add(PDLPatternModule &&pattern)
Add the given PDL pattern to the pattern list.
bool failed(LogicalResult result)
Utility function that returns true if the provided LogicalResult corresponds to a failure value...
Definition: LogicalResult.h:72
RewritePatternSet & insert(PDLPatternModule &&pattern)
Add the given PDL pattern to the pattern list.
BlockListType::iterator iterator
Definition: Region.h:52
OpInterfaceRewritePattern(MLIRContext *context, PatternBenefit benefit=1)
Definition: PatternMatch.h:372
OpTraitRewritePattern(MLIRContext *context, PatternBenefit benefit=1)
Definition: PatternMatch.h:384
This class implements the result iterators for the Operation class.
bool succeeded(LogicalResult result)
Utility function that returns true if the provided LogicalResult corresponds to a success value...
Definition: LogicalResult.h:68
void push_back(Operation *value)
Push a new Operation onto the result list.
Definition: PatternMatch.h:732
LogicalResult match(Operation *op) const final
Attempt to match against code rooted at the specified operation, which is the same operation code as ...
Definition: PatternMatch.h:324
static void processAsResult(PatternRewriter &rewriter, PDLResultList &results, StringRef value)
Definition: PatternMatch.h:976
LogicalResult verifyAsArgs(PatternRewriter &rewriter, ArrayRef< PDLValue > values, std::index_sequence< I... >)
Validate the given PDLValues match the constraints defined by the argument types of the given functio...
llvm::StringMap< PDLRewriteFunction > takeRewriteFunctions()
PatternBenefit & operator=(const PatternBenefit &)=default
virtual void startRootUpdate(Operation *op)
This method is used to notify the rewriter that an in-place operation modification is about to happen...
Definition: PatternMatch.h:484
LogicalResult notifyMatchFailure(ArgT &&arg, const char *msg)
Definition: PatternMatch.h:532
const void * getAsOpaquePointer() const
Get an opaque pointer to the value.
Definition: PatternMatch.h:656
raw_ostream & operator<<(raw_ostream &os, const AliasResult &result)
Definition: AliasAnalysis.h:78
void rewrite(Operation *op, PatternRewriter &rewriter) const final
Wrappers around the RewritePattern methods that pass the derived op type.
Definition: PatternMatch.h:321
PDLValue(Value value)
Definition: PatternMatch.h:627
This class represents a listener that may be used to hook into various actions within an OpBuilder...
Definition: Builders.h:241
RewritePatternSet(MLIRContext *context, std::unique_ptr< RewritePattern > pattern)
Construct a RewritePatternSet populated with the given pattern.
PDLValue(Attribute value)
Definition: PatternMatch.h:622
FnTraitsT::result_t processArgsAndInvokeConstraint(PDLFnT &fn, PatternRewriter &rewriter, ArrayRef< PDLValue > values, std::index_sequence< I... >)
Process the arguments of a native constraint and invoke it.
static constexpr const bool value
void registerRewriteFunction(StringRef name, RewriteFnT &&rewriteFn)
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:104
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:48
void addDebugLabels(StringRef label)
Definition: PatternMatch.h:151
std::function< void(PatternRewriter &, PDLResultList &, ArrayRef< PDLValue >)> PDLRewriteFunction
A native PDL rewrite function.
Definition: PatternMatch.h:812
static OperationName getFromOpaquePointer(const void *pointer)
This class contains all of the data related to a pattern, but does not contain any methods or logic f...
Definition: PatternMatch.h:71
NativePatternListT & getNativePatterns()
Return the native patterns held in this list.
llvm::StringMap< PDLConstraintFunction > takeConstraintFunctions()
RewritePattern is the common base class for all DAG to DAG replacements.
Definition: PatternMatch.h:244
void setHasBoundedRewriteRecursion(bool hasBoundedRecursionArg=true)
Set the flag detailing if this pattern has bounded rewrite recursion or not.
Definition: PatternMatch.h:200
void push_back(TypeRange value)
Push a new TypeRange onto the result list.
Definition: PatternMatch.h:738
unsigned short getBenefit() const
If the corresponding pattern can match, return its benefit. If the.
ModuleOp getModule()
Return the internal PDL module of this pattern.
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:274
LogicalResult success(bool isSuccess=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:56
std::function< LogicalResult(PatternRewriter &, ArrayRef< PDLValue >)> PDLConstraintFunction
A generic PDL pattern constraint function.
Definition: PatternMatch.h:806
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine...
Definition: Diagnostics.h:157
PDLValue(ValueRange *value)
Definition: PatternMatch.h:629
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26
LogicalResult failure(bool isFailure=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:62
static PatternBenefit impossibleToMatch()
Definition: PatternMatch.h:41
bool operator<=(const PatternBenefit &rhs) const
Definition: PatternMatch.h:56
OpListType::iterator iterator
Definition: Block.h:131
This class contains all of the necessary data for a set of PDL patterns, or pattern rewrites specifie...
virtual LogicalResult notifyMatchFailure(Location loc, function_ref< void(Diagnostic &)> reasonCallback)
Notify the rewriter that the pattern failed to match the given operation, and provide a callback to p...
Definition: PatternMatch.h:562
static void processAsResult(PatternRewriter &, PDLResultList &results, ValueTypeRange< ResultRange > types)
Storage type of byte-code interpreter values.
Definition: PatternMatch.h:614
LogicalResult matchAndRewrite(Operation *op, PatternRewriter &rewriter) const final
Attempt to match against code rooted at the specified operation, which is the same operation code as ...
Definition: PatternMatch.h:327
Attributes are known-constant values of operations.
Definition: Attributes.h:24
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
Definition: PatternMatch.h:32
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
void push_back(Attribute value)
Push a new Attribute value onto the result list.
Definition: PatternMatch.h:729
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...
void assertArgs(PatternRewriter &rewriter, ArrayRef< PDLValue > values, std::index_sequence< I... >)
Assert that the given PDLValues match the constraints defined by the arguments of the given function...
void clear()
Clear out the patterns and functions within this module.
Optional< TypeID > getRootTraitID() const
Return the trait ID used to match the root operation of this pattern.
Definition: PatternMatch.h:110
ArrayRef< StringRef > getDebugLabels() const
Return the set of debug labels attached to this pattern.
Definition: PatternMatch.h:145
void push_back(ValueRange value)
Push a new ValueRange onto the result list.
Definition: PatternMatch.h:760
bool operator>=(const PatternBenefit &rhs) const
Definition: PatternMatch.h:57
ArrayRef< OperationName > getGeneratedOps() const
Return a list of operations that may be generated when rewriting an operation instance with this patt...
Definition: PatternMatch.h:88
void setDebugName(StringRef name)
Set the human readable debug name used for this pattern.
Definition: PatternMatch.h:142
This class provides an abstraction over the various different ranges of value types.
Definition: TypeRange.h:38
void push_back(Type value)
Push a new Type onto the result list.
Definition: PatternMatch.h:735
virtual void notifyRootReplaced(Operation *op)
These are the callback methods that subclasses can choose to implement if they would like to be notif...
Definition: PatternMatch.h:551
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:360
void updateRootInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around a root update of an operation.
Definition: PatternMatch.h:499
std::enable_if_t<!std::is_convertible< RewriteFnT, PDLRewriteFunction >::value, PDLRewriteFunction > buildRewriteFn(RewriteFnT &&rewriteFn)
Otherwise, we generate a wrapper that will unpack the PDLValues in the form we desire.
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:161
static void rewrite(SCCPAnalysis &analysis, MLIRContext *context, MutableArrayRef< Region > initialRegions)
Rewrite the given regions using the computing analysis.
Definition: SCCP.cpp:195
This class acts as a special tag that makes the desire to match "any" operation type explicit...
Definition: PatternMatch.h:157
PatternBenefit()=default
RewriterBase(MLIRContext *ctx)
Initialize the builder with this rewriter as the listener.
Definition: PatternMatch.h:538
static LogicalResult verifyAsArg(function_ref< LogicalResult(const Twine &)> errorFn, BaseT baseValue, size_t argIdx)
Definition: PatternMatch.h:937
virtual LogicalResult matchAndRewrite(Operation *op, PatternRewriter &rewriter) const
Attempt to match against code rooted at the specified operation, which is the same operation code as ...
Definition: PatternMatch.h:262
bool hasBoundedRewriteRecursion() const
Returns true if this pattern is known to result in recursive application, i.e.
Definition: PatternMatch.h:127
RewritePatternSet & add()
Add an instance of each of the pattern types &#39;Ts&#39;.
const llvm::StringMap< PDLConstraintFunction > & getConstraintFunctions() const
Return the set of the registered constraint functions.
std::enable_if_t<!std::is_same< typename FnTraitsT::result_t, void >::value > processArgsAndInvokeRewrite(PDLFnT &fn, PatternRewriter &rewriter, PDLResultList &results, ArrayRef< PDLValue > values, std::index_sequence< I... >)
This overload handles the case of return values, which need to be packaged into the result list...
std::enable_if_t< std::is_convertible< RewriteFnT, PDLRewriteFunction >::value, PDLRewriteFunction > buildRewriteFn(RewriteFnT &&rewriteFn)
Build a rewrite function from the given function RewriteFnT.
virtual void finalizeRootUpdate(Operation *op)
This method is used to signal the end of a root update on the given operation.
Definition: PatternMatch.h:489
Kind
The underlying kind of a PDL value.
Definition: PatternMatch.h:617
RewriterBase(const OpBuilder &otherBuilder)
Definition: PatternMatch.h:539
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:72
LogicalResult notifyMatchFailure(ArgT &&arg, const Twine &msg)
Definition: PatternMatch.h:527
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
Definition: PatternMatch.h:584
bool operator>(const PatternBenefit &rhs) const
Definition: PatternMatch.h:55
This struct provides a simplified model for processing types that have "builtin" PDLValue support: ...
Definition: PatternMatch.h:913
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:85
RewritePatternSet & add(std::unique_ptr< RewritePattern > pattern)
Add the given native pattern to the pattern list.
SmallVector< TypeRange > typeRanges
Memory used to store ranges held by the list.
Definition: PatternMatch.h:791
SmallVector< ValueRange > valueRanges
Definition: PatternMatch.h:792
PDLPatternModule(OwningOpRef< ModuleOp > pdlModule)
Construct a PDL pattern with the given module.
RewritePatternSet(MLIRContext *context)
This class implements iteration on the types of a given range of values.
Definition: Block.h:26
static void processAsResult(PatternRewriter &, PDLResultList &results, T value)
Definition: PatternMatch.h:953
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
Definition: PatternMatch.h:355
static TypeID getFromOpaquePointer(const void *pointer)
Definition: TypeID.h:132
bool isImpossibleToMatch() const
Definition: PatternMatch.h:42
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&... args)
Add an instance of each of the pattern types &#39;Ts&#39; to the pattern list with the given arguments...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replaces the result op with a new op that is created without verification.
Definition: PatternMatch.h:451
static void processResults(PatternRewriter &rewriter, PDLResultList &results, std::tuple< Ts... > &&tuple)
Store a std::tuple<> as individual results within the result list.
void addDebugLabels(ArrayRef< StringRef > labels)
Add the provided debug labels to this pattern.
Definition: PatternMatch.h:148
Kind getKind() const
Return the kind of this value.
Definition: PatternMatch.h:662
virtual LogicalResult matchAndRewrite(SourceOp op, PatternRewriter &rewriter) const
Definition: PatternMatch.h:340
virtual LogicalResult match(SourceOp op) const
Definition: PatternMatch.h:337
RewritePatternSet & add(LogicalResult(*implFn)(OpType, PatternRewriter &rewriter))
IRRewriter(MLIRContext *ctx)
Definition: PatternMatch.h:586
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:55
bool operator==(const PatternBenefit &rhs) const
Definition: PatternMatch.h:48
This class represents an operand of an operation.
Definition: Value.h:251
void clear()
Clear out all of the held patterns in this list.
OpOrInterfaceRewritePatternBase is a wrapper around RewritePattern that allows for matching and rewri...
Definition: PatternMatch.h:317
The class represents a list of PDL results, returned by a native rewrite method.
Definition: PatternMatch.h:726
This class implements the operand iterators for the Operation class.
void replaceOpWithIf(Operation *op, ValueRange newValues, llvm::unique_function< bool(OpOperand &) const > functor)
Definition: PatternMatch.h:430
PDLValue(Operation *value)
Definition: PatternMatch.h:624
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the rewriter that the IR failed to be rewritten because of a match failure...
Definition: PatternMatch.h:512
This class acts as a special tag that makes the desire to match any operation that implements a given...
Definition: PatternMatch.h:167
This struct provides a convenient way to determine how to process a given type as either a PDL parame...
Definition: PatternMatch.h:863
void push_back(ValueTypeRange< OperandRange > value)
Definition: PatternMatch.h:747
void push_back(ValueTypeRange< ResultRange > value)
Definition: PatternMatch.h:751
PDLPatternModule & getPDLPatterns()
Return the PDL patterns held in this list.
static void processAsResult(PatternRewriter &, PDLResultList &results, ResultRange values)
virtual void notifyOperationRemoved(Operation *op)
This is called on an operation that a rewrite is removing, right before the operation is deleted...
Definition: PatternMatch.h:555
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Operation *op, CallbackT &&reasonCallback)
Definition: PatternMatch.h:522
MLIRContext * getContext() const
Return the MLIRContext used to create this pattern.
Definition: PatternMatch.h:132
RewritePatternSet(PDLPatternModule &&pattern)
This struct provides a simplified model for processing types that inherit from builtin PDLValue types...
Definition: PatternMatch.h:935
void push_back(Value value)
Push a new Value onto the result list.
Definition: PatternMatch.h:757
void registerConstraintFunction(StringRef name, ConstraintFnT &&constraintFn)
static void processAsResult(PatternRewriter &, PDLResultList &results, T value)
Definition: PatternMatch.h:924
static LogicalResult verifyAsArg(function_ref< LogicalResult(const Twine &)> errorFn, PDLValue pdlValue, size_t argIdx)
Definition: PatternMatch.h:885
StringRef getDebugName() const
Return a readable name for this pattern.
Definition: PatternMatch.h:138
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...
PDLValue(std::nullptr_t=nullptr)
Definition: PatternMatch.h:621
This class helps build Operations.
Definition: Builders.h:184
This class provides an abstraction over the different types of ranges over Values.
SmallVector< llvm::OwningArrayRef< Type > > allocatedTypeRanges
Memory allocated to store ranges in the result list whose lifetime was generated in the native functi...
Definition: PatternMatch.h:795
bool operator!=(const PatternBenefit &rhs) const
Definition: PatternMatch.h:51
virtual void cancelRootUpdate(Operation *op)
This method cancels a pending root update.
Definition: PatternMatch.h:493
void print(raw_ostream &os) const
Print this value to the provided output stream.
RewritePatternSet & insert(LogicalResult(*implFn)(OpType, PatternRewriter &rewriter))
constexpr bool always_false
A utility variable that always resolves to false.
Definition: PatternMatch.h:827
StringAttr getStringAttr(const Twine &bytes)
Definition: Builders.cpp:201
SmallVector< llvm::OwningArrayRef< Value > > allocatedValueRanges
Definition: PatternMatch.h:796
RewritePatternSet & insert()
Add an instance of each of the pattern types &#39;Ts&#39;.
static void processAsResult(PatternRewriter &, PDLResultList &results, ValueTypeRange< OperandRange > types)
PatternBenefit getBenefit() const
Return the benefit (the inverse of "cost") of matching this pattern.
Definition: PatternMatch.h:121
MLIRContext * getContext() const
std::enable_if_t< !std::is_convertible< ConstraintFnT, PDLConstraintFunction >::value, PDLConstraintFunction > buildConstraintFn(ConstraintFnT &&constraintFn)
Otherwise, we generate a wrapper that will unpack the PDLValues in the form we desire.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:398
std::enable_if_t< std::is_convertible< ConstraintFnT, PDLConstraintFunction >::value, PDLConstraintFunction > buildConstraintFn(ConstraintFnT &&constraintFn)
Build a constraint function from the given function ConstraintFnT.
OpTraitRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting again...
Definition: PatternMatch.h:382
OpInterfaceRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting a...
Definition: PatternMatch.h:370
RewritePatternSet & insert(ConstructorArg &&arg, ConstructorArgs &&... args)
Add an instance of each of the pattern types &#39;Ts&#39; to the pattern list with the given arguments...
Optional< OperationName > getRootKind() const
Return the root node that this pattern matches.
Definition: PatternMatch.h:92