MLIR  20.0.0git
Types.h
Go to the documentation of this file.
1 //===- Types.h - MLIR Type Classes ------------------------------*- 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 #ifndef MLIR_IR_TYPES_H
10 #define MLIR_IR_TYPES_H
11 
12 #include "mlir/IR/TypeSupport.h"
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/DenseMapInfo.h"
15 #include "llvm/Support/PointerLikeTypeTraits.h"
16 
17 namespace mlir {
18 class AsmState;
19 
20 /// Instances of the Type class are uniqued, have an immutable identifier and an
21 /// optional mutable component. They wrap a pointer to the storage object owned
22 /// by MLIRContext. Therefore, instances of Type are passed around by value.
23 ///
24 /// Some types are "primitives" meaning they do not have any parameters, for
25 /// example the Index type. Parametric types have additional information that
26 /// differentiates the types of the same class, for example the Integer type has
27 /// bitwidth, making i8 and i16 belong to the same kind by be different
28 /// instances of the IntegerType. Type parameters are part of the unique
29 /// immutable key. The mutable component of the type can be modified after the
30 /// type is created, but cannot affect the identity of the type.
31 ///
32 /// Types are constructed and uniqued via the 'detail::TypeUniquer' class.
33 ///
34 /// Derived type classes are expected to implement several required
35 /// implementation hooks:
36 /// * Optional:
37 /// - static LogicalResult verify(
38 /// function_ref<InFlightDiagnostic()> emitError,
39 /// Args... args)
40 /// * This method is invoked when calling the 'TypeBase::get/getChecked'
41 /// methods to ensure that the arguments passed in are valid to construct
42 /// a type instance with.
43 /// * This method is expected to return failure if a type cannot be
44 /// constructed with 'args', success otherwise.
45 /// * 'args' must correspond with the arguments passed into the
46 /// 'TypeBase::get' call.
47 ///
48 ///
49 /// Type storage objects inherit from TypeStorage and contain the following:
50 /// - The dialect that defined the type.
51 /// - Any parameters of the type.
52 /// - An optional mutable component.
53 /// For non-parametric types, a convenience DefaultTypeStorage is provided.
54 /// Parametric storage types must derive TypeStorage and respect the following:
55 /// - Define a type alias, KeyTy, to a type that uniquely identifies the
56 /// instance of the type.
57 /// * The key type must be constructible from the values passed into the
58 /// detail::TypeUniquer::get call.
59 /// * If the KeyTy does not have an llvm::DenseMapInfo specialization, the
60 /// storage class must define a hashing method:
61 /// 'static unsigned hashKey(const KeyTy &)'
62 ///
63 /// - Provide a method, 'bool operator==(const KeyTy &) const', to
64 /// compare the storage instance against an instance of the key type.
65 ///
66 /// - Provide a static construction method:
67 /// 'DerivedStorage *construct(TypeStorageAllocator &, const KeyTy &key)'
68 /// that builds a unique instance of the derived storage. The arguments to
69 /// this function are an allocator to store any uniqued data within the
70 /// context and the key type for this storage.
71 ///
72 /// - If they have a mutable component, this component must not be a part of
73 /// the key.
74 class Type {
75 public:
76  /// Utility class for implementing types.
77  template <typename ConcreteType, typename BaseType, typename StorageType,
78  template <typename T> class... Traits>
79  using TypeBase = detail::StorageUserBase<ConcreteType, BaseType, StorageType,
80  detail::TypeUniquer, Traits...>;
81 
83 
85 
86  constexpr Type() = default;
87  /* implicit */ Type(const ImplType *impl)
88  : impl(const_cast<ImplType *>(impl)) {}
89 
90  Type(const Type &other) = default;
91  Type &operator=(const Type &other) = default;
92 
93  bool operator==(Type other) const { return impl == other.impl; }
94  bool operator!=(Type other) const { return !(*this == other); }
95  explicit operator bool() const { return impl; }
96 
97  bool operator!() const { return impl == nullptr; }
98 
99  template <typename... Tys>
100  [[deprecated("Use mlir::isa<U>() instead")]]
101  bool isa() const;
102  template <typename... Tys>
103  [[deprecated("Use mlir::isa_and_nonnull<U>() instead")]]
104  bool isa_and_nonnull() const;
105  template <typename U>
106  [[deprecated("Use mlir::dyn_cast<U>() instead")]]
107  U dyn_cast() const;
108  template <typename U>
109  [[deprecated("Use mlir::dyn_cast_or_null<U>() instead")]]
110  U dyn_cast_or_null() const;
111  template <typename U>
112  [[deprecated("Use mlir::cast<U>() instead")]]
113  U cast() const;
114 
115  /// Return a unique identifier for the concrete type. This is used to support
116  /// dynamic type casting.
117  TypeID getTypeID() { return impl->getAbstractType().getTypeID(); }
118 
119  /// Return the MLIRContext in which this type was uniqued.
120  MLIRContext *getContext() const;
121 
122  /// Get the dialect this type is registered to.
123  Dialect &getDialect() const { return impl->getAbstractType().getDialect(); }
124 
125  // Convenience predicates. This is only for floating point types,
126  // derived types should use isa/dyn_cast.
127  bool isIndex() const;
128  bool isFloat8E5M2() const;
129  bool isFloat8E4M3() const;
130  bool isFloat8E4M3FN() const;
131  bool isFloat8E5M2FNUZ() const;
132  bool isFloat8E4M3FNUZ() const;
133  bool isFloat8E4M3B11FNUZ() const;
134  bool isBF16() const;
135  bool isF16() const;
136  bool isTF32() const;
137  bool isF32() const;
138  bool isF64() const;
139  bool isF80() const;
140  bool isF128() const;
141 
142  /// Return true if this is an integer type (with the specified width).
143  bool isInteger() const;
144  bool isInteger(unsigned width) const;
145  /// Return true if this is a signless integer type (with the specified width).
146  bool isSignlessInteger() const;
147  bool isSignlessInteger(unsigned width) const;
148  /// Return true if this is a signed integer type (with the specified width).
149  bool isSignedInteger() const;
150  bool isSignedInteger(unsigned width) const;
151  /// Return true if this is an unsigned integer type (with the specified
152  /// width).
153  bool isUnsignedInteger() const;
154  bool isUnsignedInteger(unsigned width) const;
155 
156  /// Return the bit width of an integer or a float type, assert failure on
157  /// other types.
158  unsigned getIntOrFloatBitWidth() const;
159 
160  /// Return true if this is a signless integer or index type.
161  bool isSignlessIntOrIndex() const;
162  /// Return true if this is a signless integer, index, or float type.
163  bool isSignlessIntOrIndexOrFloat() const;
164  /// Return true of this is a signless integer or a float type.
165  bool isSignlessIntOrFloat() const;
166 
167  /// Return true if this is an integer (of any signedness) or an index type.
168  bool isIntOrIndex() const;
169  /// Return true if this is an integer (of any signedness) or a float type.
170  bool isIntOrFloat() const;
171  /// Return true if this is an integer (of any signedness), index, or float
172  /// type.
173  bool isIntOrIndexOrFloat() const;
174 
175  /// Print the current type.
176  void print(raw_ostream &os) const;
177  void print(raw_ostream &os, AsmState &state) const;
178  void dump() const;
179 
180  friend ::llvm::hash_code hash_value(Type arg);
181 
182  /// Methods for supporting PointerLikeTypeTraits.
183  const void *getAsOpaquePointer() const {
184  return static_cast<const void *>(impl);
185  }
186  static Type getFromOpaquePointer(const void *pointer) {
187  return Type(reinterpret_cast<ImplType *>(const_cast<void *>(pointer)));
188  }
189 
190  /// Returns true if `InterfaceT` has been promised by the dialect or
191  /// implemented.
192  template <typename InterfaceT>
195  getDialect(), getTypeID(), InterfaceT::getInterfaceID()) ||
196  mlir::isa<InterfaceT>(*this);
197  }
198 
199  /// Returns true if the type was registered with a particular trait.
200  template <template <typename T> class Trait>
201  bool hasTrait() {
202  return getAbstractType().hasTrait<Trait>();
203  }
204 
205  /// Return the abstract type descriptor for this type.
206  const AbstractTy &getAbstractType() const { return impl->getAbstractType(); }
207 
208  /// Return the Type implementation.
209  ImplType *getImpl() const { return impl; }
210 
211  /// Walk all of the immediately nested sub-attributes and sub-types. This
212  /// method does not recurse into sub elements.
214  function_ref<void(Type)> walkTypesFn) const {
215  getAbstractType().walkImmediateSubElements(*this, walkAttrsFn, walkTypesFn);
216  }
217 
218  /// Replace the immediately nested sub-attributes and sub-types with those
219  /// provided. The order of the provided elements is derived from the order of
220  /// the elements returned by the callbacks of `walkImmediateSubElements`. The
221  /// element at index 0 would replace the very first attribute given by
222  /// `walkImmediateSubElements`. On success, the new instance with the values
223  /// replaced is returned. If replacement fails, nullptr is returned.
225  ArrayRef<Type> replTypes) const {
226  return getAbstractType().replaceImmediateSubElements(*this, replAttrs,
227  replTypes);
228  }
229 
230  /// Walk this type and all attibutes/types nested within using the
231  /// provided walk functions. See `AttrTypeWalker` for information on the
232  /// supported walk function types.
233  template <WalkOrder Order = WalkOrder::PostOrder, typename... WalkFns>
234  auto walk(WalkFns &&...walkFns) {
235  AttrTypeWalker walker;
236  (walker.addWalk(std::forward<WalkFns>(walkFns)), ...);
237  return walker.walk<Order>(*this);
238  }
239 
240  /// Recursively replace all of the nested sub-attributes and sub-types using
241  /// the provided map functions. Returns nullptr in the case of failure. See
242  /// `AttrTypeReplacer` for information on the support replacement function
243  /// types.
244  template <typename... ReplacementFns>
245  auto replace(ReplacementFns &&...replacementFns) {
246  AttrTypeReplacer replacer;
247  (replacer.addReplacement(std::forward<ReplacementFns>(replacementFns)),
248  ...);
249  return replacer.replace(*this);
250  }
251 
252 protected:
253  ImplType *impl{nullptr};
254 };
255 
256 inline raw_ostream &operator<<(raw_ostream &os, Type type) {
257  type.print(os);
258  return os;
259 }
260 
261 //===----------------------------------------------------------------------===//
262 // TypeTraitBase
263 //===----------------------------------------------------------------------===//
264 
265 namespace TypeTrait {
266 /// This class represents the base of a type trait.
267 template <typename ConcreteType, template <typename> class TraitType>
269 } // namespace TypeTrait
270 
271 //===----------------------------------------------------------------------===//
272 // TypeInterface
273 //===----------------------------------------------------------------------===//
274 
275 /// This class represents the base of a type interface. See the definition of
276 /// `detail::Interface` for requirements on the `Traits` type.
277 template <typename ConcreteType, typename Traits>
278 class TypeInterface : public detail::Interface<ConcreteType, Type, Traits, Type,
279  TypeTrait::TraitBase> {
280 public:
285 
286 protected:
287  /// Returns the impl interface instance for the given type.
288  static typename InterfaceBase::Concept *getInterfaceFor(Type type) {
289 #ifndef NDEBUG
290  // Check that the current interface isn't an unresolved promise for the
291  // given type.
293  type.getDialect(), type.getTypeID(), ConcreteType::getInterfaceID(),
294  llvm::getTypeName<ConcreteType>());
295 #endif
296 
297  return type.getAbstractType().getInterface<ConcreteType>();
298  }
299 
300  /// Allow access to 'getInterfaceFor'.
302 };
303 
304 //===----------------------------------------------------------------------===//
305 // Core TypeTrait
306 //===----------------------------------------------------------------------===//
307 
308 /// This trait is used to determine if a type is mutable or not. It is attached
309 /// on a type if the corresponding ImplType defines a `mutate` function with
310 /// a proper signature.
311 namespace TypeTrait {
312 template <typename ConcreteType>
314 } // namespace TypeTrait
315 
316 //===----------------------------------------------------------------------===//
317 // Type Utils
318 //===----------------------------------------------------------------------===//
319 
320 // Make Type hashable.
321 inline ::llvm::hash_code hash_value(Type arg) {
323 }
324 
325 template <typename... Tys>
326 bool Type::isa() const {
327  return llvm::isa<Tys...>(*this);
328 }
329 
330 template <typename... Tys>
331 bool Type::isa_and_nonnull() const {
332  return llvm::isa_and_present<Tys...>(*this);
333 }
334 
335 template <typename U>
336 U Type::dyn_cast() const {
337  return llvm::dyn_cast<U>(*this);
338 }
339 
340 template <typename U>
342  return llvm::dyn_cast_or_null<U>(*this);
343 }
344 
345 template <typename U>
346 U Type::cast() const {
347  return llvm::cast<U>(*this);
348 }
349 
350 } // namespace mlir
351 
352 namespace llvm {
353 
354 // Type hash just like pointers.
355 template <>
356 struct DenseMapInfo<mlir::Type> {
358  auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
359  return mlir::Type(static_cast<mlir::Type::ImplType *>(pointer));
360  }
363  return mlir::Type(static_cast<mlir::Type::ImplType *>(pointer));
364  }
365  static unsigned getHashValue(mlir::Type val) { return mlir::hash_value(val); }
366  static bool isEqual(mlir::Type LHS, mlir::Type RHS) { return LHS == RHS; }
367 };
368 template <typename T>
369 struct DenseMapInfo<T, std::enable_if_t<std::is_base_of<mlir::Type, T>::value &&
370  !mlir::detail::IsInterface<T>::value>>
371  : public DenseMapInfo<mlir::Type> {
372  static T getEmptyKey() {
373  const void *pointer = llvm::DenseMapInfo<const void *>::getEmptyKey();
374  return T::getFromOpaquePointer(pointer);
375  }
376  static T getTombstoneKey() {
378  return T::getFromOpaquePointer(pointer);
379  }
380 };
381 
382 /// We align TypeStorage by 8, so allow LLVM to steal the low bits.
383 template <>
384 struct PointerLikeTypeTraits<mlir::Type> {
385 public:
386  static inline void *getAsVoidPointer(mlir::Type I) {
387  return const_cast<void *>(I.getAsOpaquePointer());
388  }
389  static inline mlir::Type getFromVoidPointer(void *P) {
391  }
392  static constexpr int NumLowBitsAvailable = 3;
393 };
394 
395 /// Add support for llvm style casts.
396 /// We provide a cast between To and From if From is mlir::Type or derives from
397 /// it
398 template <typename To, typename From>
399 struct CastInfo<
400  To, From,
401  std::enable_if_t<std::is_same_v<mlir::Type, std::remove_const_t<From>> ||
402  std::is_base_of_v<mlir::Type, From>>>
404  DefaultDoCastIfPossible<To, From, CastInfo<To, From>> {
405  /// Arguments are taken as mlir::Type here and not as `From`, because when
406  /// casting from an intermediate type of the hierarchy to one of its children,
407  /// the val.getTypeID() inside T::classof will use the static getTypeID of the
408  /// parent instead of the non-static Type::getTypeID that returns the dynamic
409  /// ID. This means that T::classof would end up comparing the static TypeID of
410  /// the children to the static TypeID of its parent, making it impossible to
411  /// downcast from the parent to the child.
412  static inline bool isPossible(mlir::Type ty) {
413  /// Return a constant true instead of a dynamic true when casting to self or
414  /// up the hierarchy.
415  if constexpr (std::is_base_of_v<To, From>) {
416  return true;
417  } else {
418  return To::classof(ty);
419  };
420  }
421  static inline To doCast(mlir::Type ty) { return To(ty.getImpl()); }
422 };
423 
424 } // namespace llvm
425 
426 #endif // MLIR_IR_TYPES_H
This class contains all of the static information common to all instances of a registered Type.
Definition: TypeSupport.h:30
Type replaceImmediateSubElements(Type type, ArrayRef< Attribute > replAttrs, ArrayRef< Type > replTypes) const
Replace the immediate sub-elements of the given type.
Definition: Types.cpp:25
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
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:79
bool hasTrait() const
Returns true if the type has a particular trait.
Definition: TypeSupport.h:90
This class provides management for the lifetime of the state used when printing the IR.
Definition: AsmState.h:533
This is an attribute/type replacer that is naively cached.
Attribute replace(Attribute attr)
void addWalk(WalkFn< Attribute > &&fn)
Register a walk function for a given attribute or type.
WalkResult walk(T element)
Walk the given attribute/type, and recursively walk any sub elements.
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:60
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:104
This class represents the base of a type interface.
Definition: Types.h:279
static InterfaceBase::Concept * getInterfaceFor(Type type)
Returns the impl interface instance for the given type.
Definition: Types.h:288
friend InterfaceBase
Allow access to 'getInterfaceFor'.
Definition: Types.h:301
Base storage class appearing in a Type.
Definition: TypeSupport.h:166
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
void print(raw_ostream &os) const
Print the current type.
bool isF64() const
Definition: Types.cpp:53
const void * getAsOpaquePointer() const
Methods for supporting PointerLikeTypeTraits.
Definition: Types.h:183
bool isTF32() const
Definition: Types.cpp:51
U cast() const
Definition: Types.h:346
Dialect & getDialect() const
Get the dialect this type is registered to.
Definition: Types.h:123
auto replaceImmediateSubElements(ArrayRef< Attribute > replAttrs, ArrayRef< Type > replTypes) const
Replace the immediately nested sub-attributes and sub-types with those provided.
Definition: Types.h:224
Type(const Type &other)=default
bool isSignlessIntOrIndex() const
Return true if this is a signless integer or index type.
Definition: Types.cpp:104
U dyn_cast_or_null() const
Definition: Types.h:341
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition: Types.cpp:35
bool isa_and_nonnull() const
Definition: Types.h:331
bool isSignedInteger() const
Return true if this is a signed integer type (with the specified width).
Definition: Types.cpp:80
bool isFloat8E4M3FN() const
Definition: Types.cpp:39
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
Definition: Types.cpp:68
ImplType * impl
Definition: Types.h:253
friend ::llvm::hash_code hash_value(Type arg)
Definition: Types.h:321
static Type getFromOpaquePointer(const void *pointer)
Definition: Types.h:186
bool isIndex() const
Definition: Types.cpp:57
bool hasTrait()
Returns true if the type was registered with a particular trait.
Definition: Types.h:201
constexpr Type()=default
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
Definition: Types.cpp:124
U dyn_cast() const
Definition: Types.h:336
bool isF32() const
Definition: Types.cpp:52
void walkImmediateSubElements(function_ref< void(Attribute)> walkAttrsFn, function_ref< void(Type)> walkTypesFn) const
Walk all of the immediately nested sub-attributes and sub-types.
Definition: Types.h:213
bool hasPromiseOrImplementsInterface()
Returns true if InterfaceT has been promised by the dialect or implemented.
Definition: Types.h:193
bool isFloat8E4M3FNUZ() const
Definition: Types.cpp:43
bool isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
Definition: Types.cpp:92
const AbstractTy & getAbstractType() const
Return the abstract type descriptor for this type.
Definition: Types.h:206
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
Definition: Types.cpp:116
bool isFloat8E4M3B11FNUZ() const
Definition: Types.cpp:46
Type & operator=(const Type &other)=default
ImplType * getImpl() const
Return the Type implementation.
Definition: Types.h:209
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition: Types.cpp:59
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition: Types.cpp:120
Type(const ImplType *impl)
Definition: Types.h:87
bool isFloat8E5M2() const
Definition: Types.cpp:37
bool operator!() const
Definition: Types.h:97
bool operator==(Type other) const
Definition: Types.h:93
bool isF128() const
Definition: Types.cpp:55
TypeID getTypeID()
Return a unique identifier for the concrete type.
Definition: Types.h:117
void dump() const
bool operator!=(Type other) const
Definition: Types.h:94
bool isF16() const
Definition: Types.cpp:50
bool isF80() const
Definition: Types.cpp:54
bool isa() const
Definition: Types.h:326
auto replace(ReplacementFns &&...replacementFns)
Recursively replace all of the nested sub-attributes and sub-types using the provided map functions.
Definition: Types.h:245
auto walk(WalkFns &&...walkFns)
Walk this type and all attibutes/types nested within using the provided walk functions.
Definition: Types.h:234
bool isSignlessIntOrFloat() const
Return true of this is a signless integer or a float type.
Definition: Types.cpp:112
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition: Types.cpp:126
bool isBF16() const
Definition: Types.cpp:49
bool isFloat8E4M3() const
Definition: Types.cpp:38
bool isFloat8E5M2FNUZ() const
Definition: Types.cpp:40
bool isSignlessIntOrIndexOrFloat() const
Return true if this is a signless integer, index, or float type.
Definition: Types.cpp:108
void addReplacement(ReplaceFn< Attribute > fn)
Register a replacement function for mapping a given attribute or type.
This class represents an abstract interface.
Interface< ConcreteType, Type, Traits, Type, TypeTrait::TraitBase > InterfaceBase
Utility class for implementing users of storage classes uniqued by a StorageUniquer.
Helper class for implementing traits for storage classes.
Include the generated interface declarations.
Definition: CallGraph.h:229
bool hasPromisedInterface(Dialect &dialect, TypeID interfaceRequestorID, TypeID interfaceID)
Checks if a promise has been made for the interface/requestor pair.
Definition: Dialect.cpp:166
void handleUseOfUndefinedPromisedInterface(Dialect &dialect, TypeID interfaceRequestorID, TypeID interfaceID, StringRef interfaceName)
Checks if the given interface, which is attempting to be used, is a promised interface of this dialec...
Definition: Dialect.cpp:153
Include the generated interface declarations.
WalkOrder
Traversal order for region, block and operation walk utilities.
Definition: Visitors.h:62
inline ::llvm::hash_code hash_value(AffineExpr arg)
Make AffineExpr hashable.
Definition: AffineExpr.h:260
raw_ostream & operator<<(raw_ostream &os, const AliasResult &result)
Definition: AliasAnalysis.h:78
static bool isPossible(mlir::Type ty)
Arguments are taken as mlir::Type here and not as From, because when casting from an intermediate typ...
Definition: Types.h:412
static mlir::Type getEmptyKey()
Definition: Types.h:357
static unsigned getHashValue(mlir::Type val)
Definition: Types.h:365
static mlir::Type getTombstoneKey()
Definition: Types.h:361
static bool isEqual(mlir::Type LHS, mlir::Type RHS)
Definition: Types.h:366
static void * getAsVoidPointer(mlir::Type I)
Definition: Types.h:386
static mlir::Type getFromVoidPointer(void *P)
Definition: Types.h:389
This trait is used to determine if a storage user, like Type, is mutable or not.
A utility class to get, or create, unique instances of types within an MLIRContext.
Definition: TypeSupport.h:210