xref: /llvm-project/mlir/examples/transform/Ch4/lib/MyExtension.cpp (revision db791b278a414fb6df1acc1799adcf11d8fb9169)
1 //===-- MyExtension.cpp - Transform dialect tutorial ----------------------===//
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 // This file defines Transform dialect extension operations used in the
10 // Chapter 4 of the Transform dialect tutorial.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MyExtension.h"
15 #include "mlir/Dialect/Transform/IR/TransformDialect.h"
16 #include "llvm/Support/Debug.h"
17 
18 #define DEBUG_TYPE_MATCHER "transform-matcher"
19 #define DBGS_MATCHER() (llvm::dbgs() << "[" DEBUG_TYPE_MATCHER "] ")
20 #define DEBUG_MATCHER(x) DEBUG_WITH_TYPE(DEBUG_TYPE_MATCHER, x)
21 
22 #define GET_OP_CLASSES
23 #include "MyExtension.cpp.inc"
24 
25 //===---------------------------------------------------------------------===//
26 // MyExtension
27 //===---------------------------------------------------------------------===//
28 
29 // Define a new transform dialect extension. This uses the CRTP idiom to
30 // identify extensions.
31 class MyExtension
32     : public ::mlir::transform::TransformDialectExtension<MyExtension> {
33 public:
34   // The extension must derive the base constructor.
35   using Base::Base;
36 
37   // This function initializes the extension, similarly to `initialize` in
38   // dialect definitions. List individual operations and dependent dialects
39   // here.
40   void init();
41 };
42 
43 void MyExtension::init() {
44   // Register the additional match operations with the dialect similarly to
45   // other transform operations. List all operations generated from ODS. This
46   // call will perform additional checks that the operations implement the
47   // transform and memory effect interfaces required by the dialect interpreter
48   // and assert if they do not.
49   registerTransformOps<
50 #define GET_OP_LIST
51 #include "MyExtension.cpp.inc"
52       >();
53 }
54 
55 //===---------------------------------------------------------------------===//
56 // HasOperandSatisfyingOp
57 //===---------------------------------------------------------------------===//
58 
59 /// Returns `true` if both types implement one of the interfaces provided as
60 /// template parameters.
61 template <typename... Tys>
62 static bool implementSameInterface(mlir::Type t1, mlir::Type t2) {
63   return ((llvm::isa<Tys>(t1) && llvm::isa<Tys>(t2)) || ... || false);
64 }
65 
66 /// Returns `true` if both types implement one of the transform dialect
67 /// interfaces.
68 static bool implementSameTransformInterface(mlir::Type t1, mlir::Type t2) {
69   return implementSameInterface<
70       mlir::transform::TransformHandleTypeInterface,
71       mlir::transform::TransformParamTypeInterface,
72       mlir::transform::TransformValueHandleTypeInterface>(t1, t2);
73 }
74 
75 // Matcher ops implement `apply` similarly to other transform ops. They are not
76 // expected to modify payload, but use the tri-state result to signal failure or
77 // success to match, as well as potential irrecoverable errors.
78 mlir::DiagnosedSilenceableFailure
79 mlir::transform::HasOperandSatisfyingOp::apply(
80     mlir::transform::TransformRewriter &rewriter,
81     mlir::transform::TransformResults &results,
82     mlir::transform::TransformState &state) {
83   // For simplicity, only handle a single payload op. Actual implementations
84   // can use `SingleOpMatcher` trait to simplify implementation and document
85   // this expectation.
86   auto payloadOps = state.getPayloadOps(getOp());
87   if (!llvm::hasSingleElement(payloadOps))
88     return emitSilenceableError() << "expected single payload";
89 
90   // Iterate over all operands of the payload op to see if they can be matched
91   // using the body of this op.
92   Operation *payload = *payloadOps.begin();
93   for (OpOperand &operand : payload->getOpOperands()) {
94     // Create a scope for transform values defined in the body. This corresponds
95     // to the syntactic scope of the region attached to this op. Any values
96     // associated with payloads from now on will be automatically dissociated
97     // when this object is destroyed, i.e. at the end of the iteration.
98     // Associate the block argument handle with the operand.
99     auto matchScope = state.make_region_scope(getBody());
100     if (failed(state.mapBlockArgument(getBody().getArgument(0),
101                                       {operand.get()}))) {
102       return DiagnosedSilenceableFailure::definiteFailure();
103     }
104 
105     // Iterate over all nested matchers with the current mapping and see if they
106     // succeed.
107     bool matchSucceeded = true;
108     for (Operation &matcher : getBody().front().without_terminator()) {
109       // Matcher ops are applied similarly to any other transform op.
110       DiagnosedSilenceableFailure diag =
111           state.applyTransform(cast<TransformOpInterface>(matcher));
112 
113       // Definite failures are immediately propagated as they are irrecoverable.
114       if (diag.isDefiniteFailure())
115         return diag;
116 
117       // On success, keep checking the remaining conditions.
118       if (diag.succeeded())
119         continue;
120 
121       // Report failure-to-match for debugging purposes and stop matching this
122       // operand.
123       assert(diag.isSilenceableFailure());
124       DEBUG_MATCHER(DBGS_MATCHER()
125                     << "failed to match operand #" << operand.getOperandNumber()
126                     << ": " << diag.getMessage());
127       (void)diag.silence();
128       matchSucceeded = false;
129       break;
130     }
131     // If failed to match this operand, try other operands.
132     if (!matchSucceeded)
133       continue;
134 
135     // If we reached this point, the matching succeeded for the current operand.
136     // Remap the values associated with terminator operands to be associated
137     // with op results, and also map the parameter result to the operand's
138     // position. Note that it is safe to do here despite the end of the scope
139     // as `results` are integrated into `state` by the interpreter after `apply`
140     // returns rather than immediately.
141     SmallVector<SmallVector<MappedValue>> yieldedMappings;
142     transform::detail::prepareValueMappings(
143         yieldedMappings, getBody().front().getTerminator()->getOperands(),
144         state);
145     results.setParams(cast<OpResult>(getPosition()),
146                       {rewriter.getI32IntegerAttr(operand.getOperandNumber())});
147     for (auto &&[result, mapping] : llvm::zip(getResults(), yieldedMappings))
148       results.setMappedValues(result, mapping);
149     return DiagnosedSilenceableFailure::success();
150   }
151 
152   // If we reached this point, none of the operands succeeded the match.
153   return emitSilenceableError()
154          << "none of the operands satisfied the conditions";
155 }
156 
157 // By convention, operations implementing MatchOpInterface must not modify
158 // payload IR and must therefore specify that they only read operand handles and
159 // payload as their effects.
160 void mlir::transform::HasOperandSatisfyingOp::getEffects(
161     llvm::SmallVectorImpl<mlir::MemoryEffects::EffectInstance> &effects) {
162   onlyReadsPayload(effects);
163   onlyReadsHandle(getOpMutable(), effects);
164   producesHandle(getOperation()->getOpResults(), effects);
165 }
166 
167 // Verify well-formedness of the operation and emit diagnostics if it is
168 // ill-formed.
169 llvm::LogicalResult mlir::transform::HasOperandSatisfyingOp::verify() {
170   mlir::Block &bodyBlock = getBody().front();
171   if (bodyBlock.getNumArguments() != 1 ||
172       !isa<TransformValueHandleTypeInterface>(
173           bodyBlock.getArgument(0).getType())) {
174     return emitOpError()
175            << "expects the body to have one value handle argument";
176   }
177   if (bodyBlock.getTerminator()->getNumOperands() != getNumResults() - 1) {
178     return emitOpError() << "expects the body to yield "
179                          << (getNumResults() - 1) << " values, got "
180                          << bodyBlock.getTerminator()->getNumOperands();
181   }
182   for (auto &&[i, operand, result] :
183        llvm::enumerate(bodyBlock.getTerminator()->getOperands().getTypes(),
184                        getResults().getTypes())) {
185     if (implementSameTransformInterface(operand, result))
186       continue;
187     return emitOpError() << "expects terminator operand #" << i
188                          << " and result #" << (i + 1)
189                          << " to implement the same transform interface";
190   }
191 
192   for (Operation &op : bodyBlock.without_terminator()) {
193     if (!isa<TransformOpInterface>(op) || !isa<MatchOpInterface>(op)) {
194       InFlightDiagnostic diag = emitOpError()
195                                 << "expects body to contain match ops";
196       diag.attachNote(op.getLoc()) << "non-match operation";
197       return diag;
198     }
199   }
200 
201   return success();
202 }
203 
204 void registerMyExtension(::mlir::DialectRegistry &registry) {
205   registry.addExtensions<MyExtension>();
206 }
207