MLIR  18.0.0git
TransformInterfaces.h
Go to the documentation of this file.
1 //===- TransformInterfaces.h - Transform Dialect Interfaces -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef MLIR_DIALECT_TRANSFORM_IR_TRANSFORMINTERFACES_H
10 #define MLIR_DIALECT_TRANSFORM_IR_TRANSFORMINTERFACES_H
11 
15 #include "mlir/IR/OpDefinition.h"
16 #include "mlir/IR/PatternMatch.h"
20 
21 namespace mlir {
22 namespace transform {
23 
24 class TransformOpInterface;
25 class TransformResults;
26 class TransformRewriter;
27 class TransformState;
28 
29 using Param = Attribute;
31 
32 namespace detail {
33 /// Maps the only block argument of the op with PossibleTopLevelTransformOpTrait
34 /// to either the list of operations associated with its operand or the root of
35 /// the payload IR, depending on what is available in the context.
38  Operation *op, Region &region);
39 
40 /// Verification hook for PossibleTopLevelTransformOpTrait.
42 
43 /// Populates `effects` with side effects implied by
44 /// PossibleTopLevelTransformOpTrait for the given operation. The operation may
45 /// have an optional `root` operand, indicating it is not in fact top-level. It
46 /// is also expected to have a single-block body.
48  Operation *operation, Value root, Block &body,
50 
51 /// Verification hook for TransformOpInterface.
53 
54 /// Populates `mappings` with mapped values associated with the given transform
55 /// IR values in the given `state`.
58  ValueRange values, const transform::TransformState &state);
59 
60 /// Populates `results` with payload associations that match exactly those of
61 /// the operands to `block`'s terminator.
64 
65 /// Make a dummy transform state for testing purposes. This MUST NOT be used
66 /// outside of test cases.
68  Operation *payloadRoot);
69 
70 /// Returns all operands that are handles and being consumed by the given op.
72 getConsumedHandleOpOperands(transform::TransformOpInterface transformOp);
73 } // namespace detail
74 } // namespace transform
75 } // namespace mlir
76 
77 #include "mlir/Dialect/Transform/IR/TransformInterfaces.h.inc"
78 
79 namespace mlir {
80 namespace transform {
81 
82 /// Options controlling the application of transform operations by the
83 /// TransformState.
85 public:
86  TransformOptions() = default;
87  TransformOptions(const TransformOptions &) = default;
89 
90  /// Requests computationally expensive checks of the transform and payload IR
91  /// well-formedness to be performed before each transformation. In particular,
92  /// these ensure that the handles still point to valid operations when used.
93  TransformOptions &enableExpensiveChecks(bool enable = true) {
94  expensiveChecksEnabled = enable;
95  return *this;
96  }
97 
98  // Ensures that only a single top-level transform op is present in the IR.
100  enforceSingleToplevelTransformOp = enable;
101  return *this;
102  }
103 
104  /// Returns true if the expensive checks are requested.
105  bool getExpensiveChecksEnabled() const { return expensiveChecksEnabled; }
106 
107  // Returns true if enforcing a single top-level transform op is requested.
109  return enforceSingleToplevelTransformOp;
110  }
111 
112 private:
113  bool expensiveChecksEnabled = true;
114  bool enforceSingleToplevelTransformOp = true;
115 };
116 
117 /// Entry point to the Transform dialect infrastructure. Applies the
118 /// transformation specified by `transform` to payload IR contained in
119 /// `payloadRoot`. The `transform` operation may contain other operations that
120 /// will be executed following the internal logic of the operation. It must
121 /// have the `PossibleTopLevelTransformOp` trait and not have any operands.
122 /// This function internally keeps track of the transformation state.
124 applyTransforms(Operation *payloadRoot, TransformOpInterface transform,
125  const RaggedArray<MappedValue> &extraMapping = {},
126  const TransformOptions &options = TransformOptions(),
127  bool enforceToplevelTransformOp = true);
128 
129 /// The state maintained across applications of various ops implementing the
130 /// TransformOpInterface. The operations implementing this interface and the
131 /// surrounding structure are referred to as transform IR. The operations to
132 /// which transformations apply are referred to as payload IR. Transform IR
133 /// operates on values that can be associated either with a list of payload IR
134 /// operations (such values are referred to as handles) or with a list of
135 /// parameters represented as attributes. The state thus contains the mapping
136 /// between values defined in the transform IR ops and either payload IR ops or
137 /// parameters. For payload ops, the mapping is many-to-many and the reverse
138 /// mapping is also stored. The "expensive-checks" option can be passed to the
139 /// constructor at transformation execution time that transform IR values used
140 /// as operands by a transform IR operation are not associated with dangling
141 /// pointers to payload IR operations that are known to have been erased by
142 /// previous transformation through the same or a different transform IR value.
143 ///
144 /// A reference to this class is passed as an argument to "apply" methods of the
145 /// transform op interface. Thus the "apply" method can call either
146 /// `state.getPayloadOps( getSomeOperand() )` to obtain the list of operations
147 /// or `state.getParams( getSomeOperand() )` to obtain the list of parameters
148 /// associated with its operand. The method is expected to populate the
149 /// `TransformResults` class instance in order to update the mapping. The
150 /// `applyTransform` method takes care of propagating the state of
151 /// `TransformResults` into the instance of this class.
152 ///
153 /// When applying transform IR operations with regions, the client is expected
154 /// to create a `RegionScope` RAII object to create a new "stack frame" for
155 /// values defined inside the region. The mappings from and to these values will
156 /// be automatically dropped when the object goes out of scope, typically at the
157 /// end of the `apply` function of the parent operation. If a region contains
158 /// blocks with arguments, the client can map those arguments to payload IR ops
159 /// using `mapBlockArguments`.
161 public:
163 
164 private:
165  /// Mapping between a Value in the transform IR and the corresponding set of
166  /// operations in the payload IR.
168 
169  /// Mapping between a payload IR operation and the transform IR values it is
170  /// associated with.
173 
174  /// Mapping between a Value in the transform IR and the corresponding list of
175  /// parameters.
177 
178  /// Mapping between a Value in the transform IR and the corrsponding list of
179  /// values in the payload IR. Also works for reverse mappings.
181 
182  /// Mapping between a Value in the transform IR and an error message that
183  /// should be emitted when the value is used.
184  using InvalidatedHandleMap = DenseMap<Value, std::function<void(Location)>>;
185 
186 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
187  /// Debug only: A timestamp is associated with each transform IR value, so
188  /// that invalid iterator usage can be detected more reliably.
189  using TransformIRTimestampMapping = DenseMap<Value, int64_t>;
190 #endif // LLVM_ENABLE_ABI_BREAKING_CHECKS
191 
192  /// The bidirectional mappings between transform IR values and payload IR
193  /// operations, and the mapping between transform IR values and parameters.
194  struct Mappings {
195  TransformOpMapping direct;
197  ParamMapping params;
198  ValueMapping values;
199  ValueMapping reverseValues;
200 
201 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
202  TransformIRTimestampMapping timestamps;
203  void incrementTimestamp(Value value) { ++timestamps[value]; }
204 #endif // LLVM_ENABLE_ABI_BREAKING_CHECKS
205  };
206 
207  friend LogicalResult applyTransforms(Operation *, TransformOpInterface,
208  const RaggedArray<MappedValue> &,
209  const TransformOptions &, bool);
210 
211  friend TransformState
213 
214 public:
215  const TransformOptions &getOptions() const { return options; }
216 
217  /// Returns the op at which the transformation state is rooted. This is
218  /// typically helpful for transformations that apply globally.
219  Operation *getTopLevel() const;
220 
221  /// Returns the number of extra mappings for the top-level operation.
222  size_t getNumTopLevelMappings() const { return topLevelMappedValues.size(); }
223 
224  /// Returns the position-th extra mapping for the top-level operation.
225  ArrayRef<MappedValue> getTopLevelMapping(size_t position) const {
226  return topLevelMappedValues[position];
227  }
228 
229  /// Returns an iterator that enumerates all ops that the given transform IR
230  /// value corresponds to. Ops may be erased while iterating; erased ops are
231  /// not enumerated. This function is helpful for transformations that apply to
232  /// a particular handle.
233  auto getPayloadOps(Value value) const {
234  ArrayRef<Operation *> view = getPayloadOpsView(value);
235 
236 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
237  // Memorize the current timestamp and make sure that it has not changed
238  // when incrementing or dereferencing the iterator returned by this
239  // function. The timestamp is incremented when the "direct" mapping is
240  // resized; this would invalidate the iterator returned by this function.
241  int64_t currentTimestamp = getMapping(value).timestamps.lookup(value);
242 #endif // LLVM_ENABLE_ABI_BREAKING_CHECKS
243 
244  // When ops are replaced/erased, they are replaced with nullptr (until
245  // the data structure is compacted). Do not enumerate these ops.
246  return llvm::make_filter_range(view, [=](Operation *op) {
247 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
248  [[maybe_unused]] bool sameTimestamp =
249  currentTimestamp == this->getMapping(value).timestamps.lookup(value);
250  assert(sameTimestamp && "iterator was invalidated during iteration");
251 #endif // LLVM_ENABLE_ABI_BREAKING_CHECKS
252  return op != nullptr;
253  });
254  }
255 
256  /// Returns the list of parameters that the given transform IR value
257  /// corresponds to.
258  ArrayRef<Attribute> getParams(Value value) const;
259 
260  /// Returns an iterator that enumerates all payload IR values that the given
261  /// transform IR value corresponds to.
262  auto getPayloadValues(Value handleValue) const {
263  ArrayRef<Value> view = getPayloadValuesView(handleValue);
264 
265 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
266  // Memorize the current timestamp and make sure that it has not changed
267  // when incrementing or dereferencing the iterator returned by this
268  // function. The timestamp is incremented when the "values" mapping is
269  // resized; this would invalidate the iterator returned by this function.
270  int64_t currentTimestamp =
271  getMapping(handleValue).timestamps.lookup(handleValue);
272  return llvm::make_filter_range(view, [=](Value v) {
273  [[maybe_unused]] bool sameTimestamp =
274  currentTimestamp ==
275  this->getMapping(handleValue).timestamps.lookup(handleValue);
276  assert(sameTimestamp && "iterator was invalidated during iteration");
277  return true;
278  });
279 #else
280  return llvm::make_range(view.begin(), view.end());
281 #endif // LLVM_ENABLE_ABI_BREAKING_CHECKS
282  }
283 
284  /// Populates `handles` with all handles pointing to the given Payload IR op.
285  /// Returns success if such handles exist, failure otherwise.
286  /// If `includeOutOfScope` is set to "true", handles that are defined in
287  /// regions beyond the most recent isolated from above region are included.
289  SmallVectorImpl<Value> &handles,
290  bool includeOutOfScope = false) const;
291 
292  /// Populates `handles` with all handles pointing to the given payload IR
293  /// value. Returns success if such handles exist, failure otherwise.
294  /// If `includeOutOfScope` is set to "true", handles that are defined in
295  /// regions beyond the most recent isolated from above region are included.
297  SmallVectorImpl<Value> &handles,
298  bool includeOutOfScope = false) const;
299 
300  /// Applies the transformation specified by the given transform op and updates
301  /// the state accordingly.
302  DiagnosedSilenceableFailure applyTransform(TransformOpInterface transform);
303 
304  /// Records the mapping between a block argument in the transform IR and a
305  /// list of operations in the payload IR. The arguments must be defined in
306  /// blocks of the currently processed transform IR region, typically after a
307  /// region scope is defined.
308  ///
309  /// Returns failure if the payload does not satisfy the conditions associated
310  /// with the type of the handle value.
312  ArrayRef<Operation *> operations) {
313 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
314  assert(argument.getParentRegion() == regionStack.back() &&
315  "mapping block arguments from a region other than the active one");
316 #endif // LLVM_ENABLE_ABI_BREAKING_CHECKS
317  return setPayloadOps(argument, operations);
318  }
320  ArrayRef<MappedValue> values);
321 
322  // Forward declarations to support limited visibility.
323  class RegionScope;
324 
325  /// Creates a new region scope for the given region. The region is expected to
326  /// be nested in the currently processed region.
327  // Implementation note: this method is inline but implemented outside of the
328  // class body to comply with visibility and full-declaration requirements.
329  inline RegionScope make_region_scope(Region &region);
330 
331  /// A RAII object maintaining a "stack frame" for a transform IR region. When
332  /// applying a transform IR operation that contains a region, the caller is
333  /// expected to create a RegionScope before applying the ops contained in the
334  /// region. This ensures that the mappings between values defined in the
335  /// transform IR region and payload IR operations are cleared when the region
336  /// processing ends; such values cannot be accessed outside the region.
337  class RegionScope {
338  public:
339  /// Forgets the mapping from or to values defined in the associated
340  /// transform IR region, and restores the mapping that existed before
341  /// entering this scope.
342  ~RegionScope();
343 
344  private:
345  /// Creates a new scope for mappings between values defined in the given
346  /// transform IR region and payload IR objects.
347  RegionScope(TransformState &state, Region &region)
348  : state(state), region(&region) {
349  auto res = state.mappings.insert(
350  std::make_pair(&region, std::make_unique<Mappings>()));
351  assert(res.second && "the region scope is already present");
352  (void)res;
353 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
354  state.regionStack.push_back(&region);
355 #endif // LLVM_ENABLE_ABI_BREAKING_CHECKS
356  }
357 
358  /// Back-reference to the transform state.
359  TransformState &state;
360 
361  /// The region this scope is associated with.
362  Region *region;
363 
365  };
366  friend class RegionScope;
367 
368  /// Base class for TransformState extensions that allow TransformState to
369  /// contain user-specified information in the state object. Clients are
370  /// expected to derive this class, add the desired fields, and make the
371  /// derived class compatible with the MLIR TypeID mechanism:
372  ///
373  /// ```mlir
374  /// class MyExtension final : public TransformState::Extension {
375  /// public:
376  /// MyExtension(TranfsormState &state, int myData)
377  /// : Extension(state) {...}
378  /// private:
379  /// int mySupplementaryData;
380  /// };
381  /// ```
382  ///
383  /// Instances of this and derived classes are not expected to be created by
384  /// the user, instead they are directly constructed within a TransformState. A
385  /// TransformState can only contain one extension with the given TypeID.
386  /// Extensions can be obtained from a TransformState instance, and can be
387  /// removed when they are no longer required.
388  ///
389  /// ```mlir
390  /// transformState.addExtension<MyExtension>(/*myData=*/42);
391  /// MyExtension *ext = transformState.getExtension<MyExtension>();
392  /// ext->doSomething();
393  /// ```
394  class Extension {
395  // Allow TransformState to allocate Extensions.
396  friend class TransformState;
397 
398  public:
399  /// Base virtual destructor.
400  // Out-of-line definition ensures symbols are emitted in a single object
401  // file.
402  virtual ~Extension();
403 
404  protected:
405  /// Constructs an extension of the given TransformState object.
406  Extension(TransformState &state) : state(state) {}
407 
408  /// Provides read-only access to the parent TransformState object.
409  const TransformState &getTransformState() const { return state; }
410 
411  /// Replaces the given payload op with another op. If the replacement op is
412  /// null, removes the association of the payload op with its handle. Returns
413  /// failure if the op is not associated with any handle.
414  ///
415  /// Note: This function does not update value handles. None of the original
416  /// op's results are allowed to be mapped to any value handle.
418 
419  /// Replaces the given payload value with another value. If the replacement
420  /// value is null, removes the association of the payload value with its
421  /// handle. Returns failure if the value is not associated with any handle.
422  LogicalResult replacePayloadValue(Value value, Value replacement);
423 
424  private:
425  /// Back-reference to the state that is being extended.
426  TransformState &state;
427  };
428 
429  /// Adds a new Extension of the type specified as template parameter,
430  /// constructing it with the arguments provided. The extension is owned by the
431  /// TransformState. It is expected that the state does not already have an
432  /// extension of the same type. Extension constructors are expected to take
433  /// a reference to TransformState as first argument, automatically supplied
434  /// by this call.
435  template <typename Ty, typename... Args>
436  Ty &addExtension(Args &&...args) {
437  static_assert(
438  std::is_base_of<Extension, Ty>::value,
439  "only an class derived from TransformState::Extension is allowed here");
440  auto ptr = std::make_unique<Ty>(*this, std::forward<Args>(args)...);
441  auto result = extensions.try_emplace(TypeID::get<Ty>(), std::move(ptr));
442  assert(result.second && "extension already added");
443  return *static_cast<Ty *>(result.first->second.get());
444  }
445 
446  /// Returns the extension of the specified type.
447  template <typename Ty>
448  Ty *getExtension() {
449  static_assert(
450  std::is_base_of<Extension, Ty>::value,
451  "only an class derived from TransformState::Extension is allowed here");
452  auto iter = extensions.find(TypeID::get<Ty>());
453  if (iter == extensions.end())
454  return nullptr;
455  return static_cast<Ty *>(iter->second.get());
456  }
457 
458  /// Removes the extension of the specified type.
459  template <typename Ty>
461  static_assert(
462  std::is_base_of<Extension, Ty>::value,
463  "only an class derived from TransformState::Extension is allowed here");
464  extensions.erase(TypeID::get<Ty>());
465  }
466 
467 private:
468  /// Identifier for storing top-level value in the `operations` mapping.
469  static constexpr Value kTopLevelValue = Value();
470 
471  /// Creates a state for transform ops living in the given region. The second
472  /// argument points to the root operation in the payload IR being transformed,
473  /// which may or may not contain the region with transform ops. Additional
474  /// options can be provided through the trailing configuration object.
475  TransformState(Region *region, Operation *payloadRoot,
476  const RaggedArray<MappedValue> &extraMappings = {},
477  const TransformOptions &options = TransformOptions());
478 
479  /// Returns the mappings frame for the region in which the value is defined.
480  /// If `allowOutOfScope` is set to "false", asserts that the value is in
481  /// scope, based on the current stack of frames.
482  const Mappings &getMapping(Value value, bool allowOutOfScope = false) const {
483  return const_cast<TransformState *>(this)->getMapping(value,
484  allowOutOfScope);
485  }
486  Mappings &getMapping(Value value, bool allowOutOfScope = false) {
487  Region *region = value.getParentRegion();
488  auto it = mappings.find(region);
489  assert(it != mappings.end() &&
490  "trying to find a mapping for a value from an unmapped region");
491 #ifndef NDEBUG
492  if (!allowOutOfScope) {
493  for (Region *r : llvm::reverse(llvm::make_first_range(mappings))) {
494  if (r == region)
495  break;
496  if (r->getParentOp()->hasTrait<OpTrait::IsIsolatedFromAbove>())
497  llvm_unreachable("trying to get mapping beyond region that is "
498  "isolated from above");
499  }
500  }
501 #endif // NDEBUG
502  return *it->second;
503  }
504 
505  /// Returns the mappings frame for the region in which the operation resides.
506  /// If `allowOutOfScope` is set to "false", asserts that the operation is in
507  /// scope, based on the current stack of frames.
508  const Mappings &getMapping(Operation *operation,
509  bool allowOutOfScope = false) const {
510  return const_cast<TransformState *>(this)->getMapping(operation,
511  allowOutOfScope);
512  }
513  Mappings &getMapping(Operation *operation, bool allowOutOfScope = false) {
514  Region *region = operation->getParentRegion();
515  auto it = mappings.find(region);
516  assert(it != mappings.end() &&
517  "trying to find a mapping for an operation from an unmapped region");
518 #ifndef NDEBUG
519  if (!allowOutOfScope) {
520  for (Region *r : llvm::reverse(llvm::make_first_range(mappings))) {
521  if (r == region)
522  break;
523  if (r->getParentOp()->hasTrait<OpTrait::IsIsolatedFromAbove>())
524  llvm_unreachable("trying to get mapping beyond region that is "
525  "isolated from above");
526  }
527  }
528 #endif // NDEBUG
529  return *it->second;
530  }
531 
532  /// Updates the state to include the associations between op results and the
533  /// provided result of applying a transform op.
534  LogicalResult updateStateFromResults(const TransformResults &results,
535  ResultRange opResults);
536 
537  /// Returns a list of all ops that the given transform IR value corresponds
538  /// to. In case an op was erased, the returned list contains nullptr. This
539  /// function is helpful for transformations that apply to a particular handle.
540  ArrayRef<Operation *> getPayloadOpsView(Value value) const;
541 
542  /// Returns a list of payload IR values that the given transform IR value
543  /// corresponds to.
544  ArrayRef<Value> getPayloadValuesView(Value handleValue) const;
545 
546  /// Sets the payload IR ops associated with the given transform IR value
547  /// (handle). A payload op may be associated multiple handles as long as
548  /// at most one of them gets consumed by further transformations.
549  /// For example, a hypothetical "find function by name" may be called twice in
550  /// a row to produce two handles pointing to the same function:
551  ///
552  /// %0 = transform.find_func_by_name { name = "myfunc" }
553  /// %1 = transform.find_func_by_name { name = "myfunc" }
554  ///
555  /// which is valid by itself. However, calling a hypothetical "rewrite and
556  /// rename function" transform on both handles:
557  ///
558  /// transform.rewrite_and_rename %0 { new_name = "func" }
559  /// transform.rewrite_and_rename %1 { new_name = "func" }
560  ///
561  /// is invalid given the transformation "consumes" the handle as expressed
562  /// by side effects. Practically, a transformation consuming a handle means
563  /// that the associated payload operation may no longer exist.
564  ///
565  /// Similarly, operation handles may be invalidate and should not be used
566  /// after a transform that consumed a value handle pointing to a payload value
567  /// defined by the operation as either block argument or op result. For
568  /// example, in the following sequence, the last transform operation rewrites
569  /// the callee to not return a specified result:
570  ///
571  /// %0 = transform.find_call "myfunc"
572  /// %1 = transform.find_results_of_calling "myfunc"
573  /// transform.drop_call_result_from_signature %1[0]
574  ///
575  /// which requires the call operations to be recreated. Therefore, the handle
576  /// %0 becomes associated with a dangling pointer and should not be used.
577  ///
578  /// Returns failure if the payload does not satisfy the conditions associated
579  /// with the type of the handle value. The value is expected to have a type
580  /// implementing TransformHandleTypeInterface.
581  LogicalResult setPayloadOps(Value value, ArrayRef<Operation *> targets);
582 
583  /// Sets the payload IR values association with the given transform IR value
584  /// (handle). A payload value may be associated with multiple handles as long
585  /// as at most one of them is consumed by further transformations. For
586  /// example, a hypothetical "get results of calls to function with the given
587  /// name" transform may be performed twice in a row producing handles pointing
588  /// to the same values:
589  ///
590  /// %0 = transform.find_results_of_calling "myfunc"
591  /// %1 = transform.find_results_of_calling "myfunc"
592  ///
593  /// which is valid by itself. However, calling a hypothetical "erase value
594  /// producer" transform on both handles:
595  ///
596  /// transform.erase_value_produce %0
597  /// transform.erase_value_produce %1
598  ///
599  /// is invalid provided the transformation "consumes" the handle as expressed
600  /// by side effects (which themselves reflect the semantics of the transform
601  /// erasing the producer and making the handle dangling). Practically, a
602  /// transformation consuming a handle means the associated payload value may
603  /// no longer exist.
604  ///
605  /// Similarly, value handles are invalidated and should not be used after a
606  /// transform that consumed an operation handle pointing to the payload IR
607  /// operation defining the values associated the value handle, as either block
608  /// arguments or op results, or any ancestor operation. For example,
609  ///
610  /// %0 = transform.find_call "myfunc"
611  /// %1 = transform.find_results_of_calling "myfunc"
612  /// transform.rewrite_and_rename %0 { new_name = "func" }
613  ///
614  /// makes %1 unusable after the last transformation if it consumes %0. When an
615  /// operation handle is consumed, it usually indicates that the operation was
616  /// destroyed or heavily modified, meaning that the values it defines may no
617  /// longer exist.
618  ///
619  /// Returns failure if the payload values do not satisfy the conditions
620  /// associated with the type of the handle value. The value is expected to
621  /// have a type implementing TransformValueHandleTypeInterface.
622  LogicalResult setPayloadValues(Value handle, ValueRange payloadValues);
623 
624  /// Sets the parameters associated with the given transform IR value. Returns
625  /// failure if the parameters do not satisfy the conditions associated with
626  /// the type of the value. The value is expected to have a type implementing
627  /// TransformParamTypeInterface.
628  LogicalResult setParams(Value value, ArrayRef<Param> params);
629 
630  /// Forgets the payload IR ops associated with the given transform IR value,
631  /// as well as any association between value handles and the results of said
632  /// payload IR op.
633  ///
634  /// If `allowOutOfScope` is set to "false", asserts that the handle is in
635  /// scope, based on the current stack of frames.
636  void forgetMapping(Value opHandle, ValueRange origOpFlatResults,
637  bool allowOutOfScope = false);
638 
639  void forgetValueMapping(Value valueHandle,
640  ArrayRef<Operation *> payloadOperations);
641 
642  /// Replaces the given payload op with another op. If the replacement op is
643  /// null, removes the association of the payload op with its handle. Returns
644  /// failure if the op is not associated with any handle.
645  ///
646  /// Note: This function does not update value handles. None of the original
647  /// op's results are allowed to be mapped to any value handle.
648  LogicalResult replacePayloadOp(Operation *op, Operation *replacement);
649 
650  /// Replaces the given payload value with another value. If the replacement
651  /// value is null, removes the association of the payload value with its
652  /// handle. Returns failure if the value is not associated with any handle.
653  LogicalResult replacePayloadValue(Value value, Value replacement);
654 
655  /// Records handle invalidation reporters into `newlyInvalidated`.
656  /// Specifically,
657  /// - `handle` is the op operand that consumes the handle,
658  /// - `potentialAncestors` is a list of ancestors of the payload operation
659  /// that the consumed handle is associated with, including itself,
660  /// - `throughValue` is the payload value the handle to which is consumed,
661  /// when it is the case, null when the operation handle is consumed
662  /// directly.
663  /// Iterates over all known operation and value handles and records reporters
664  /// for any potential future use of `handle` or any other handle that is
665  /// invalidated by its consumption, i.e., any handle pointing to any payload
666  /// IR entity (operation or value) associated with the same payload IR entity
667  /// as the consumed handle, or any nested payload IR entity. If
668  /// `potentialAncestors` is empty, records the reporter anyway. Does not
669  /// override existing reporters. This must remain a const method so it doesn't
670  /// inadvertently mutate `invalidatedHandles` too early.
671  void recordOpHandleInvalidation(OpOperand &consumingHandle,
672  ArrayRef<Operation *> potentialAncestors,
673  Value throughValue,
674  InvalidatedHandleMap &newlyInvalidated) const;
675 
676  /// Records handle invalidation reporters into `newlyInvalidated`.
677  /// Specifically,
678  /// - `consumingHandle` is the op operand that consumes the handle,
679  /// - `potentialAncestors` is a list of ancestors of the payload operation
680  /// that the consumed handle is associated with, including itself,
681  /// - `payloadOp` is the operation itself,
682  /// - `otherHandle` is another that may be associated with the affected
683  /// payload operations
684  /// - `throughValue` is the payload value the handle to which is consumed,
685  /// when it is the case, null when the operation handle is consumed
686  /// directly.
687  /// Looks at the payload opreations associated with `otherHandle` and if any
688  /// of these operations has an ancestor (or is itself) listed in
689  /// `potentialAncestors`, records the error message describing the use of the
690  /// invalidated handle. Does nothing if `otherHandle` already has a reporter
691  /// associated with it. This must remain a const method so it doesn't
692  /// inadvertently mutate `invalidatedHandles` too early.
693  void recordOpHandleInvalidationOne(
694  OpOperand &consumingHandle, ArrayRef<Operation *> potentialAncestors,
695  Operation *payloadOp, Value otherHandle, Value throughValue,
696  InvalidatedHandleMap &newlyInvalidated) const;
697 
698  /// Records handle invalidation reporters into `newlyInvalidated`.
699  /// Specifically,
700  /// - `opHandle` is the op operand that consumes the handle;
701  /// - `potentialAncestors` is a list of ancestors of the payload operation
702  /// that the consumed handle is associated with, including itself;
703  /// - `payloadValue` is the value defined by the operation associated with
704  /// the consuming handle as either op result or block argument;
705  /// - `valueHandle` is another that may be associated with the payload value.
706  /// Looks at the payload values associated with `valueHandle` and if any of
707  /// these values is defined, as op result or block argument, by an operation
708  /// whose ancestor (or the operation itself) is listed in
709  /// `potentialAncestors`, records the error message describing the use of the
710  /// invalidated handle. Does nothing if `valueHandle` already has a reporter
711  /// associated with it. This must remain a const method so it doesn't
712  /// inadvertently mutate `invalidatedHandles` too early.
713  void recordValueHandleInvalidationByOpHandleOne(
714  OpOperand &opHandle, ArrayRef<Operation *> potentialAncestors,
715  Value payloadValue, Value valueHandle,
716  InvalidatedHandleMap &newlyInvalidated) const;
717 
718  /// Records handle invalidation reporters into `newlyInvalidated`.
719  /// Specifically,
720  /// - `valueHandle` is the op operand that consumes the handle,
721  /// - `throughValue` is the payload value the handle to which is consumed,
722  /// when it is the case, null when the operation handle is consumed
723  /// directly.
724  /// Iterates over all known operation and value handles and records reporters
725  /// for any potential future use of `handle` or any other handle that is
726  /// invalidated by its consumption, i.e., any handle pointing to any payload
727  /// IR entity (operation or value) associated with the same payload IR entity
728  /// as the consumed handle, or any nested payload IR entity. Does not override
729  /// existing reporters. This must remain a const method so it doesn't
730  /// inadvertently mutate `invalidatedHandles` too early.
731  void
732  recordValueHandleInvalidation(OpOperand &valueHandle,
733  InvalidatedHandleMap &newlyInvalidated) const;
734 
735  /// Checks that the operation does not use invalidated handles as operands.
736  /// Reports errors and returns failure if it does. Otherwise, invalidates the
737  /// handles consumed by the operation as well as any handles pointing to
738  /// payload IR operations nested in the operations associated with the
739  /// consumed handles.
740  LogicalResult
741  checkAndRecordHandleInvalidation(TransformOpInterface transform);
742 
743  /// Implementation of the checkAndRecordHandleInvalidation. This must remain a
744  /// const method so it doesn't inadvertently mutate `invalidatedHandles` too
745  /// early.
746  LogicalResult checkAndRecordHandleInvalidationImpl(
747  transform::TransformOpInterface transform,
748  transform::TransformState::InvalidatedHandleMap &newlyInvalidated) const;
749 
750  /// Remove all nullptrs from op handles that were added by `replacePayloadOp`.
751  void compactOpHandles();
752 
753  /// A stack of mappings between transform IR values and payload IR ops,
754  /// aggregated by the region in which the transform IR values are defined.
755  /// We use a pointer to the Mappings struct so that reallocations inside
756  /// MapVector don't invalidate iterators when we apply nested transform ops
757  /// while also iterating over the mappings.
758  llvm::MapVector<Region *, std::unique_ptr<Mappings>> mappings;
759 
760  /// Op handles may be temporarily mapped to nullptr to avoid invalidating
761  /// payload op iterators. This set contains all op handles with nullptrs.
762  /// These handles are "compacted" (i.e., nullptrs removed) at the end of each
763  /// transform.
764  DenseSet<Value> opHandlesToCompact;
765 
766  /// Extensions attached to the TransformState, identified by the TypeID of
767  /// their type. Only one extension of any given type is allowed.
768  DenseMap<TypeID, std::unique_ptr<Extension>> extensions;
769 
770  /// The top-level operation that contains all payload IR, typically a module.
771  Operation *topLevel;
772 
773  /// Extra mapped values (payload operations, values or parameters) to be
774  /// associated with additional entry block arguments of the top-level
775  /// transform operation.
776  RaggedArray<MappedValue> topLevelMappedValues;
777 
778  /// Additional options controlling the transformation state behavior.
779  TransformOptions options;
780 
781  /// The mapping from invalidated handles to the error-reporting functions that
782  /// describe when the handles were invalidated. Calling such a function emits
783  /// a user-visible diagnostic with an additional note pointing to the given
784  /// location.
785  InvalidatedHandleMap invalidatedHandles;
786 
787 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
788  /// A stack of nested regions that are being processed in the transform IR.
789  /// Each region must be an ancestor of the following regions in this list.
790  /// These are also the keys for "mappings".
791  SmallVector<Region *> regionStack;
792 #endif // LLVM_ENABLE_ABI_BREAKING_CHECKS
793 };
794 
795 /// Local mapping between values defined by a specific op implementing the
796 /// TransformOpInterface and the payload IR ops they correspond to.
798  friend class TransformState;
799 
800 public:
801  /// Indicates that the result of the transform IR op at the given position
802  /// corresponds to the given list of payload IR ops. Each result must be set
803  /// by the transformation exactly once in case of transformation succeeding.
804  /// The value must have a type implementing TransformHandleTypeInterface.
805  template <typename Range>
806  void set(OpResult value, Range &&ops) {
807  int64_t position = value.getResultNumber();
808  assert(position < static_cast<int64_t>(operations.size()) &&
809  "setting results for a non-existent handle");
810  assert(operations[position].data() == nullptr && "results already set");
811  assert(params[position].data() == nullptr &&
812  "another kind of results already set");
813  assert(values[position].data() == nullptr &&
814  "another kind of results already set");
815  operations.replace(position, std::forward<Range>(ops));
816  }
817 
818  /// Indicates that the result of the transform IR op at the given position
819  /// corresponds to the given list of payload IR ops. Each result must be set
820  /// by the transformation exactly once in case of transformation succeeding.
821  /// The value must have a type implementing TransformHandleTypeInterface.
822  void set(OpResult value, std::initializer_list<Operation *> ops) {
823  set(value, ArrayRef<Operation *>(ops));
824  }
825 
826  /// Indicates that the result of the transform IR op at the given position
827  /// corresponds to the given list of parameters. Each result must be set by
828  /// the transformation exactly once in case of transformation succeeding. The
829  /// value must have a type implementing TransformParamTypeInterface.
831 
832  /// Indicates that the result of the transform IR op at the given position
833  /// corresponds to the given range of payload IR values. Each result must be
834  /// set by the transformation exactly once in case of transformation
835  /// succeeding. The value must have a type implementing
836  /// TransformValueHandleTypeInterface.
837  template <typename Range>
838  void setValues(OpResult handle, Range &&values) {
839  int64_t position = handle.getResultNumber();
840  assert(position < static_cast<int64_t>(this->values.size()) &&
841  "setting values for a non-existent handle");
842  assert(this->values[position].data() == nullptr && "values already set");
843  assert(operations[position].data() == nullptr &&
844  "another kind of results already set");
845  assert(params[position].data() == nullptr &&
846  "another kind of results already set");
847  this->values.replace(position, std::forward<Range>(values));
848  }
849 
850  /// Indicates that the result of the transform IR op at the given position
851  /// corresponds to the given range of payload IR values. Each result must be
852  /// set by the transformation exactly once in case of transformation
853  /// succeeding. The value must have a type implementing
854  /// TransformValueHandleTypeInterface.
855  void setValues(OpResult handle, std::initializer_list<Value> values) {
856  setValues(handle, ArrayRef<Value>(values));
857  }
858 
859  /// Indicates that the result of the transform IR op at the given position
860  /// corresponds to the given range of mapped values. All mapped values are
861  /// expected to be compatible with the type of the result, e.g., if the result
862  /// is an operation handle, all mapped values are expected to be payload
863  /// operations.
864  void setMappedValues(OpResult handle, ArrayRef<MappedValue> values);
865 
866  /// Sets the currently unset results to empty lists of the kind expected by
867  /// the corresponding results of the given `transform` op.
868  void setRemainingToEmpty(TransformOpInterface transform);
869 
870 private:
871  /// Creates an instance of TransformResults that expects mappings for
872  /// `numSegments` values, which may be associated with payload operations or
873  /// parameters.
874  explicit TransformResults(unsigned numSegments);
875 
876  /// Gets the list of operations associated with the result identified by its
877  /// number in the list of operation results. The result must have been set to
878  /// be associated with payload IR operations.
879  ArrayRef<Operation *> get(unsigned resultNumber) const;
880 
881  /// Gets the list of parameters associated with the result identified by its
882  /// number in the list of operation results. The result must have been set to
883  /// be associated with parameters.
884  ArrayRef<TransformState::Param> getParams(unsigned resultNumber) const;
885 
886  /// Gets the list of payload IR values associated with the result identified
887  /// by its number in the list of operation results. The result must have been
888  /// set to be associated with payload IR values.
889  ArrayRef<Value> getValues(unsigned resultNumber) const;
890 
891  /// Returns `true` if the result identified by its number in the list of
892  /// operation results is associated with a list of parameters, `false`
893  /// otherwise.
894  bool isParam(unsigned resultNumber) const;
895 
896  /// Returns `true` if the result identified by its number in the list of
897  /// operation results is associated with a list of payload IR value, `false`
898  /// otherwise.
899  bool isValue(unsigned resultNumber) const;
900 
901  /// Returns `true` if the result identified by its number in the list of
902  /// operation results is associated with something.
903  bool isSet(unsigned resultNumber) const;
904 
905  /// Pointers to payload IR ops that are associated with results of a transform
906  /// IR op.
907  RaggedArray<Operation *> operations;
908 
909  /// Parameters that are associated with results of the transform IR op.
910  RaggedArray<Param> params;
911 
912  /// Payload IR values that are associated with results of a transform IR op.
913  RaggedArray<Value> values;
914 };
915 
916 /// Creates a RAII object the lifetime of which corresponds to the new mapping
917 /// for transform IR values defined in the given region. Values defined in
918 /// surrounding regions remain accessible.
920  return RegionScope(*this, region);
921 }
922 
923 /// A listener that updates a TransformState based on IR modifications. This
924 /// listener can be used during a greedy pattern rewrite to keep the transform
925 /// state up-to-date.
928 public:
929  /// Create a new TrackingListener for usage in the specified transform op.
930  TrackingListener(TransformState &state, TransformOpInterface op);
931 
932 protected:
933  /// Return a replacement payload op for the given op, which is going to be
934  /// replaced with the given values. By default, if all values are defined by
935  /// the same op, which also has the same type as the given op, that defining
936  /// op is used as a replacement.
937  ///
938  /// A "failure" return value indicates that no replacement operation could be
939  /// found. A "nullptr" return value indicates that no replacement op is needed
940  /// (e.g., handle is dead or was consumed) and that the payload op should
941  /// be dropped from the mapping.
942  ///
943  /// Example: A tracked "linalg.generic" with two results is replaced with two
944  /// values defined by (another) "linalg.generic". It is reasonable to assume
945  /// that the replacement "linalg.generic" represents the same "computation".
946  /// Therefore, the payload op mapping is updated to the defining op of the
947  /// replacement values.
948  ///
949  /// Counter Example: A "linalg.generic" is replaced with values defined by an
950  /// "scf.for". Without further investigation, the relationship between the
951  /// "linalg.generic" and the "scf.for" is unclear. They may not represent the
952  /// same computation; e.g., there may be tiled "linalg.generic" inside the
953  /// loop body that represents the original computation. Therefore, the
954  /// TrackingListener is conservative by default: it drops the mapping and
955  /// triggers the "payload replacement not found" notification.
956  ///
957  /// If no replacement op could be found according to the rules mentioned
958  /// above, this function tries to skip over cast-like ops that implement
959  /// `CastOpInterface`.
960  ///
961  /// Example: A tracked "linalg.generic" is replaced with "linalg.generic",
962  /// wrapped in a "tensor.cast". A cast is a metadata-only operation and it is
963  /// reasonable to assume that the wrapped "linalg.generic" represents the same
964  /// computation as the original "linalg.generic". The mapping is updated
965  /// accordingly.
966  ///
967  /// Certain ops (typically also metadata-only ops) are not considered casts,
968  /// but should be skipped nonetheless. Such ops should implement
969  /// `FindPayloadReplacementOpInterface` to specify with which operands the
970  /// lookup should continue.
971  ///
972  /// Example: A tracked "linalg.generic" is replaced with "linalg.generic",
973  /// wrapped in a "tensor.reshape". A reshape is a metadata-only operation but
974  /// not cast. (Implementing `CastOpInterface` would be incorrect and cause
975  /// invalid foldings.) However, due to its `FindPayloadReplacementOpInterface`
976  /// implementation, the replacement op lookup continues with the wrapped
977  /// "linalg.generic" and the mapping is updated accordingly.
978  ///
979  /// Derived classes may override `findReplacementOp` to specify custom
980  /// replacement rules.
982  findReplacementOp(Operation *&result, Operation *op,
983  ValueRange newValues) const;
984 
985  /// Notify the listener that the pattern failed to match the given operation,
986  /// and provide a callback to populate a diagnostic with the reason why the
987  /// failure occurred.
990  function_ref<void(Diagnostic &)> reasonCallback) override;
991 
992  /// This function is called when a tracked payload op is dropped because no
993  /// replacement op was found. Derived classes can implement this function for
994  /// custom error handling.
995  virtual void
998 
999  /// Return the single op that defines all given values (if any).
1000  static Operation *getCommonDefiningOp(ValueRange values);
1001 
1002  /// Return the transform op in which this TrackingListener is used.
1003  TransformOpInterface getTransformOp() const { return transformOp; }
1004 
1005 private:
1006  friend class TransformRewriter;
1007 
1008  void notifyOperationRemoved(Operation *op) override;
1009 
1010  void notifyOperationReplaced(Operation *op, ValueRange newValues) override;
1011  using Listener::notifyOperationReplaced;
1012 
1013  /// The transform op in which this TrackingListener is used.
1014  TransformOpInterface transformOp;
1015 
1016  /// The handles that are consumed by the transform op.
1017  DenseSet<Value> consumedHandles;
1018 };
1019 
1020 /// A specialized listener that keeps track of cases in which no replacement
1021 /// payload could be found. The error state of this listener must be checked
1022 /// before the end of its lifetime.
1024 public:
1026 
1027  ~ErrorCheckingTrackingListener() override;
1028 
1029  /// Check and return the current error state of this listener. Afterwards,
1030  /// resets the error state to "success".
1032 
1033  /// Return "true" if this tracking listener had a failure.
1034  bool failed() const;
1035 
1036 protected:
1037  void
1039  DiagnosedSilenceableFailure &&diag) override;
1040 
1041 private:
1042  /// The error state of this listener. "Success" indicates that no error
1043  /// happened so far.
1045 
1046  /// The number of errors that have been encountered.
1047  int64_t errorCounter = 0;
1048 };
1049 
1050 /// This is a special rewriter to be used in transform op implementations,
1051 /// providing additional helper functions to update the transform state, etc.
1052 // TODO: Helper functions will be added in a subsequent change.
1054 protected:
1055  friend class TransformState;
1056 
1057  /// Create a new TransformRewriter.
1058  explicit TransformRewriter(MLIRContext *ctx,
1059  ErrorCheckingTrackingListener *listener);
1060 
1061 public:
1062  /// Return "true" if the tracking listener had failures.
1063  bool hasTrackingFailures() const;
1064 
1065  /// Silence all tracking failures that have been encountered so far.
1066  void silenceTrackingFailure();
1067 
1068  /// Notify the transform dialect interpreter that the given op has been
1069  /// replaced with another op and that the mapping between handles and payload
1070  /// ops/values should be updated. This function should be called before the
1071  /// original op is erased. It fails if the operation could not be replaced,
1072  /// e.g., because the original operation is not tracked.
1073  ///
1074  /// Note: As long as IR modifications are performed through this rewriter,
1075  /// the transform state is usually updated automatically. This function should
1076  /// be used when unsupported rewriter API is used; e.g., updating all uses of
1077  /// a tracked operation one-by-one instead of using `RewriterBase::replaceOp`.
1079  Operation *replacement);
1080 
1081 private:
1082  ErrorCheckingTrackingListener *const listener;
1083 };
1084 
1085 /// This trait is supposed to be attached to Transform dialect operations that
1086 /// can be standalone top-level transforms. Such operations typically contain
1087 /// other Transform dialect operations that can be executed following some
1088 /// control flow logic specific to the current operation. The operations with
1089 /// this trait are expected to have at least one single-block region with at
1090 /// least one argument of type implementing TransformHandleTypeInterface. The
1091 /// operations are also expected to be valid without operands, in which case
1092 /// they are considered top-level, and with one or more arguments, in which case
1093 /// they are considered nested. Top-level operations have the block argument of
1094 /// the entry block in the Transform IR correspond to the root operation of
1095 /// Payload IR. Nested operations have the block argument of the entry block in
1096 /// the Transform IR correspond to a list of Payload IR operations mapped to the
1097 /// first operand of the Transform IR operation. The operation must implement
1098 /// TransformOpInterface.
1099 template <typename OpTy>
1101  : public OpTrait::TraitBase<OpTy, PossibleTopLevelTransformOpTrait> {
1102 public:
1103  /// Verifies that `op` satisfies the invariants of this trait. Not expected to
1104  /// be called directly.
1107  }
1108 
1109  /// Returns the single block of the given region.
1110  Block *getBodyBlock(unsigned region = 0) {
1111  return &this->getOperation()->getRegion(region).front();
1112  }
1113 
1114  /// Populates `effects` with side effects implied by this trait.
1118  this->getOperation(), cast<OpTy>(this->getOperation()).getRoot(),
1119  *getBodyBlock(), effects);
1120  }
1121 
1122  /// Sets up the mapping between the entry block of the given region of this op
1123  /// and the relevant list of Payload IR operations in the given state. The
1124  /// state is expected to be already scoped at the region of this operation.
1126  assert(region.getParentOp() == this->getOperation() &&
1127  "op comes from the wrong region");
1129  state, this->getOperation(), region);
1130  }
1132  assert(
1133  this->getOperation()->getNumRegions() == 1 &&
1134  "must indicate the region to map if the operation has more than one");
1135  return mapBlockArguments(state, this->getOperation()->getRegion(0));
1136  }
1137 };
1138 
1139 class ApplyToEachResultList;
1140 
1141 /// Trait implementing the TransformOpInterface for operations applying a
1142 /// transformation to a single operation handle and producing an arbitrary
1143 /// number of handles and parameter values.
1144 /// The op must implement a method with the following signature:
1145 /// - DiagnosedSilenceableFailure applyToOne(OpTy,
1146 /// ApplyToEachResultList &results, TransformState &state)
1147 /// to perform a transformation that is applied in turn to all payload IR
1148 /// operations that correspond to the handle of the transform IR operation.
1149 /// In `applyToOne`, OpTy is either Operation* or a concrete payload IR Op class
1150 /// that the transformation is applied to (and NOT the class of the transform IR
1151 /// op).
1152 /// The `applyToOne` method takes an empty `results` vector that it fills with
1153 /// zero, one or multiple operations depending on the number of results expected
1154 /// by the transform op.
1155 /// The number of results must match the number of results of the transform op.
1156 /// `applyToOne` is allowed to fill the `results` with all null elements to
1157 /// signify that the transformation did not apply to the payload IR operations.
1158 /// Such null elements are filtered out from results before return.
1159 ///
1160 /// The transform op having this trait is expected to have a single operand.
1161 template <typename OpTy>
1163  : public OpTrait::TraitBase<OpTy, TransformEachOpTrait> {
1164 public:
1165  /// Calls `applyToOne` for every payload operation associated with the operand
1166  /// of this transform IR op, the following case disjunction happens:
1167  /// 1. If not target payload ops are associated to the operand then fill the
1168  /// results vector with the expected number of null elements and return
1169  /// success. This is the corner case handling that allows propagating
1170  /// the "no-op" case gracefully to improve usability.
1171  /// 2. If any `applyToOne` returns definiteFailure, the transformation is
1172  /// immediately considered definitely failed and we return.
1173  /// 3. All applications of `applyToOne` are checked to return a number of
1174  /// results expected by the transform IR op. If not, this is a definite
1175  /// failure and we return early.
1176  /// 4. If `applyToOne` produces ops, associate them with the result of this
1177  /// transform op.
1178  /// 5. If any `applyToOne` return silenceableFailure, the transformation is
1179  /// considered silenceable.
1180  /// 6. Otherwise the transformation is considered successful.
1182  TransformResults &transformResults,
1183  TransformState &state);
1184 
1185  /// Checks that the op matches the expectations of this trait.
1186  static LogicalResult verifyTrait(Operation *op);
1187 };
1188 
1189 /// Side effect resource corresponding to the mapping between Transform IR
1190 /// values and Payload IR operations. An Allocate effect from this resource
1191 /// means creating a new mapping entry, it is always accompanied by a Write
1192 /// effect. A Read effect from this resource means accessing the mapping. A Free
1193 /// effect on this resource indicates the removal of the mapping entry,
1194 /// typically after a transformation that modifies the Payload IR operations
1195 /// associated with one of the Transform IR operation's operands. It is always
1196 /// accompanied by a Read effect. Read-after-Free and double-Free are not
1197 /// allowed (they would be problematic with "regular" memory effects too) as
1198 /// they indicate an attempt to access Payload IR operations that have been
1199 /// modified, potentially erased, by the previous transformations.
1200 // TODO: consider custom effects if these are not enabling generic passes such
1201 // as CSE/DCE to work.
1203  : public SideEffects::Resource::Base<TransformMappingResource> {
1204  StringRef getName() override { return "transform.mapping"; }
1205 };
1206 
1207 /// Side effect resource corresponding to the Payload IR itself. Only Read and
1208 /// Write effects are expected on this resource, with Write always accompanied
1209 /// by a Read (short of fully replacing the top-level Payload IR operation, one
1210 /// cannot modify the Payload IR without reading it first). This is intended
1211 /// to disallow reordering of Transform IR operations that mutate the Payload IR
1212 /// while still allowing the reordering of those that only access it.
1214  : public SideEffects::Resource::Base<PayloadIRResource> {
1215  StringRef getName() override { return "transform.payload_ir"; }
1216 };
1217 
1218 /// Populates `effects` with the memory effects indicating the operation on the
1219 /// given handle value:
1220 /// - consumes = Read + Free,
1221 /// - produces = Allocate + Write,
1222 /// - onlyReads = Read.
1223 void consumesHandle(ValueRange handles,
1225 void producesHandle(ValueRange handles,
1227 void onlyReadsHandle(ValueRange handles,
1229 
1230 /// Checks whether the transform op consumes the given handle.
1231 bool isHandleConsumed(Value handle, transform::TransformOpInterface transform);
1232 
1233 /// Populates `effects` with the memory effects indicating the access to payload
1234 /// IR resource.
1237 
1238 /// Checks whether the transform op modifies the payload.
1239 bool doesModifyPayload(transform::TransformOpInterface transform);
1240 /// Checks whether the transform op reads the payload.
1241 bool doesReadPayload(transform::TransformOpInterface transform);
1242 
1243 /// Populates `consumedArguments` with positions of `block` arguments that are
1244 /// consumed by the operations in the `block`.
1246  Block &block, llvm::SmallDenseSet<unsigned> &consumedArguments);
1247 
1248 /// Trait implementing the MemoryEffectOpInterface for operations that "consume"
1249 /// their operands and produce new results.
1250 template <typename OpTy>
1252  : public OpTrait::TraitBase<OpTy, FunctionalStyleTransformOpTrait> {
1253 public:
1254  /// This op "consumes" the operands by reading and freeing then, "produces"
1255  /// the results by allocating and writing it and reads/writes the payload IR
1256  /// in the process.
1258  consumesHandle(this->getOperation()->getOperands(), effects);
1259  producesHandle(this->getOperation()->getResults(), effects);
1260  modifiesPayload(effects);
1261  }
1262 
1263  /// Checks that the op matches the expectations of this trait.
1265  if (!op->getName().getInterface<MemoryEffectOpInterface>()) {
1266  op->emitError()
1267  << "FunctionalStyleTransformOpTrait should only be attached to ops "
1268  "that implement MemoryEffectOpInterface";
1269  }
1270  return success();
1271  }
1272 };
1273 
1274 /// Trait implementing the MemoryEffectOpInterface for single-operand
1275 /// single-result operations that use their operand without consuming and
1276 /// without modifying the Payload IR to produce a new handle.
1277 template <typename OpTy>
1279  : public OpTrait::TraitBase<OpTy, NavigationTransformOpTrait> {
1280 public:
1281  /// This op produces handles to the Payload IR without consuming the original
1282  /// handles and without modifying the IR itself.
1284  onlyReadsHandle(this->getOperation()->getOperands(), effects);
1285  producesHandle(this->getOperation()->getResults(), effects);
1286  onlyReadsPayload(effects);
1287  }
1288 
1289  /// Checks that the op matches the expectation of this trait.
1291  static_assert(OpTy::template hasTrait<OpTrait::OneOperand>(),
1292  "expected single-operand op");
1293  static_assert(OpTy::template hasTrait<OpTrait::OneResult>(),
1294  "expected single-result op");
1295  if (!op->getName().getInterface<MemoryEffectOpInterface>()) {
1296  op->emitError() << "NavigationTransformOpTrait should only be attached "
1297  "to ops that implement MemoryEffectOpInterface";
1298  }
1299  return success();
1300  }
1301 };
1302 
1303 namespace detail {
1304 /// Non-template implementation of ParamProducerTransformOpTrait::getEffects().
1307 /// Non-template implementation of ParamProducerTransformOpTrait::verify().
1309 } // namespace detail
1310 
1311 /// Trait implementing the MemoryEffectsOpInterface for operations that produce
1312 /// transform dialect parameters. It marks all op results of
1313 /// TransformHandleTypeInterface as produced by the op, all operands as only
1314 /// read by the op and, if at least one of the operand is a handle to payload
1315 /// ops, the entire payload as potentially read. The op must only produce
1316 /// parameter-typed results.
1317 template <typename OpTy>
1319  : public OpTrait::TraitBase<OpTy, ParamProducerTransformOpTrait> {
1320 public:
1321  /// Populates `effects` with effect instances described in the trait
1322  /// documentation.
1325  effects);
1326  }
1327 
1328  /// Checks that the op matches the expectation of this trait, i.e., that it
1329  /// implements the MemoryEffectsOpInterface and only produces parameter-typed
1330  /// results.
1333  }
1334 };
1335 
1336 /// `TrackingListener` failures are reported only for ops that have this trait.
1337 /// The purpose of this trait is to give users more time to update their custom
1338 /// transform ops to use the provided `TransformRewriter` for all IR
1339 /// modifications. This trait will eventually be removed, and failures will be
1340 /// reported for all transform ops.
1341 template <typename OpTy>
1343  : public OpTrait::TraitBase<OpTy, ReportTrackingListenerFailuresOpTrait> {};
1344 
1345 /// A single result of applying a transform op with `ApplyEachOpTrait` to a
1346 /// single payload operation.
1348 
1349 /// A list of results of applying a transform op with `ApplyEachOpTrait` to a
1350 /// single payload operation, co-indexed with the results of the transform op.
1352 public:
1354  explicit ApplyToEachResultList(unsigned size) : results(size) {}
1355 
1356  /// Sets the list of results to `size` null pointers.
1357  void assign(unsigned size, std::nullptr_t) { results.assign(size, nullptr); }
1358 
1359  /// Sets the list of results to the given range of values.
1360  template <typename Range>
1361  void assign(Range &&range) {
1362  // This is roughly the implementation of SmallVectorImpl::assign.
1363  // Dispatching to it with map_range and template type inference would result
1364  // in more complex code here.
1365  results.clear();
1366  results.reserve(llvm::size(range));
1367  for (auto element : range) {
1368  if constexpr (std::is_convertible_v<decltype(*std::begin(range)),
1369  Operation *>) {
1370  results.push_back(static_cast<Operation *>(element));
1371  } else if constexpr (std::is_convertible_v<decltype(*std::begin(range)),
1372  Value>) {
1373  results.push_back(element.template get<Value>());
1374  } else {
1375  results.push_back(static_cast<Attribute>(element));
1376  }
1377  }
1378  }
1379 
1380  /// Appends an element to the list.
1381  // Using ApplyToEachResult that can be implicitly constructed from a Value but
1382  // not from a concrete Op that is implicitly convertible to a Value to avoid
1383  // ambiguity.
1384  void push_back(Operation *op) { results.push_back(op); }
1385  void push_back(Attribute attr) { results.push_back(attr); }
1386  void push_back(ApplyToEachResult r) { results.push_back(r); }
1387 
1388  /// Reserves space for `size` elements in the list.
1389  void reserve(unsigned size) { results.reserve(size); }
1390 
1391  /// Iterators over the list.
1392  auto begin() { return results.begin(); }
1393  auto end() { return results.end(); }
1394  auto begin() const { return results.begin(); }
1395  auto end() const { return results.end(); }
1396 
1397  /// Returns the number of elements in the list.
1398  size_t size() const { return results.size(); }
1399 
1400  /// Element access. Expects the index to be in bounds.
1401  ApplyToEachResult &operator[](size_t index) { return results[index]; }
1402  const ApplyToEachResult &operator[](size_t index) const {
1403  return results[index];
1404  }
1405 
1406 private:
1407  /// Underlying storage.
1409 };
1410 
1411 namespace detail {
1412 
1413 /// Check that the contents of `partialResult` matches the number, kind (payload
1414 /// op or parameter) and nullity (either all or none) requirements of
1415 /// `transformOp`. Report errors and return failure otherwise.
1416 LogicalResult checkApplyToOne(Operation *transformOp, Location payloadOpLoc,
1417  const ApplyToEachResultList &partialResult);
1418 
1419 /// "Transpose" the results produced by individual applications, arranging them
1420 /// per result value of the transform op, and populate `transformResults` with
1421 /// that. The number, kind and nullity of per-application results are assumed to
1422 /// have been verified.
1423 void setApplyToOneResults(Operation *transformOp,
1424  TransformResults &transformResults,
1426 
1427 /// Applies a one-to-one or a one-to-many transform to each of the given
1428 /// targets. Puts the results of transforms, if any, in `results` in the same
1429 /// order. Fails if any of the application fails. Individual transforms must be
1430 /// callable with the following signature:
1431 /// - DiagnosedSilenceableFailure(OpTy,
1432 /// SmallVector<Operation*> &results, state)
1433 /// where OpTy is either
1434 /// - Operation *, in which case the transform is always applied;
1435 /// - a concrete Op class, in which case a check is performed whether
1436 /// `targets` contains operations of the same class and a silenceable failure
1437 /// is reported if it does not.
1438 template <typename TransformOpTy, typename Range>
1440  TransformOpTy transformOp, TransformRewriter &rewriter, Range &&targets,
1442  using OpTy = typename llvm::function_traits<
1443  decltype(&TransformOpTy::applyToOne)>::template arg_t<1>;
1444  static_assert(std::is_convertible<OpTy, Operation *>::value,
1445  "expected transform function to take an operation");
1446  OpBuilder::InsertionGuard g(rewriter);
1447 
1448  SmallVector<Diagnostic> silenceableStack;
1449  unsigned expectedNumResults = transformOp->getNumResults();
1450  for (Operation *target : targets) {
1451  auto specificOp = dyn_cast<OpTy>(target);
1452  if (!specificOp) {
1453  Diagnostic diag(transformOp->getLoc(), DiagnosticSeverity::Error);
1454  diag << "transform applied to the wrong op kind";
1455  diag.attachNote(target->getLoc()) << "when applied to this op";
1456  silenceableStack.push_back(std::move(diag));
1457  continue;
1458  }
1459 
1460  ApplyToEachResultList partialResults;
1461  partialResults.reserve(expectedNumResults);
1462  Location specificOpLoc = specificOp->getLoc();
1463  rewriter.setInsertionPoint(specificOp);
1465  transformOp.applyToOne(rewriter, specificOp, partialResults, state);
1466  if (res.isDefiniteFailure())
1468 
1469  if (res.isSilenceableFailure()) {
1470  res.takeDiagnostics(silenceableStack);
1471  continue;
1472  }
1473 
1474  if (failed(detail::checkApplyToOne(transformOp, specificOpLoc,
1475  partialResults))) {
1477  }
1478  results.push_back(std::move(partialResults));
1479  }
1480  if (!silenceableStack.empty()) {
1482  std::move(silenceableStack));
1483  }
1485 }
1486 
1487 /// Reports an error and returns failure if `targets` contains an ancestor
1488 /// operation before its descendant (or a copy of itself). Implementation detail
1489 /// for expensive checks during `TransformEachOpTrait::apply`.
1491  ArrayRef<Operation *> targets);
1492 
1493 } // namespace detail
1494 } // namespace transform
1495 } // namespace mlir
1496 
1497 template <typename OpTy>
1500  TransformRewriter &rewriter, TransformResults &transformResults,
1501  TransformState &state) {
1502  Value handle = this->getOperation()->getOperand(0);
1503  auto targets = state.getPayloadOps(handle);
1504 
1505  // If the operand is consumed, check if it is associated with operations that
1506  // may be erased before their nested operations are.
1507  if (state.getOptions().getExpensiveChecksEnabled() &&
1508  isHandleConsumed(handle, cast<transform::TransformOpInterface>(
1509  this->getOperation())) &&
1510  failed(detail::checkNestedConsumption(this->getOperation()->getLoc(),
1511  llvm::to_vector(targets)))) {
1512  return DiagnosedSilenceableFailure::definiteFailure();
1513  }
1514 
1515  // Step 1. Handle the corner case where no target is specified.
1516  // This is typically the case when the matcher fails to apply and we need to
1517  // propagate gracefully.
1518  // In this case, we fill all results with an empty vector.
1519  if (std::empty(targets)) {
1520  SmallVector<Operation *> emptyPayload;
1521  SmallVector<Attribute> emptyParams;
1522  for (OpResult r : this->getOperation()->getResults()) {
1523  if (isa<TransformParamTypeInterface>(r.getType()))
1524  transformResults.setParams(r, emptyParams);
1525  else if (isa<TransformValueHandleTypeInterface>(r.getType()))
1526  transformResults.setValues(r, ValueRange());
1527  else
1528  transformResults.set(r, emptyPayload);
1529  }
1531  }
1532 
1533  // Step 2. Call applyToOne on each target and record newly produced ops in its
1534  // corresponding results entry.
1537  cast<OpTy>(this->getOperation()), rewriter, targets, results, state);
1538 
1539  // Step 3. Propagate the definite failure if any and bail out.
1540  if (result.isDefiniteFailure())
1541  return result;
1542 
1543  // Step 4. "Transpose" the results produced by individual applications,
1544  // arranging them per result value of the transform op. The number, kind and
1545  // nullity of per-application results have been verified by the callback
1546  // above.
1547  detail::setApplyToOneResults(this->getOperation(), transformResults, results);
1548 
1549  // Step 5. ApplyToOne may have returned silenceableFailure, propagate it.
1550  return result;
1551 }
1552 
1553 template <typename OpTy>
1556  static_assert(OpTy::template hasTrait<OpTrait::OneOperand>(),
1557  "expected single-operand op");
1558  if (!op->getName().getInterface<TransformOpInterface>()) {
1559  return op->emitError() << "TransformEachOpTrait should only be attached to "
1560  "ops that implement TransformOpInterface";
1561  }
1562 
1563  return success();
1564 }
1565 
1566 #endif // DIALECT_TRANSFORM_IR_TRANSFORMINTERFACES_H
static std::string diag(const llvm::Value &value)
static llvm::ManagedStatic< PassManagerOptions > options
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class represents an argument of a Block.
Definition: Value.h:315
Block represents an ordered list of Operations.
Definition: Block.h:30
The result of a transform IR operation application.
static DiagnosedSilenceableFailure success()
Constructs a DiagnosedSilenceableFailure in the success state.
bool isDefiniteFailure() const
Returns true if this is a definite failure.
static DiagnosedSilenceableFailure silenceableFailure(Diagnostic &&diag)
Constructs a DiagnosedSilenceableFailure in the silenceable failure state, ready to emit the given di...
void takeDiagnostics(SmallVectorImpl< Diagnostic > &diags)
Take the diagnostics and silence.
static DiagnosedSilenceableFailure definiteFailure()
Constructs a DiagnosedSilenceableFailure in the failure state.
bool isSilenceableFailure() const
Returns true if this is a silenceable failure.
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
Definition: Diagnostics.h:156
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:63
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:333
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:383
This is a value defined by a result of an operation.
Definition: Value.h:453
unsigned getResultNumber() const
Returns the number of this result.
Definition: Value.h:465
Helper class for implementing traits.
Definition: OpDefinition.h:371
Operation * getOperation()
Return the ultimate Operation being worked on.
Definition: OpDefinition.h:374
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition: Operation.h:665
A 2D array where each row may have different length.
Definition: RaggedArray.h:18
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
Region * getParentRegion()
Return the region containing this region or nullptr if the region is attached to a top-level operatio...
Definition: Region.cpp:45
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition: Region.h:200
Block & back()
Definition: Region.h:64
Block & front()
Definition: Region.h:65
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:399
This base class is used for derived effects that are non-parametric.
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:378
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Region * getParentRegion()
Return the Region in which this Value is defined.
Definition: Value.cpp:41
A list of results of applying a transform op with ApplyEachOpTrait to a single payload operation,...
auto begin()
Iterators over the list.
const ApplyToEachResult & operator[](size_t index) const
void assign(unsigned size, std::nullptr_t)
Sets the list of results to size null pointers.
void reserve(unsigned size)
Reserves space for size elements in the list.
size_t size() const
Returns the number of elements in the list.
ApplyToEachResult & operator[](size_t index)
Element access. Expects the index to be in bounds.
void push_back(Operation *op)
Appends an element to the list.
void assign(Range &&range)
Sets the list of results to the given range of values.
A specialized listener that keeps track of cases in which no replacement payload could be found.
bool failed() const
Return "true" if this tracking listener had a failure.
void notifyPayloadReplacementNotFound(Operation *op, ValueRange values, DiagnosedSilenceableFailure &&diag) override
This function is called when a tracked payload op is dropped because no replacement op was found.
DiagnosedSilenceableFailure checkAndResetError()
Check and return the current error state of this listener.
Trait implementing the MemoryEffectOpInterface for operations that "consume" their operands and produ...
void getEffects(SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
This op "consumes" the operands by reading and freeing then, "produces" the results by allocating and...
static LogicalResult verifyTrait(Operation *op)
Checks that the op matches the expectations of this trait.
Trait implementing the MemoryEffectOpInterface for single-operand single-result operations that use t...
void getEffects(SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
This op produces handles to the Payload IR without consuming the original handles and without modifyi...
static LogicalResult verifyTrait(Operation *op)
Checks that the op matches the expectation of this trait.
Trait implementing the MemoryEffectsOpInterface for operations that produce transform dialect paramet...
static LogicalResult verifyTrait(Operation *op)
Checks that the op matches the expectation of this trait, i.e., that it implements the MemoryEffectsO...
void getEffects(SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Populates effects with effect instances described in the trait documentation.
This trait is supposed to be attached to Transform dialect operations that can be standalone top-leve...
LogicalResult mapBlockArguments(TransformState &state)
static LogicalResult verifyTrait(Operation *op)
Verifies that op satisfies the invariants of this trait.
void getPotentialTopLevelEffects(SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Populates effects with side effects implied by this trait.
LogicalResult mapBlockArguments(TransformState &state, Region &region)
Sets up the mapping between the entry block of the given region of this op and the relevant list of P...
Block * getBodyBlock(unsigned region=0)
Returns the single block of the given region.
TrackingListener failures are reported only for ops that have this trait.
A listener that updates a TransformState based on IR modifications.
LogicalResult notifyMatchFailure(Location loc, function_ref< void(Diagnostic &)> reasonCallback) override
Notify the listener that the pattern failed to match the given operation, and provide a callback to p...
TransformOpInterface getTransformOp() const
Return the transform op in which this TrackingListener is used.
static Operation * getCommonDefiningOp(ValueRange values)
Return the single op that defines all given values (if any).
virtual void notifyPayloadReplacementNotFound(Operation *op, ValueRange values, DiagnosedSilenceableFailure &&diag)
This function is called when a tracked payload op is dropped because no replacement op was found.
virtual DiagnosedSilenceableFailure findReplacementOp(Operation *&result, Operation *op, ValueRange newValues) const
Return a replacement payload op for the given op, which is going to be replaced with the given values...
TrackingListener(TransformState &state, TransformOpInterface op)
Create a new TrackingListener for usage in the specified transform op.
Trait implementing the TransformOpInterface for operations applying a transformation to a single oper...
static LogicalResult verifyTrait(Operation *op)
Checks that the op matches the expectations of this trait.
DiagnosedSilenceableFailure apply(transform::TransformRewriter &rewriter, TransformResults &transformResults, TransformState &state)
Calls applyToOne for every payload operation associated with the operand of this transform IR op,...
Options controlling the application of transform operations by the TransformState.
TransformOptions & enableExpensiveChecks(bool enable=true)
Requests computationally expensive checks of the transform and payload IR well-formedness to be perfo...
TransformOptions & enableEnforceSingleToplevelTransformOp(bool enable=true)
TransformOptions & operator=(const TransformOptions &)=default
TransformOptions(const TransformOptions &)=default
bool getExpensiveChecksEnabled() const
Returns true if the expensive checks are requested.
Local mapping between values defined by a specific op implementing the TransformOpInterface and the p...
void set(OpResult value, std::initializer_list< Operation * > ops)
Indicates that the result of the transform IR op at the given position corresponds to the given list ...
void setValues(OpResult handle, std::initializer_list< Value > values)
Indicates that the result of the transform IR op at the given position corresponds to the given range...
void setValues(OpResult handle, Range &&values)
Indicates that the result of the transform IR op at the given position corresponds to the given range...
void setParams(OpResult value, ArrayRef< TransformState::Param > params)
Indicates that the result of the transform IR op at the given position corresponds to the given list ...
void set(OpResult value, Range &&ops)
Indicates that the result of the transform IR op at the given position corresponds to the given list ...
void setRemainingToEmpty(TransformOpInterface transform)
Sets the currently unset results to empty lists of the kind expected by the corresponding results of ...
void setMappedValues(OpResult handle, ArrayRef< MappedValue > values)
Indicates that the result of the transform IR op at the given position corresponds to the given range...
This is a special rewriter to be used in transform op implementations, providing additional helper fu...
TransformRewriter(MLIRContext *ctx, ErrorCheckingTrackingListener *listener)
Create a new TransformRewriter.
bool hasTrackingFailures() const
Return "true" if the tracking listener had failures.
LogicalResult notifyPayloadOperationReplaced(Operation *op, Operation *replacement)
Notify the transform dialect interpreter that the given op has been replaced with another op and that...
void silenceTrackingFailure()
Silence all tracking failures that have been encountered so far.
Base class for TransformState extensions that allow TransformState to contain user-specified informat...
Extension(TransformState &state)
Constructs an extension of the given TransformState object.
const TransformState & getTransformState() const
Provides read-only access to the parent TransformState object.
LogicalResult replacePayloadOp(Operation *op, Operation *replacement)
Replaces the given payload op with another op.
virtual ~Extension()
Base virtual destructor.
LogicalResult replacePayloadValue(Value value, Value replacement)
Replaces the given payload value with another value.
A RAII object maintaining a "stack frame" for a transform IR region.
~RegionScope()
Forgets the mapping from or to values defined in the associated transform IR region,...
The state maintained across applications of various ops implementing the TransformOpInterface.
const TransformOptions & getOptions() const
friend LogicalResult applyTransforms(Operation *, TransformOpInterface, const RaggedArray< MappedValue > &, const TransformOptions &, bool)
Entry point to the Transform dialect infrastructure.
LogicalResult getHandlesForPayloadValue(Value payloadValue, SmallVectorImpl< Value > &handles, bool includeOutOfScope=false) const
Populates handles with all handles pointing to the given payload IR value.
auto getPayloadOps(Value value) const
Returns an iterator that enumerates all ops that the given transform IR value corresponds to.
auto getPayloadValues(Value handleValue) const
Returns an iterator that enumerates all payload IR values that the given transform IR value correspon...
LogicalResult mapBlockArguments(BlockArgument argument, ArrayRef< Operation * > operations)
Records the mapping between a block argument in the transform IR and a list of operations in the payl...
DiagnosedSilenceableFailure applyTransform(TransformOpInterface transform)
Applies the transformation specified by the given transform op and updates the state accordingly.
RegionScope make_region_scope(Region &region)
Creates a new region scope for the given region.
ArrayRef< Attribute > getParams(Value value) const
Returns the list of parameters that the given transform IR value corresponds to.
LogicalResult mapBlockArgument(BlockArgument argument, ArrayRef< MappedValue > values)
size_t getNumTopLevelMappings() const
Returns the number of extra mappings for the top-level operation.
Ty & addExtension(Args &&...args)
Adds a new Extension of the type specified as template parameter, constructing it with the arguments ...
LogicalResult getHandlesForPayloadOp(Operation *op, SmallVectorImpl< Value > &handles, bool includeOutOfScope=false) const
Populates handles with all handles pointing to the given Payload IR op.
Ty * getExtension()
Returns the extension of the specified type.
Operation * getTopLevel() const
Returns the op at which the transformation state is rooted.
void removeExtension()
Removes the extension of the specified type.
ArrayRef< MappedValue > getTopLevelMapping(size_t position) const
Returns the position-th extra mapping for the top-level operation.
LogicalResult verifyTransformOpInterface(Operation *op)
Verification hook for TransformOpInterface.
void setApplyToOneResults(Operation *transformOp, TransformResults &transformResults, ArrayRef< ApplyToEachResultList > results)
"Transpose" the results produced by individual applications, arranging them per result value of the t...
void forwardTerminatorOperands(Block *block, transform::TransformState &state, transform::TransformResults &results)
Populates results with payload associations that match exactly those of the operands to block's termi...
void getParamProducerTransformOpTraitEffects(Operation *op, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Non-template implementation of ParamProducerTransformOpTrait::getEffects().
LogicalResult checkNestedConsumption(Location loc, ArrayRef< Operation * > targets)
Reports an error and returns failure if targets contains an ancestor operation before its descendant ...
LogicalResult mapPossibleTopLevelTransformOpBlockArguments(TransformState &state, Operation *op, Region &region)
Maps the only block argument of the op with PossibleTopLevelTransformOpTrait to either the list of op...
TransformState makeTransformStateForTesting(Region *region, Operation *payloadRoot)
Make a dummy transform state for testing purposes.
LogicalResult checkApplyToOne(Operation *transformOp, Location payloadOpLoc, const ApplyToEachResultList &partialResult)
Check that the contents of partialResult matches the number, kind (payload op or parameter) and nulli...
SmallVector< OpOperand * > getConsumedHandleOpOperands(transform::TransformOpInterface transformOp)
Returns all operands that are handles and being consumed by the given op.
LogicalResult verifyParamProducerTransformOpTrait(Operation *op)
Non-template implementation of ParamProducerTransformOpTrait::verify().
void prepareValueMappings(SmallVectorImpl< SmallVector< transform::MappedValue >> &mappings, ValueRange values, const transform::TransformState &state)
Populates mappings with mapped values associated with the given transform IR values in the given stat...
LogicalResult verifyPossibleTopLevelTransformOpTrait(Operation *op)
Verification hook for PossibleTopLevelTransformOpTrait.
DiagnosedSilenceableFailure applyTransformToEach(TransformOpTy transformOp, TransformRewriter &rewriter, Range &&targets, SmallVectorImpl< ApplyToEachResultList > &results, TransformState &state)
Applies a one-to-one or a one-to-many transform to each of the given targets.
void getPotentialTopLevelEffects(Operation *operation, Value root, Block &body, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Populates effects with side effects implied by PossibleTopLevelTransformOpTrait for the given operati...
void onlyReadsPayload(SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
bool isHandleConsumed(Value handle, transform::TransformOpInterface transform)
Checks whether the transform op consumes the given handle.
void onlyReadsHandle(ValueRange handles, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
void getConsumedBlockArguments(Block &block, llvm::SmallDenseSet< unsigned > &consumedArguments)
Populates consumedArguments with positions of block arguments that are consumed by the operations in ...
LogicalResult applyTransforms(Operation *payloadRoot, TransformOpInterface transform, const RaggedArray< MappedValue > &extraMapping={}, const TransformOptions &options=TransformOptions(), bool enforceToplevelTransformOp=true)
Entry point to the Transform dialect infrastructure.
bool doesModifyPayload(transform::TransformOpInterface transform)
Checks whether the transform op modifies the payload.
void consumesHandle(ValueRange handles, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Populates effects with the memory effects indicating the operation on the given handle value:
bool doesReadPayload(transform::TransformOpInterface transform)
Checks whether the transform op reads the payload.
void producesHandle(ValueRange handles, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
void modifiesPayload(SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Populates effects with the memory effects indicating the access to payload IR resource.
llvm::PointerUnion< Operation *, Param, Value > MappedValue
Include the generated interface declarations.
LogicalResult success(bool isSuccess=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:56
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
bool failed(LogicalResult result)
Utility function that returns true if the provided LogicalResult corresponds to a failure value.
Definition: LogicalResult.h:72
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26
Represents a range (offset, size, and stride) where each element of the triple may be dynamic or stat...
Side effect resource corresponding to the Payload IR itself.
StringRef getName() override
Return a string name of the resource.
Side effect resource corresponding to the mapping between Transform IR values and Payload IR operatio...
StringRef getName() override
Return a string name of the resource.