[RFC] Add enum attribute decorator class


I have one proposal regarding enum attributes support and I’d like to hear your opinion.

For now, such attributes are represented as raw StringAttr/IntegerAttr in the generated code. All checks for value validity and conversion from raw format to actual enum value is done in the code, which uses the enum attribute (Operation, for example).

I’d like to propose generating separate decorator classes for enum attributes in the same way as it is done for struct attributes. Those classes will incapsulate all validation/conversion logic.

For example:

enum class SomeEnum {...};

class SomeEnumAttr : public ::mlir::StringAttr {
    using ::mlir::StringAttr::StringAttr;

    static bool classof(::mlir::Attribute attr) {
        if (!::mlir::StringAttr::classof(attr)) {
             return false;

        // Check that the string represents SomeEnum value
        return symbolizeEnum<SomeEnum>(attr.cast<::mlir::StringAttr>.getValue()).hasValue();

    static SomeEnumAttr get(SomeEnum val, ::mlir::MLIRContext* context) {
        return ::mlir::StringAttr::get(stringifyEnum(val), context).cast<SomeEnumAttr>()

    SomeEnum getValue() const {
        return symbolizeEnum<SomeEnum>(::mlir::StringAttr::getValue()).getValue();

IMHO, this will simply the code, which uses enum attrs (no need to duplicate the validation checks).

LGTM, feel free to send a patch.

– River

+1, nice idea! Do you also plan to generate some of that from ODS?

Yes, this will be an extension for --gen-enum-* parts of mlir-tblgen, it will generate new Attribute classes in addition to enums utilities. Other parts (like StructAttr and Operation generation) will use new Enum Attribute classes instead of raw String/Integer to delegate the validation logic to them.