Clang] Fix expansion of response files in -Wp after integrated-cc1 change
[llvm-project.git] / mlir / docs / DefiningAttributesAndTypes.md
blobbe8d550bcf3a5810bde0c757c7ec5dc3aa5ed712
1 # Quickstart tutorial to defining custom dialect attributes and types
3 This document is a quickstart to defining dialect specific extensions to the
4 [attribute](LangRef.md#attributes) and [type system](LangRef.md#type-system).
5 The main part of the tutorial focuses on defining types, but the instructions
6 are nearly identical for defining attributes.
8 See [MLIR specification](LangRef.md) for more information about MLIR, the
9 structure of the IR, operations, etc.
11 ## Types
13 Types in MLIR (like attributes, locations, and many other things) are
14 value-typed. This means that instances of `Type` should be passed around
15 by-value, as opposed to by-pointer or by-reference. The `Type` class in itself
16 acts as a wrapper around an internal storage object that is uniqued within an
17 instance of an `MLIRContext`.
19 ### Reserving a range of type kinds
21 Types in MLIR rely on having a unique `kind` value to ensure that casting checks
22 remain extremely
23 efficient([rationale](Rationale.md#reserving-dialect-type-kinds). For a dialect
24 author, this means that a range of type `kind` values must be explicitly, and
25 statically, reserved. A dialect can reserve a range of values by adding a new
26 entry to the
27 [DialectSymbolRegistry](https://github.com/llvm/llvm-project/blob/master/mlir/include/mlir/IR/DialectSymbolRegistry.def).
28 To support out-of-tree and experimental dialects, the registry predefines a set
29 of privates ranges, `PRIVATE_EXPERIMENTAL_[0-9]`, that are free for immediate
30 use.
32 ```c++
33 DEFINE_SYM_KIND_RANGE(LINALG) // Linear Algebra Dialect
34 DEFINE_SYM_KIND_RANGE(TOY)    // Toy language (tutorial) Dialect
36 // The following ranges are reserved for experimenting with MLIR dialects in a
37 // private context without having to register them here.
38 DEFINE_SYM_KIND_RANGE(PRIVATE_EXPERIMENTAL_0)
39 ```
41 For the sake of this tutorial, we will use the predefined
42 `PRIVATE_EXPERIMENTAL_0` range. These definitions will provide a range in the
43 Type::Kind enum to use when defining the derived types.
45 ```c++
46 namespace MyTypes {
47 enum Kinds {
48   // These kinds will be used in the examples below.
49   Simple = Type::Kind::FIRST_PRIVATE_EXPERIMENTAL_0_TYPE,
50   Complex
53 ```
55 ### Defining the type class
57 As described above, `Type` objects in MLIR are value-typed and rely on having an
58 implicitly internal storage object that holds the actual data for the type. When
59 defining a new `Type` it isn't always necessary to define a new storage class.
60 So before defining the derived `Type`, it's important to know which of the two
61 classes of `Type` we are defining. Some types are `primitives` meaning they do
62 not have any parameters and are singletons uniqued by kind, like the
63 [`index` type](LangRef.md#index-type). Parametric types on the other hand, have
64 additional information that differentiates different instances of the same
65 `Type` kind. For example the [`integer` type](LangRef.md#integer-type) has a
66 bitwidth, making `i8` and `i16` be different instances of
67 [`integer` type](LangRef.md#integer-type).
69 #### Simple non-parametric types
71 For simple parameterless types, we can jump straight into defining the derived
72 type class. Given that these types are uniqued solely on `kind`, we don't need
73 to provide our own storage class.
75 ```c++
76 /// This class defines a simple parameterless type. All derived types must
77 /// inherit from the CRTP class 'Type::TypeBase'. It takes as template
78 /// parameters the concrete type (SimpleType), and the base class to use (Type).
79 /// 'Type::TypeBase' also provides several utility methods to simplify type
80 /// construction.
81 class SimpleType : public Type::TypeBase<SimpleType, Type> {
82 public:
83   /// Inherit some necessary constructors from 'TypeBase'.
84   using Base::Base;
86   /// This static method is used to support type inquiry through isa, cast,
87   /// and dyn_cast.
88   static bool kindof(unsigned kind) { return kind == MyTypes::Simple; }
90   /// This method is used to get an instance of the 'SimpleType'. Given that
91   /// this is a parameterless type, it just needs to take the context for
92   /// uniquing purposes.
93   static SimpleType get(MLIRContext *context) {
94     // Call into a helper 'get' method in 'TypeBase' to get a uniqued instance
95     // of this type.
96     return Base::get(context, MyTypes::Simple);
97   }
99 ```
101 #### Parametric types
103 Parametric types are those that have additional construction or uniquing
104 constraints outside of the type `kind`. As such, these types require defining a
105 type storage class.
107 ##### Defining a type storage
109 Type storage objects contain all of the data necessary to construct and unique a
110 parametric type instance. The storage classes must obey the following:
112 *   Inherit from the base type storage class `TypeStorage`.
113 *   Define a type alias, `KeyTy`, that maps to a type that uniquely identifies
114     an instance of the parent type.
115 *   Provide a construction method that is used to allocate a new instance of the
116     storage class.
117     -   `Storage *construct(TypeStorageAllocator &, const KeyTy &key)`
118 *   Provide a comparison method between the storage and `KeyTy`.
119     -   `bool operator==(const KeyTy &) const`
120 *   Provide a method to generate the `KeyTy` from a list of arguments passed to
121     the uniquer. (Note: This is only necessary if the `KeyTy` cannot be default
122     constructed from these arguments).
123     -   `static KeyTy getKey(Args...&& args)`
124 *   Provide a method to hash an instance of the `KeyTy`. (Note: This is not
125     necessary if an `llvm::DenseMapInfo<KeyTy>` specialization exists)
126     -   `static llvm::hash_code hashKey(const KeyTy &)`
128 Let's look at an example:
130 ```c++
131 /// Here we define a storage class for a ComplexType, that holds a non-zero
132 /// integer and an integer type.
133 struct ComplexTypeStorage : public TypeStorage {
134   ComplexTypeStorage(unsigned nonZeroParam, Type integerType)
135       : nonZeroParam(nonZeroParam), integerType(integerType) {}
137   /// The hash key for this storage is a pair of the integer and type params.
138   using KeyTy = std::pair<unsigned, Type>;
140   /// Define the comparison function for the key type.
141   bool operator==(const KeyTy &key) const {
142     return key == KeyTy(nonZeroParam, integerType);
143   }
145   /// Define a hash function for the key type.
146   /// Note: This isn't necessary because std::pair, unsigned, and Type all have
147   /// hash functions already available.
148   static llvm::hash_code hashKey(const KeyTy &key) {
149     return llvm::hash_combine(key.first, key.second);
150   }
152   /// Define a construction function for the key type.
153   /// Note: This isn't necessary because KeyTy can be directly constructed with
154   /// the given parameters.
155   static KeyTy getKey(unsigned nonZeroParam, Type integerType) {
156     return KeyTy(nonZeroParam, integerType);
157   }
159   /// Define a construction method for creating a new instance of this storage.
160   static ComplexTypeStorage *construct(TypeStorageAllocator &allocator,
161                                        const KeyTy &key) {
162     return new (allocator.allocate<ComplexTypeStorage>())
163         ComplexTypeStorage(key.first, key.second);
164   }
166   unsigned nonZeroParam;
167   Type integerType;
171 ##### Type class definition
173 Now that the storage class has been created, the derived type class can be
174 defined. This structure is similar to the
175 [simple type](#simple-non-parametric-types), except for a bit more of the
176 functionality of `Type::TypeBase` is put to use.
178 ```c++
179 /// This class defines a parametric type. All derived types must inherit from
180 /// the CRTP class 'Type::TypeBase'. It takes as template parameters the
181 /// concrete type (ComplexType), the base class to use (Type), and the storage
182 /// class (ComplexTypeStorage). 'Type::TypeBase' also provides several utility
183 /// methods to simplify type construction and verification.
184 class ComplexType : public Type::TypeBase<ComplexType, Type,
185                                           ComplexTypeStorage> {
186 public:
187   /// Inherit some necessary constructors from 'TypeBase'.
188   using Base::Base;
190   /// This static method is used to support type inquiry through isa, cast,
191   /// and dyn_cast.
192   static bool kindof(unsigned kind) { return kind == MyTypes::Complex; }
194   /// This method is used to get an instance of the 'ComplexType'. This method
195   /// asserts that all of the construction invariants were satisfied. To
196   /// gracefully handle failed construction, getChecked should be used instead.
197   static ComplexType get(MLIRContext *context, unsigned param, Type type) {
198     // Call into a helper 'get' method in 'TypeBase' to get a uniqued instance
199     // of this type. All parameters to the storage class are passed after the
200     // type kind.
201     return Base::get(context, MyTypes::Complex, param, type);
202   }
204   /// This method is used to get an instance of the 'ComplexType', defined at
205   /// the given location. If any of the construction invariants are invalid,
206   /// errors are emitted with the provided location and a null type is returned.
207   /// Note: This method is completely optional.
208   static ComplexType getChecked(MLIRContext *context, unsigned param, Type type,
209                                 Location location) {
210     // Call into a helper 'getChecked' method in 'TypeBase' to get a uniqued
211     // instance of this type. All parameters to the storage class are passed
212     // after the type kind.
213     return Base::getChecked(location, context, MyTypes::Complex, param, type);
214   }
216   /// This method is used to verify the construction invariants passed into the
217   /// 'get' and 'getChecked' methods. Note: This method is completely optional.
218   static LogicalResult verifyConstructionInvariants(
219       llvm::Optional<Location> loc, MLIRContext *context, unsigned param,
220       Type type) {
221     // Our type only allows non-zero parameters.
222     if (param == 0) {
223       if (loc)
224         context->emitError(loc) << "non-zero parameter passed to 'ComplexType'";
225       return failure();
226     }
227     // Our type also expects an integer type.
228     if (!type.isa<IntegerType>()) {
229       if (loc)
230         context->emitError(loc) << "non integer-type passed to 'ComplexType'";
231       return failure();
232     }
233     return success();
234   }
236   /// Return the parameter value.
237   unsigned getParameter() {
238     // 'getImpl' returns a pointer to our internal storage instance.
239     return getImpl()->nonZeroParam;
240   }
242   /// Return the integer parameter type.
243   IntegerType getParameterType() {
244     // 'getImpl' returns a pointer to our internal storage instance.
245     return getImpl()->integerType;
246   }
250 ### Registering types with a Dialect
252 Once the dialect types have been defined, they must then be registered with a
253 `Dialect`. This is done via similar mechanism to
254 [operations](LangRef.md#operations), `addTypes`.
256 ```c++
257 struct MyDialect : public Dialect {
258   MyDialect(MLIRContext *context) : Dialect(/*name=*/"mydialect", context) {
259     /// Add these types to the dialect.
260     addTypes<SimpleType, ComplexType>();
261   }
265 ### Parsing and Printing
267 As a final step after registration, a dialect must override the `printType` and
268 `parseType` hooks. These enable native support for roundtripping the type in the
269 textual IR.
271 ## Attributes
273 As stated in the introduction, the process for defining dialect attributes is
274 nearly identical to that of defining dialect types. That key difference is that
275 the things named `*Type` are generally now named `*Attr`.
277 *   `Type::TypeBase` -> `Attribute::AttrBase`
278 *   `TypeStorageAllocator` -> `AttributeStorageAllocator`
279 *   `addTypes` -> `addAttributes`
281 Aside from that, all of the interfaces for uniquing and storage construction are
282 all the same.