MLIR 24.0.0git
TypeSupport.h
Go to the documentation of this file.
1//===- TypeSupport.h --------------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines support types for registering dialect extended types.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_IR_TYPESUPPORT_H
14#define MLIR_IR_TYPESUPPORT_H
15
16#include "mlir/IR/MLIRContext.h"
18#include "llvm/ADT/Twine.h"
19
20namespace mlir {
21class Dialect;
22class MLIRContext;
23
24//===----------------------------------------------------------------------===//
25// AbstractType
26//===----------------------------------------------------------------------===//
27
28/// This class contains all of the static information common to all instances of
29/// a registered Type.
30class AbstractType {
31public:
32 using HasTraitFn = llvm::unique_function<bool(TypeID) const>;
37
38 /// Look up the specified abstract type in the MLIRContext and return a
39 /// reference to it.
40 static const AbstractType &lookup(TypeID typeID, MLIRContext *context);
41
42 /// Look up the specified abstract type in the MLIRContext and return a
43 /// reference to it if it exists.
44 static std::optional<std::reference_wrapper<const AbstractType>>
45 lookup(StringRef name, MLIRContext *context);
46
47 /// This method is used by Dialect objects when they register the list of
48 /// types they contain.
49 template <typename T>
50 static AbstractType get(Dialect &dialect) {
51 return AbstractType(dialect, T::getInterfaceMap(), T::getHasTraitFn(),
52 T::getWalkImmediateSubElementsFn(),
53 T::getReplaceImmediateSubElementsFn(), T::getTypeID(),
54 T::name);
55 }
56
57 /// Register the type `T` with `dialect`.
58 template <typename T>
59 static void insert(Dialect &dialect);
60
61 /// This method is used by Dialect objects to register types with
62 /// custom TypeIDs.
63 /// The use of this method is in general discouraged in favor of
64 /// 'get<CustomType>(dialect)';
65 static AbstractType
66 get(Dialect &dialect, detail::InterfaceMap &&interfaceMap,
68 WalkImmediateSubElementsFn walkImmediateSubElementsFn,
69 ReplaceImmediateSubElementsFn replaceImmediateSubElementsFn,
70 TypeID typeID, StringRef name) {
71 return AbstractType(dialect, std::move(interfaceMap), std::move(hasTrait),
72 walkImmediateSubElementsFn,
73 replaceImmediateSubElementsFn, typeID, name);
74 }
75
76 /// Return the dialect this type was registered to.
77 Dialect &getDialect() const { return const_cast<Dialect &>(dialect); }
78
79 /// Returns an instance of the concept object for the given interface if it
80 /// was registered to this type, null otherwise. This should not be used
81 /// directly.
82 template <typename T>
83 typename T::Concept *getInterface() const {
84 return interfaceMap.lookup<T>();
85 }
86
87 /// Returns true if the type has the interface with the given ID.
88 bool hasInterface(TypeID interfaceID) const {
89 return interfaceMap.contains(interfaceID);
90 }
91
92 /// Returns true if the type has a particular trait.
93 template <template <typename T> class Trait>
94 bool hasTrait() const {
95 return hasTraitFn(TypeID::get<Trait>());
96 }
97
98 /// Returns true if the type has a particular trait.
99 bool hasTrait(TypeID traitID) const { return hasTraitFn(traitID); }
100
101 /// Walk the immediate sub-elements of the given type.
103 function_ref<void(Attribute)> walkAttrsFn,
104 function_ref<void(Type)> walkTypesFn) const;
105
106 /// Replace the immediate sub-elements of the given type.
108 ArrayRef<Type> replTypes) const;
109
110 /// Return the unique identifier representing the concrete type class.
111 TypeID getTypeID() const { return typeID; }
112
113 /// Return the unique name representing the type.
114 StringRef getName() const { return name; }
115
116private:
117 /// Registers `typeInfo` with `dialect` and returns the context of `dialect`.
118 /// This is the part of `insert<T>` that requires the definition of `Dialect`.
119 static MLIRContext *insert(Dialect &dialect, AbstractType &&typeInfo);
120
121 AbstractType(Dialect &dialect, detail::InterfaceMap &&interfaceMap,
123 WalkImmediateSubElementsFn walkImmediateSubElementsFn,
124 ReplaceImmediateSubElementsFn replaceImmediateSubElementsFn,
125 TypeID typeID, StringRef name)
126 : dialect(dialect), interfaceMap(std::move(interfaceMap)),
127 hasTraitFn(std::move(hasTrait)),
128 walkImmediateSubElementsFn(walkImmediateSubElementsFn),
129 replaceImmediateSubElementsFn(replaceImmediateSubElementsFn),
130 typeID(typeID), name(name) {}
131
132 /// Give StorageUserBase access to the mutable lookup.
133 template <typename ConcreteT, typename BaseT, typename StorageT,
134 typename UniquerT, template <typename T> class... Traits>
136
137 /// Look up the specified abstract type in the MLIRContext and return a
138 /// (mutable) pointer to it. Return a null pointer if the type could not
139 /// be found in the context.
140 static AbstractType *lookupMutable(TypeID typeID, MLIRContext *context);
141
142 /// This is the dialect that this type was registered to.
143 const Dialect &dialect;
144
145 /// This is a collection of the interfaces registered to this type.
146 detail::InterfaceMap interfaceMap;
147
148 /// Function to check if the type has a particular trait.
149 HasTraitFn hasTraitFn;
150
151 /// Function to walk the immediate sub-elements of this type.
152 WalkImmediateSubElementsFn walkImmediateSubElementsFn;
153
154 /// Function to replace the immediate sub-elements of this type.
155 ReplaceImmediateSubElementsFn replaceImmediateSubElementsFn;
156
157 /// The unique identifier of the derived Type class.
158 const TypeID typeID;
159
160 /// The unique name of this type. The string is not owned by the context, so
161 /// The lifetime of this string should outlive the MLIR context.
162 const StringRef name;
163};
164
165//===----------------------------------------------------------------------===//
166// TypeStorage
167//===----------------------------------------------------------------------===//
168
169namespace detail {
170struct TypeUniquer;
171} // namespace detail
172
173/// Base storage class appearing in a Type.
175 friend detail::TypeUniquer;
176 friend StorageUniquer;
177
178public:
179 /// Return the abstract type descriptor for this type.
181 assert(abstractType && "Malformed type storage object.");
182 return *abstractType;
183 }
184
185protected:
186 /// This constructor is used by derived classes as part of the TypeUniquer.
188
189private:
190 /// Set the abstract type for this storage instance. This is used by the
191 /// TypeUniquer when initializing a newly constructed type storage object.
192 void initialize(const AbstractType &abstractTy) {
193 abstractType = const_cast<AbstractType *>(&abstractTy);
194 }
195
196 /// The abstract description for this type.
197 AbstractType *abstractType{nullptr};
198};
199
200/// Default storage type for types that require no additional initialization or
201/// storage.
203
204//===----------------------------------------------------------------------===//
205// TypeStorageAllocator
206//===----------------------------------------------------------------------===//
207
208/// This is a utility allocator used to allocate memory for instances of derived
209/// Types.
211
212//===----------------------------------------------------------------------===//
213// TypeUniquer
214//===----------------------------------------------------------------------===//
215namespace detail {
216/// A utility class to get, or create, unique instances of types within an
217/// MLIRContext. This class manages all creation and uniquing of types.
219 /// Get an uniqued instance of a type T.
220 template <typename T, typename... Args>
221 static T get(MLIRContext *ctx, Args &&...args) {
222 return getWithTypeID<T, Args...>(ctx, T::getTypeID(),
223 std::forward<Args>(args)...);
224 }
225
226 /// Get an uniqued instance of a parametric type T.
227 /// The use of this method is in general discouraged in favor of
228 /// 'get<T, Args>(ctx, args)'.
229 template <typename T, typename... Args>
230 static std::enable_if_t<
231 !std::is_same<typename T::ImplType, TypeStorage>::value, T>
232 getWithTypeID(MLIRContext *ctx, TypeID typeID, Args &&...args) {
233#ifndef NDEBUG
235 llvm::report_fatal_error(
236 llvm::Twine("can't create type '") + llvm::getTypeName<T>() +
237 "' because storage uniquer isn't initialized: the dialect was likely "
238 "not loaded, or the type wasn't added with addTypes<...>() "
239 "in the Dialect::initialize() method.");
240#endif
241 return ctx->getTypeUniquer().get<typename T::ImplType>(
242 [&, typeID](TypeStorage *storage) {
243 storage->initialize(AbstractType::lookup(typeID, ctx));
244 },
245 typeID, std::forward<Args>(args)...);
246 }
247 /// Get an uniqued instance of a singleton type T.
248 /// The use of this method is in general discouraged in favor of
249 /// 'get<T, Args>(ctx, args)'.
250 template <typename T>
251 static std::enable_if_t<
252 std::is_same<typename T::ImplType, TypeStorage>::value, T>
254#ifndef NDEBUG
256 llvm::report_fatal_error(
257 llvm::Twine("can't create type '") + llvm::getTypeName<T>() +
258 "' because storage uniquer isn't initialized: the dialect was likely "
259 "not loaded, or the type wasn't added with addTypes<...>() "
260 "in the Dialect::initialize() method.");
261#endif
262 return ctx->getTypeUniquer().get<typename T::ImplType>(typeID);
263 }
264
265 /// Change the mutable component of the given type instance in the provided
266 /// context.
267 template <typename T, typename... Args>
268 static LogicalResult mutate(MLIRContext *ctx, typename T::ImplType *impl,
269 Args &&...args) {
270 assert(impl && "cannot mutate null type");
271 return ctx->getTypeUniquer().mutate(T::getTypeID(), impl,
272 std::forward<Args>(args)...);
273 }
274
275 /// Register a type instance T with the uniquer.
276 template <typename T>
277 static void registerType(MLIRContext *ctx) {
278 registerType<T>(ctx, T::getTypeID());
279 }
280
281 /// Register a parametric type instance T with the uniquer.
282 /// The use of this method is in general discouraged in favor of
283 /// 'registerType<T>(ctx)'.
284 template <typename T>
285 static std::enable_if_t<
286 !std::is_same<typename T::ImplType, TypeStorage>::value>
288 ctx->getTypeUniquer().registerParametricStorageType<typename T::ImplType>(
289 typeID);
290 }
291 /// Register a singleton type instance T with the uniquer.
292 /// The use of this method is in general discouraged in favor of
293 /// 'registerType<T>(ctx)'.
294 template <typename T>
295 static std::enable_if_t<
296 std::is_same<typename T::ImplType, TypeStorage>::value>
299 typeID, [&ctx, typeID](TypeStorage *storage) {
300 storage->initialize(AbstractType::lookup(typeID, ctx));
301 });
302 }
303};
304} // namespace detail
305
306template <typename T>
308 MLIRContext *context = insert(dialect, get<T>(dialect));
310}
311} // namespace mlir
312
313#endif
LogicalResult initialize(unsigned origNumLoops, ArrayRef< ReassociationIndices > foldedIterationDims)
This class contains all of the static information common to all instances of a registered Type.
Definition TypeSupport.h:30
function_ref< void( Type, function_ref< void(Attribute)>, function_ref< void(Type)>)> WalkImmediateSubElementsFn
Definition TypeSupport.h:33
Type replaceImmediateSubElements(Type type, ArrayRef< Attribute > replAttrs, ArrayRef< Type > replTypes) const
Replace the immediate sub-elements of the given type.
Definition Types.cpp:25
T::Concept * getInterface() const
Returns an instance of the concept object for the given interface if it was registered to this type,...
Definition TypeSupport.h:83
static AbstractType get(Dialect &dialect)
This method is used by Dialect objects when they register the list of types they contain.
Definition TypeSupport.h:50
static void insert(Dialect &dialect)
Register the type T with dialect.
static const AbstractType & lookup(TypeID typeID, MLIRContext *context)
Look up the specified abstract type in the MLIRContext and return a reference to it.
bool hasInterface(TypeID interfaceID) const
Returns true if the type has the interface with the given ID.
Definition TypeSupport.h:88
void walkImmediateSubElements(Type type, function_ref< void(Attribute)> walkAttrsFn, function_ref< void(Type)> walkTypesFn) const
Walk the immediate sub-elements of the given type.
Definition Types.cpp:19
function_ref< Type(Type, ArrayRef< Attribute >, ArrayRef< Type >)> ReplaceImmediateSubElementsFn
Definition TypeSupport.h:35
TypeID getTypeID() const
Return the unique identifier representing the concrete type class.
bool hasTrait() const
Returns true if the type has a particular trait.
Definition TypeSupport.h:94
llvm::unique_function< bool(TypeID) const > HasTraitFn
Definition TypeSupport.h:32
bool hasTrait(TypeID traitID) const
Returns true if the type has a particular trait.
Definition TypeSupport.h:99
Dialect & getDialect() const
Return the dialect this type was registered to.
Definition TypeSupport.h:77
StringRef getName() const
Return the unique name representing the type.
static AbstractType get(Dialect &dialect, detail::InterfaceMap &&interfaceMap, HasTraitFn &&hasTrait, WalkImmediateSubElementsFn walkImmediateSubElementsFn, ReplaceImmediateSubElementsFn replaceImmediateSubElementsFn, TypeID typeID, StringRef name)
This method is used by Dialect objects to register types with custom TypeIDs.
Definition TypeSupport.h:66
Attributes are known-constant values of operations.
Definition Attributes.h:25
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition Dialect.h:38
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
StorageUniquer & getTypeUniquer()
Returns the storage uniquer used for constructing type storage instances.
This class acts as the base storage that all storage classes must derived from.
This is a utility allocator used to allocate memory for instances of derived types.
LogicalResult mutate(TypeID id, Storage *storage, Args &&...args)
Changes the mutable component of 'storage' by forwarding the trailing arguments to the 'mutate' funct...
void registerSingletonStorageType(TypeID id, function_ref< void(Storage *)> initFn)
Register a new singleton storage class, this is necessary to get the singletone instance.
Storage * get(function_ref< void(Storage *)> initFn, TypeID id, Args &&...args)
Gets a uniqued instance of 'Storage'.
bool isSingletonStorageInitialized(TypeID id)
Test if there is a singleton storage uniquer initialized for the provided TypeID.
bool isParametricStorageInitialized(TypeID id)
Test if there is a parametric storage uniquer initialized for the provided TypeID.
void registerParametricStorageType(TypeID id)
Register a new parametric storage class, this is necessary to create instances of this class type.
This class provides an efficient unique identifier for a specific C++ type.
Definition TypeID.h:107
static TypeID get()
Construct a type info object for the given type T.
Definition TypeID.h:245
Base storage class appearing in a Type.
TypeStorage()
This constructor is used by derived classes as part of the TypeUniquer.
const AbstractType & getAbstractType()
Return the abstract type descriptor for this type.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an efficient mapping between a given Interface type, and a particular implementat...
Utility class for implementing users of storage classes uniqued by a StorageUniquer.
AttrTypeReplacer.
Include the generated interface declarations.
StorageUniquer::StorageAllocator TypeStorageAllocator
This is a utility allocator used to allocate memory for instances of derived Types.
TypeStorage DefaultTypeStorage
Default storage type for types that require no additional initialization or storage.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
A utility class to get, or create, unique instances of types within an MLIRContext.
static T get(MLIRContext *ctx, Args &&...args)
Get an uniqued instance of a type T.
static std::enable_if_t< std::is_same< typename T::ImplType, TypeStorage >::value, T > getWithTypeID(MLIRContext *ctx, TypeID typeID)
Get an uniqued instance of a singleton type T.
static LogicalResult mutate(MLIRContext *ctx, typename T::ImplType *impl, Args &&...args)
Change the mutable component of the given type instance in the provided context.
static std::enable_if_t< !std::is_same< typename T::ImplType, TypeStorage >::value > registerType(MLIRContext *ctx, TypeID typeID)
Register a parametric type instance T with the uniquer.
static std::enable_if_t< !std::is_same< typename T::ImplType, TypeStorage >::value, T > getWithTypeID(MLIRContext *ctx, TypeID typeID, Args &&...args)
Get an uniqued instance of a parametric type T.
static void registerType(MLIRContext *ctx)
Register a type instance T with the uniquer.
static std::enable_if_t< std::is_same< typename T::ImplType, TypeStorage >::value > registerType(MLIRContext *ctx, TypeID typeID)
Register a singleton type instance T with the uniquer.