Optional Operand/ Attribute

Hi Everyone,

I would like to define an operation which can have optional memref operands and attribute. I have the following question:

  • Based on some examples that I found I see that I need to add the trait AttrSizedOperandSegments and then define 1D i32 elements attribute ‘operand_segment_sizes’, can someone explain what does mean please? is it the numbe of operand or their sizes??

  • How can declare in ODS that either a memref operand or an attribute (FlatSymbolRefAttr) is optional: I mean that my operation should either use the memref operand or use the attribute.

In ODS, you can have operands declared as Optional or Variadic, and attributes declared as OptionalAttr. The infrastructure will take care of the rest, you don’t need to deal with the storage yourself.

If you want an “exclusive or” behavior, it will have to be checked by the op verifier. Just make it emit errors if both or none of the operand and attribute are present.

1 Like

Thank you @ftynse

But in the case if I declare more than one operand as Optional. In the parse function, after parsing all existing operands (based on the existing of some keywords) how can I map each parsed operand to the corresponding operand. The only way that I know is using

parser.resolveOperands(inputsOperands, inputTypes, inputsOperandsLoc,
                             result.operands)

but I do not see how the infrastructure will manage correctly the mapping if I am not given any information to resolveOperands about the existing optional operands found?

In most cases, you shouldn’t even need to write a parse function. Declarative assembly format in ODS supports optional groups - Operation Definition Specification (ODS) - MLIR - and the corresponding parser code will be generated. You can look at the generated code or at the generator itself if you need to write a parser manually for some reason.

Ok, I did not expect the assembly format to be very developed to support optional groups. Thank you for your help.