1# Chapter 3: More than Simple Transform Operations 2 3## Type Constraints and ApplyEach Trait 4 5A transform operation that applies to each payload operation individually and requires it to be of a specific kind is a repeated pattern. One can use Transform dialect types to specify the preconditions of the type. Specifically, we can change the expected operand type from the wide `TransformHandleTypeInterface` to the more narrow `Transform_ConcreteOp<"func.call">`. Furthermore, we use the `TransformEachOpTrait` trait to provide the skeleton implementation of the `apply` method that performs verification, iteration over payloads and result concatenation. The improved ODS op definition is as follows. 6 7```tablegen 8// In MyExtension.td. 9 10// Define the new operation. By convention, prefix its name with the name of the dialect extension, "my.". The full operation name will be further prefixed with "transform.". 11def ChangeCallTargetOp : Op<Transform_Dialect, "my.change_call_target", 12 // Indicate that the operation implements the required TransformOpInterface and 13 // MemoryEffectsOpInterface. Use the TransformEach trait to provide the 14 // implementation for TransformOpInterface. 15 [TransformOpInterface, TransformEachOpTrait, 16 DeclareOpInterfaceMethods<MemoryEffectsOpInterface>]> { 17 // Provide a brief and a full description. It is recommended that the latter describes 18 // the effects on the operands and how the operation processes various failure modes. 19 let summary = "Changes the callee of a call operation to the specified one"; 20 let description = [{ 21 For each `func.call` payload operation associated with the handle, changes its 22 callee to be the symbol whose name is provided as an attribute to this operation. 23 24 Generates a silenceable failure if the operand is associated with payload operations 25 that are not `func.call`. 26 Only reads the operand. 27 }]; 28 29 // The arguments include the handle to the payload operations and the attribute that 30 // specifies the new callee. The handle must implement TransformHandleTypeInterface. 31 // We use a string attribute as the symbol may not exist in the transform IR so the 32 // verification may fail. 33 let arguments = (ins 34 Transform_ConcreteOpType<"func.call">:$call, 35 StrAttr:$new_target); 36 37 // The results are empty as the transformation does not produce any new payload. 38 let results = (outs); 39 40 // Provide nice syntax. 41 let assemblyFormat = "$call `,` $new_target attr-dict `:` type($call)"; 42 43 // Declare the function implementing the interface for a single payload operation. 44 let extraClassDeclaration = [{ 45 ::mlir::DiagnosedSilenceableFailure applyToOne( 46 ::mlir::func::CallOp call, 47 ::mlir::transform::ApplyToEachResultList &results, 48 ::mlir::transform::TransformState &state); 49 }]; 50} 51``` 52 53Now, instead of defining the `apply` method with a loop, we can simply define a function that applies to an individual payload operation and the trait will take care of the rest. 54 55```c++ 56::mlir::DiagnosedSilenceableFailure ChangeCallTargetOp::applyToOne( 57 ::mlir::func::CallOp call,, 58 ::mlir::transform::ApplyToEachResultList &results, 59 ::mlir::transform::TransformState &state) { 60 // Call the actual transformation function. 61 updateCallee(call, getNewTarget()); 62 // Indicate success. 63 return DiagnosedSilenceableFailure::success(); 64} 65``` 66 67## Defining a Transform Type 68 69In addition to operations, the Transform dialect allows extensions to define and inject additional attributes and types. As we have seen above, transform types are used to specify constraints on the payload operations. Our call rewriting operation currently applies only to `func.call`. We may want to generalize it to apply to any payload operation that implements `CallOpInterface`, but the Transform dialect currently doesn’t provide a type that checks if a payload operation implements this interface. Let’s define it in our extension. 70 71Type definition is again identical to defining a dialect type with ODS. 72 73```tablegen 74// Transform dialect allows additional types to be defined and injected. 75def CallOpInterfaceHandle 76 : TypeDef<Transform_Dialect, "CallOpInterfaceHandle", 77 // The type must implement `TransformHandleTypeInterface`. 78 [DeclareTypeInterfaceMethods<TransformHandleTypeInterface>]> { 79 80 // The usual components of a type such as description, mnemonic and assembly format 81 // should be provided. 82 let summary = "handle to payload operations implementing CallOpInterface"; 83 let mnemonic = "my.call_op_interface"; 84 let assemblyFormat = ""; 85} 86``` 87 88We will omit the generation of declaration and definitions using Tablegen for brevity as it is identical to the regular case. 89 90To finalize the definition of a transform type, one must implement the interface methods. 91 92```c++ 93// In MyExtension.cpp. 94 95// The interface declares this method to verify constraints this type has on 96// payload operations. It returns the now familiar tri-state result. 97mlir::DiagnosedSilenceableFailure 98mlir::transform::CallOpInterfaceHandleType::checkPayload( 99 // Location at which diagnostics should be emitted. 100 mlir::Location loc, 101 // List of payload operations that are about to be associated with the 102 // handle that has this type. 103 llvm::ArrayRef<mlir::Operation *> payload) const { 104 105 // All payload operations are expected to implement CallOpInterface, check this. 106 for (Operation *op : payload) { 107 if (llvm::isa<mlir::CallOpInterface>(op)) 108 continue; 109 110 // By convention, these verifiers always emit a silenceable failure since they are 111 // checking a precondition. 112 DiagnosedSilenceableFailure diag = emitSilenceableError(loc) 113 << "expected the payload operation to implement CallOpInterface"; 114 diag.attachNote(op->getLoc()) << "offending operation"; 115 return diag; 116 } 117 118 // If everything is okay, return success. 119 return DiagnosedSilenceableFailure::success(); 120} 121 122``` 123 124Additional attributes and types need to be registered in the extension, next to operations. 125 126```c++ 127// In MyExtension.cpp. 128 129void MyExtension::init() { 130 // … 131 132 registerTypes< 133#define GET_TYPEDEF_LIST 134#include "MyExtensionTypes.cpp.inc" 135 >(); 136} 137``` 138 139This type is now directly available in the transform dialect and can be used in operations. 140 141 142```mlir 143 // Cast to our new type. 144 %casted = transform.cast %call : !transform.any_op to !transform.my.call_op_interface 145 // Using our new operation. 146 transform.my.change_call_target %casted, "microkernel" : !transform.my.call_op_interface 147``` 148 149## Operand Consumption 150 151As an exercise, let us modify the rewriting operation to consume the operand. This would be necessary, for example, if the transformation were to rewrite the `func.call` operation into a custom operation `my.mm4`. Since the operand handle is now consumed, the operation can return a new handle to the newly produced payload operation. Otherwise, the ODS definition of the transform operation remains unchanged. 152 153 154```tablegen 155// In MyExtension.td. 156 157// Define another transform operation. 158def CallToOp : Op<Transform_Dialect, "my.call_to_op", 159 // Indicate that the operation implements the required TransformOpInterface and 160 // MemoryEffectsOpInterface. Use the TransformEach trait to provide the 161 // implementation for TransformOpInterface. 162 [TransformOpInterface, TransformEachOpTrait, 163 DeclareOpInterfaceMethods<MemoryEffectsOpInterface>]> { 164 // Summary and description omitted for brevity. 165 166 // The argument is the handle to the payload operations. 167 let arguments = (ins CallOpInterfaceHandle:$call); 168 169 // The result is the handle to the payload operations produced during the 170 // transformation. 171 let results = (outs TransformHandleTypeInterface:$transformed); 172 173 // Provide nice syntax. 174 let assemblyFormat = "$call attr-dict `:` functional-type(inputs, outputs)"; 175 176 // Declare the function implementing the interface for a single payload operation. 177 let extraClassDeclaration = [{ 178 ::mlir::DiagnosedSilenceableFailure applyToOne( 179 ::mlir::CallOpInterface call, 180 ::mlir::transform::ApplyToEachResultList &results, 181 ::mlir::transform::TransformState &state); 182 }]; 183} 184``` 185 186Now let’s look at the implementation of interface methods. 187 188```c++ 189// In MyExtension.cpp. 190 191::mlir::DiagnosedSilenceableFailure CallToOp::applyToOne( 192 ::mlir::CallOpInterface call, 193 ::mlir::transform::ApplyToEachResultList &results, 194 ::mlir::transform::TransformState &state) { 195 // Call the actual rewrite. 196 Operation *rewritten = rewriteToOp(call); 197 198 // Report an error if the rewriter produced a null pointer. Note that it may have 199 // irreversibly modified the payload IR, so we produce a definite failure. 200 if (!rewritten) { 201 return emitDefiniteError() << "failed to rewrite call to operation"; 202 } 203 204 // On success, push the resulting operation into the result list. The list is expected 205 // to contain exactly one entity per result and per application. The handles will be 206 // associated with lists of the respective values produced by each application. 207 results.push_back(rewritten); 208 209 // If everything is fine, return success. 210 return DiagnosedSilenceableFailure::success(); 211} 212 213void CallToOp::getEffects( 214 ::llvm::SmallVectorImpl<::mlir::MemoryEffects::EffectInstance> &effects) { 215 // Indicate using side effects that the operand handle is consumed, and the 216 // result handle is produced. 217 consumesHandle(getCall(), effects); 218 producesHandle(getTransformed(), effects); 219 220 // Indicate that the payload IR is modified. 221 modifiesPayload(effects); 222} 223``` 224 225The overall flow of these implementations is similar to the previous one. The application also needs to specify the resulting entities that are going to be associated with the handles it produces. Operations are required to specify the entities to associate with _all_ results on success, even if the list is empty. An assertion will be triggered if it is not the case. In case of failure, the interpreter will automatically associate all results that are not yet defined with empty lists. 226 227Note that since `applyToOne` always expects one payload entity to be associated with each result handle in each application, it cannot be used to return handles associated with empty lists for non-empty operand handles. Instead, one would use `apply` directly. 228 229```c++ 230::mlir::DiagnosedSilenceableFailure SomeOtherOp::apply( 231 ::mlir::transform::TransformResults &results, 232 ::mlir::transform::TransformState &state) { 233 // ... 234 235 // Associate the result `transformed` with an empty list of payload operations. 236 results.set(cast<OpResult>(getTransformed()), {}); 237 return DiagnosedSilenceableFailure::success(); 238} 239``` 240 241## Memory Effects Traits 242 243Some common memory effect patterns are also available as traits to minimize the boilerplate. 244 245* `FunctionalStyleTransformOpTrait` indicates that all handle-typed operands are consumed, all results are produced, and the payload IR is modified. 246* `NavigationTransformOpTrait` indicates that all handle-typed operands are only read, all results are produced, and the payload IR is only read. 247 248Using these traits removes the need to declare or define the methods of the `MemoryEffectsOpInterface`. 249 250```tablegen 251// In MyExtension.td. 252 253// Define another transform operation. 254def CallToOp : Op<Transform_Dialect, "my.call_to_op", 255 // Indicate that the operation implements the required TransformOpInterface. 256 // Use the TransformEach trait to provide implementation of this interface. 257 [TransformOpInterface, TransformEachOpTrait, 258 // Indicate that the operation implements the required MemoryEffectsOpInterface. 259 // Use the FunctionalStyle trait to provide the implementation for this interface. 260 MemoryEffectsOpInterface, FunctionalStyleTransformOpTrait]> { 261 // Summary and description omitted for brevity. 262 263 // The argument is the handle to the payload operations. 264 let arguments = (ins CallOpInterfaceHandle:$call); 265 266 // The result is the handle to the payload operations produced during the 267 // transformation. 268 let results = (outs TransformHandleTypeInterface:$transformed); 269 270 // Provide nice syntax. 271 let assemblyFormat = "$call attr-dict `:` functional-type(operands, results)"; 272 273 // Declare the function implementing the interface for a single payload operation. 274 let extraClassDeclaration = [{ 275 ::mlir::DiagnosedSilenceableFailure applyToOne( 276 ::mlir::CallOpInterface call, 277 ::mlir::transform::ApplyToEachResultList &results, 278 ::mlir::transform::TransformState &state); 279 }]; 280} 281``` 282 283 284