|
| 1 | +# Customizing Assembly Behavior |
| 2 | + |
| 3 | +[TOC] |
| 4 | + |
| 5 | +## Generating Aliases |
| 6 | + |
| 7 | +To reduce verbosity in the resulting assembly, `AsmPrinter` can generate aliases for frequently used types and attributes. |
| 8 | + |
| 9 | +For example, `!my_dialect.type<a=3,b=4,c=5,d=tuple,e=another_type>` and `#my_dialect.attr<a=3>` can be aliased to `!my_dialect_type` and `#my_dialect_attr`, simplifying further references. |
| 10 | + |
| 11 | +To enable this, the owning dialect of these types/attributes can define an interface to hook into the `AsmPrinter`. This is effective only when the assembly is not printed in generic form. |
| 12 | + |
| 13 | +```cpp |
| 14 | +// OpAsmDialectInterface is defined in |
| 15 | +// https://github.com/llvm/llvm-project/blob/91ab10e8d6c256d841da1a1a1b47c334e08d95b9/mlir/include/mlir/IR/OpImplementation.h#L1738 |
| 16 | +struct MyDialectOpAsmDialectInterface : public OpAsmDialectInterface { |
| 17 | + public: |
| 18 | + using OpAsmDialectInterface::OpAsmDialectInterface; |
| 19 | + |
| 20 | + AliasResult getAlias(Type type, raw_ostream& os) const override { |
| 21 | + if (mlir::isa<MyType>(type)) { |
| 22 | + os << "my_dialect_type"; |
| 23 | + // Could return OverridableAlias when |
| 24 | + // allowing other dialect to override the alias. |
| 25 | + // |
| 26 | + // Other dialects are allowed to provide alias for |
| 27 | + // type/attribute not owned by them |
| 28 | + // but the final result would depend on the registration order |
| 29 | + // of these dialects in the MLIRContext |
| 30 | + return AliasResult::FinalAlias; |
| 31 | + } |
| 32 | + return AliasResult::NoAlias; |
| 33 | + } |
| 34 | + |
| 35 | + AliasResult getAlias(Attribute attr, raw_ostream& os) const override { |
| 36 | + if (mlir::isa<MyAttribute>(attr)) { |
| 37 | + os << "my_dialect_attr"; |
| 38 | + return AliasResult::FinalAlias; |
| 39 | + } |
| 40 | + return AliasResult::NoAlias; |
| 41 | + } |
| 42 | +}; |
| 43 | + |
| 44 | +void MyDialect::initialize() { |
| 45 | + // register the interface to the dialect |
| 46 | + addInterface<MyDialectOpAsmDialectInterface>(); |
| 47 | +} |
| 48 | +``` |
| 49 | +
|
| 50 | +* If `getAlias` provides an alias with a trailing digit, `AsmPrinter` appends an underscore to avoid conflicts with autogenerated IDs. |
| 51 | +* If multiple types/attributes have the same alias from `getAlias`, a number is appended to the alias to avoid conflicts. |
0 commit comments