MLIR  17.0.0git
Attributes.h
Go to the documentation of this file.
1 //===- Attributes.h - MLIR Attribute 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_ATTRIBUTES_H
10 #define MLIR_IR_ATTRIBUTES_H
11 
13 #include "llvm/Support/PointerLikeTypeTraits.h"
14 
15 namespace mlir {
16 class AsmState;
17 class StringAttr;
18 
19 /// Attributes are known-constant values of operations.
20 ///
21 /// Instances of the Attribute class are references to immortal key-value pairs
22 /// with immutable, uniqued keys owned by MLIRContext. As such, an Attribute is
23 /// a thin wrapper around an underlying storage pointer. Attributes are usually
24 /// passed by value.
25 class Attribute {
26 public:
27  /// Utility class for implementing attributes.
28  template <typename ConcreteType, typename BaseType, typename StorageType,
29  template <typename T> class... Traits>
30  using AttrBase = detail::StorageUserBase<ConcreteType, BaseType, StorageType,
31  detail::AttributeUniquer, Traits...>;
32 
34  using ValueType = void;
36 
37  constexpr Attribute() = default;
38  /* implicit */ Attribute(const ImplType *impl)
39  : impl(const_cast<ImplType *>(impl)) {}
40 
41  Attribute(const Attribute &other) = default;
42  Attribute &operator=(const Attribute &other) = default;
43 
44  bool operator==(Attribute other) const { return impl == other.impl; }
45  bool operator!=(Attribute other) const { return !(*this == other); }
46  explicit operator bool() const { return impl; }
47 
48  bool operator!() const { return impl == nullptr; }
49 
50  /// Casting utility functions. These are deprecated and will be removed,
51  /// please prefer using the `llvm` namespace variants instead.
52  template <typename... Tys>
53  bool isa() const;
54  template <typename... Tys>
55  bool isa_and_nonnull() const;
56  template <typename U>
57  U dyn_cast() const;
58  template <typename U>
59  U dyn_cast_or_null() const;
60  template <typename U>
61  U cast() const;
62 
63  // Support dyn_cast'ing Attribute to itself.
64  static bool classof(Attribute) { return true; }
65 
66  /// Return a unique identifier for the concrete attribute type. This is used
67  /// to support dynamic type casting.
68  TypeID getTypeID() { return impl->getAbstractAttribute().getTypeID(); }
69 
70  /// Return the context this attribute belongs to.
71  MLIRContext *getContext() const;
72 
73  /// Get the dialect this attribute is registered to.
74  Dialect &getDialect() const {
75  return impl->getAbstractAttribute().getDialect();
76  }
77 
78  /// Print the attribute. If `elideType` is set, the attribute is printed
79  /// without a trailing colon type if it has one.
80  void print(raw_ostream &os, bool elideType = false) const;
81  void print(raw_ostream &os, AsmState &state, bool elideType = false) const;
82  void dump() const;
83 
84  /// Get an opaque pointer to the attribute.
85  const void *getAsOpaquePointer() const { return impl; }
86  /// Construct an attribute from the opaque pointer representation.
87  static Attribute getFromOpaquePointer(const void *ptr) {
88  return Attribute(reinterpret_cast<const ImplType *>(ptr));
89  }
90 
91  friend ::llvm::hash_code hash_value(Attribute arg);
92 
93  /// Returns true if the type was registered with a particular trait.
94  template <template <typename T> class Trait>
95  bool hasTrait() {
96  return getAbstractAttribute().hasTrait<Trait>();
97  }
98 
99  /// Return the abstract descriptor for this attribute.
101  return impl->getAbstractAttribute();
102  }
103 
104  /// Walk all of the immediately nested sub-attributes and sub-types. This
105  /// method does not recurse into sub elements.
107  function_ref<void(Type)> walkTypesFn) const {
108  getAbstractAttribute().walkImmediateSubElements(*this, walkAttrsFn,
109  walkTypesFn);
110  }
111 
112  /// Replace the immediately nested sub-attributes and sub-types with those
113  /// provided. The order of the provided elements is derived from the order of
114  /// the elements returned by the callbacks of `walkImmediateSubElements`. The
115  /// element at index 0 would replace the very first attribute given by
116  /// `walkImmediateSubElements`. On success, the new instance with the values
117  /// replaced is returned. If replacement fails, nullptr is returned.
119  ArrayRef<Type> replTypes) const {
120  return getAbstractAttribute().replaceImmediateSubElements(*this, replAttrs,
121  replTypes);
122  }
123 
124  /// Walk this attribute and all attibutes/types nested within using the
125  /// provided walk functions. See `AttrTypeWalker` for information on the
126  /// supported walk function types.
127  template <WalkOrder Order = WalkOrder::PostOrder, typename... WalkFns>
128  auto walk(WalkFns &&...walkFns) {
129  AttrTypeWalker walker;
130  (walker.addWalk(std::forward<WalkFns>(walkFns)), ...);
131  return walker.walk<Order>(*this);
132  }
133 
134  /// Recursively replace all of the nested sub-attributes and sub-types using
135  /// the provided map functions. Returns nullptr in the case of failure. See
136  /// `AttrTypeReplacer` for information on the support replacement function
137  /// types.
138  template <typename... ReplacementFns>
139  auto replace(ReplacementFns &&...replacementFns) {
140  AttrTypeReplacer replacer;
141  (replacer.addReplacement(std::forward<ReplacementFns>(replacementFns)),
142  ...);
143  return replacer.replace(*this);
144  }
145 
146  /// Return the internal Attribute implementation.
147  ImplType *getImpl() const { return impl; }
148 
149 protected:
150  ImplType *impl{nullptr};
151 };
152 
153 inline raw_ostream &operator<<(raw_ostream &os, Attribute attr) {
154  attr.print(os);
155  return os;
156 }
157 
158 template <typename... Tys>
159 bool Attribute::isa() const {
160  return llvm::isa<Tys...>(*this);
161 }
162 
163 template <typename... Tys>
165  return llvm::isa_and_present<Tys...>(*this);
166 }
167 
168 template <typename U>
170  return llvm::dyn_cast<U>(*this);
171 }
172 
173 template <typename U>
175  return llvm::dyn_cast_if_present<U>(*this);
176 }
177 
178 template <typename U>
179 U Attribute::cast() const {
180  return llvm::cast<U>(*this);
181 }
182 
183 inline ::llvm::hash_code hash_value(Attribute arg) {
185 }
186 
187 //===----------------------------------------------------------------------===//
188 // NamedAttribute
189 //===----------------------------------------------------------------------===//
190 
191 /// NamedAttribute represents a combination of a name and an Attribute value.
193 public:
194  NamedAttribute(StringAttr name, Attribute value);
195 
196  /// Return the name of the attribute.
197  StringAttr getName() const;
198 
199  /// Return the dialect of the name of this attribute, if the name is prefixed
200  /// by a dialect namespace. For example, `llvm.fast_math` would return the
201  /// LLVM dialect (if it is loaded). Returns nullptr if the dialect isn't
202  /// loaded, or if the name is not prefixed by a dialect namespace.
203  Dialect *getNameDialect() const;
204 
205  /// Return the value of the attribute.
206  Attribute getValue() const { return value; }
207 
208  /// Set the name of this attribute.
209  void setName(StringAttr newName);
210 
211  /// Set the value of this attribute.
212  void setValue(Attribute newValue) {
213  assert(value && "expected valid attribute value");
214  value = newValue;
215  }
216 
217  /// Compare this attribute to the provided attribute, ordering by name.
218  bool operator<(const NamedAttribute &rhs) const;
219  /// Compare this attribute to the provided string, ordering by name.
220  bool operator<(StringRef rhs) const;
221 
222  bool operator==(const NamedAttribute &rhs) const {
223  return name == rhs.name && value == rhs.value;
224  }
225  bool operator!=(const NamedAttribute &rhs) const { return !(*this == rhs); }
226 
227 private:
228  NamedAttribute(Attribute name, Attribute value) : name(name), value(value) {}
229 
230  /// Allow access to internals to enable hashing.
231  friend ::llvm::hash_code hash_value(const NamedAttribute &arg);
232  friend DenseMapInfo<NamedAttribute>;
233 
234  /// The name of the attribute. This is represented as a StringAttr, but
235  /// type-erased to Attribute in the field.
236  Attribute name;
237  /// The value of the attribute.
238  Attribute value;
239 };
240 
241 inline ::llvm::hash_code hash_value(const NamedAttribute &arg) {
242  using AttrPairT = std::pair<Attribute, Attribute>;
243  return DenseMapInfo<AttrPairT>::getHashValue(AttrPairT(arg.name, arg.value));
244 }
245 
246 /// Allow walking and replacing the subelements of a NamedAttribute.
247 template <>
249  template <typename T>
250  static void walk(T param, AttrTypeImmediateSubElementWalker &walker) {
251  walker.walk(param.getName());
252  walker.walk(param.getValue());
253  }
254  template <typename T>
255  static T replace(T param, AttrSubElementReplacements &attrRepls,
256  TypeSubElementReplacements &typeRepls) {
257  ArrayRef<Attribute> paramRepls = attrRepls.take_front(2);
258  return T(cast<decltype(param.getName())>(paramRepls[0]), paramRepls[1]);
259  }
260 };
261 
262 //===----------------------------------------------------------------------===//
263 // AttributeTraitBase
264 //===----------------------------------------------------------------------===//
265 
266 namespace AttributeTrait {
267 /// This class represents the base of an attribute trait.
268 template <typename ConcreteType, template <typename> class TraitType>
270 } // namespace AttributeTrait
271 
272 //===----------------------------------------------------------------------===//
273 // AttributeInterface
274 //===----------------------------------------------------------------------===//
275 
276 /// This class represents the base of an attribute interface. See the definition
277 /// of `detail::Interface` for requirements on the `Traits` type.
278 template <typename ConcreteType, typename Traits>
280  : public detail::Interface<ConcreteType, Attribute, Traits, Attribute,
281  AttributeTrait::TraitBase> {
282 public:
284  using InterfaceBase = detail::Interface<ConcreteType, Attribute, Traits,
287 
288 private:
289  /// Returns the impl interface instance for the given type.
290  static typename InterfaceBase::Concept *getInterfaceFor(Attribute attr) {
291  return attr.getAbstractAttribute().getInterface<ConcreteType>();
292  }
293 
294  /// Allow access to 'getInterfaceFor'.
295  friend InterfaceBase;
296 };
297 
298 //===----------------------------------------------------------------------===//
299 // Core AttributeTrait
300 //===----------------------------------------------------------------------===//
301 
302 /// This trait is used to determine if an attribute is mutable or not. It is
303 /// attached on an attribute if the corresponding ImplType defines a `mutate`
304 /// function with proper signature.
305 namespace AttributeTrait {
306 template <typename ConcreteType>
308 } // namespace AttributeTrait
309 
310 } // namespace mlir.
311 
312 namespace llvm {
313 
314 // Attribute hash just like pointers.
315 template <>
316 struct DenseMapInfo<mlir::Attribute> {
318  auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
319  return mlir::Attribute(static_cast<mlir::Attribute::ImplType *>(pointer));
320  }
323  return mlir::Attribute(static_cast<mlir::Attribute::ImplType *>(pointer));
324  }
325  static unsigned getHashValue(mlir::Attribute val) {
326  return mlir::hash_value(val);
327  }
328  static bool isEqual(mlir::Attribute LHS, mlir::Attribute RHS) {
329  return LHS == RHS;
330  }
331 };
332 template <typename T>
334  T, std::enable_if_t<std::is_base_of<mlir::Attribute, T>::value &&
335  !mlir::detail::IsInterface<T>::value>>
336  : public DenseMapInfo<mlir::Attribute> {
337  static T getEmptyKey() {
338  const void *pointer = llvm::DenseMapInfo<const void *>::getEmptyKey();
339  return T::getFromOpaquePointer(pointer);
340  }
341  static T getTombstoneKey() {
343  return T::getFromOpaquePointer(pointer);
344  }
345 };
346 
347 /// Allow LLVM to steal the low bits of Attributes.
348 template <>
349 struct PointerLikeTypeTraits<mlir::Attribute> {
350  static inline void *getAsVoidPointer(mlir::Attribute attr) {
351  return const_cast<void *>(attr.getAsOpaquePointer());
352  }
353  static inline mlir::Attribute getFromVoidPointer(void *ptr) {
355  }
356  static constexpr int NumLowBitsAvailable = llvm::PointerLikeTypeTraits<
357  mlir::AttributeStorage *>::NumLowBitsAvailable;
358 };
359 
360 template <>
361 struct DenseMapInfo<mlir::NamedAttribute> {
364  return mlir::NamedAttribute(emptyAttr, emptyAttr);
365  }
368  return mlir::NamedAttribute(tombAttr, tombAttr);
369  }
370  static unsigned getHashValue(mlir::NamedAttribute val) {
371  return mlir::hash_value(val);
372  }
374  return lhs == rhs;
375  }
376 };
377 
378 /// Add support for llvm style casts. We provide a cast between To and From if
379 /// From is mlir::Attribute or derives from it.
380 template <typename To, typename From>
381 struct CastInfo<To, From,
382  std::enable_if_t<std::is_same_v<mlir::Attribute,
383  std::remove_const_t<From>> ||
384  std::is_base_of_v<mlir::Attribute, From>>>
386  DefaultDoCastIfPossible<To, From, CastInfo<To, From>> {
387  /// Arguments are taken as mlir::Attribute here and not as `From`, because
388  /// when casting from an intermediate type of the hierarchy to one of its
389  /// children, the val.getTypeID() inside T::classof will use the static
390  /// getTypeID of the parent instead of the non-static Type::getTypeID that
391  /// returns the dynamic ID. This means that T::classof would end up comparing
392  /// the static TypeID of the children to the static TypeID of its parent,
393  /// making it impossible to downcast from the parent to the child.
394  static inline bool isPossible(mlir::Attribute ty) {
395  /// Return a constant true instead of a dynamic true when casting to self or
396  /// up the hierarchy.
397  return std::is_same_v<To, std::remove_const_t<From>> ||
398  std::is_base_of_v<To, From> || To::classof(ty);
399  }
400  static inline To doCast(mlir::Attribute attr) { return To(attr.getImpl()); }
401 };
402 
403 } // namespace llvm
404 
405 #endif
This class contains all of the static information common to all instances of a registered Attribute.
T::Concept * getInterface() const
Returns an instance of the concept object for the given interface if it was registered to this attrib...
bool hasTrait() const
Returns true if the attribute has a particular trait.
void walkImmediateSubElements(Attribute attr, function_ref< void(Attribute)> walkAttrsFn, function_ref< void(Type)> walkTypesFn) const
Walk the immediate sub-elements of this attribute.
Definition: Attributes.cpp:19
Attribute replaceImmediateSubElements(Attribute attr, ArrayRef< Attribute > replAttrs, ArrayRef< Type > replTypes) const
Replace the immediate sub-elements of this attribute.
Definition: Attributes.cpp:26
This class provides management for the lifetime of the state used when printing the IR.
Definition: AsmState.h:525
void walk(Attribute element)
Walk an attribute.
Attribute replace(Attribute attr)
Replace the given attribute/type, and recursively replace any sub elements.
void addReplacement(ReplaceFn< Attribute > fn)
Register a replacement function for mapping a given attribute or type.
This class is used by AttrTypeSubElementHandler instances to process sub element replacements.
ArrayRef< T > take_front(unsigned n)
Take the first N replacements as an ArrayRef, dropping them from this replacement list.
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.
This class represents the base of an attribute interface.
Definition: Attributes.h:281
detail::Interface< ConcreteType, Attribute, Traits, Attribute, AttributeTrait::TraitBase > InterfaceBase
Definition: Attributes.h:285
Base storage class appearing in an attribute.
Attributes are known-constant values of operations.
Definition: Attributes.h:25
U dyn_cast_or_null() const
Definition: Attributes.h:174
Dialect & getDialect() const
Get the dialect this attribute is registered to.
Definition: Attributes.h:74
U dyn_cast() const
Definition: Attributes.h:169
auto walk(WalkFns &&...walkFns)
Walk this attribute and all attibutes/types nested within using the provided walk functions.
Definition: Attributes.h:128
ImplType * impl
Definition: Attributes.h:150
bool operator!() const
Definition: Attributes.h:48
Attribute(const ImplType *impl)
Definition: Attributes.h:38
constexpr Attribute()=default
static bool classof(Attribute)
Definition: Attributes.h:64
U cast() const
Definition: Attributes.h:179
const AbstractTy & getAbstractAttribute() const
Return the abstract descriptor for this attribute.
Definition: Attributes.h:100
bool operator==(Attribute other) const
Definition: Attributes.h:44
void print(raw_ostream &os, bool elideType=false) const
Print the attribute.
auto replace(ReplacementFns &&...replacementFns)
Recursively replace all of the nested sub-attributes and sub-types using the provided map functions.
Definition: Attributes.h:139
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: Attributes.h:106
void dump() const
bool operator!=(Attribute other) const
Definition: Attributes.h:45
bool isa() const
Casting utility functions.
Definition: Attributes.h:159
MLIRContext * getContext() const
Return the context this attribute belongs to.
Definition: Attributes.cpp:37
auto replaceImmediateSubElements(ArrayRef< Attribute > replAttrs, ArrayRef< Type > replTypes) const
Replace the immediately nested sub-attributes and sub-types with those provided.
Definition: Attributes.h:118
Attribute & operator=(const Attribute &other)=default
friend ::llvm::hash_code hash_value(Attribute arg)
Definition: Attributes.h:183
bool hasTrait()
Returns true if the type was registered with a particular trait.
Definition: Attributes.h:95
const void * getAsOpaquePointer() const
Get an opaque pointer to the attribute.
Definition: Attributes.h:85
Attribute(const Attribute &other)=default
bool isa_and_nonnull() const
Definition: Attributes.h:164
ImplType * getImpl() const
Return the internal Attribute implementation.
Definition: Attributes.h:147
TypeID getTypeID()
Return a unique identifier for the concrete attribute type.
Definition: Attributes.h:68
static Attribute getFromOpaquePointer(const void *ptr)
Construct an attribute from the opaque pointer representation.
Definition: Attributes.h:87
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition: Dialect.h:41
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:56
NamedAttribute represents a combination of a name and an Attribute value.
Definition: Attributes.h:192
StringAttr getName() const
Return the name of the attribute.
Definition: Attributes.cpp:49
void setName(StringAttr newName)
Set the name of this attribute.
Definition: Attributes.cpp:55
bool operator==(const NamedAttribute &rhs) const
Definition: Attributes.h:222
bool operator<(const NamedAttribute &rhs) const
Compare this attribute to the provided attribute, ordering by name.
Definition: Attributes.cpp:60
NamedAttribute(StringAttr name, Attribute value)
Definition: Attributes.cpp:43
Dialect * getNameDialect() const
Return the dialect of the name of this attribute, if the name is prefixed by a dialect namespace.
Definition: Attributes.cpp:51
friend ::llvm::hash_code hash_value(const NamedAttribute &arg)
Allow access to internals to enable hashing.
Definition: Attributes.h:241
void setValue(Attribute newValue)
Set the value of this attribute.
Definition: Attributes.h:212
Attribute getValue() const
Return the value of the attribute.
Definition: Attributes.h:206
bool operator!=(const NamedAttribute &rhs) const
Definition: Attributes.h:225
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:104
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class represents an abstract interface.
Interface< ConcreteType, Attribute, Traits, Attribute, AttributeTrait::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
Include the generated interface declarations.
WalkOrder
Traversal order for region, block and operation walk utilities.
Definition: Visitors.h:63
inline ::llvm::hash_code hash_value(AffineExpr arg)
Make AffineExpr hashable.
Definition: AffineExpr.h:240
raw_ostream & operator<<(raw_ostream &os, const AliasResult &result)
Definition: AliasAnalysis.h:78
static bool isPossible(mlir::Attribute ty)
Arguments are taken as mlir::Attribute here and not as From, because when casting from an intermediat...
Definition: Attributes.h:394
static bool isEqual(mlir::Attribute LHS, mlir::Attribute RHS)
Definition: Attributes.h:328
static unsigned getHashValue(mlir::Attribute val)
Definition: Attributes.h:325
static mlir::Attribute getEmptyKey()
Definition: Attributes.h:317
static mlir::Attribute getTombstoneKey()
Definition: Attributes.h:321
static unsigned getHashValue(mlir::NamedAttribute val)
Definition: Attributes.h:370
static mlir::NamedAttribute getEmptyKey()
Definition: Attributes.h:362
static mlir::NamedAttribute getTombstoneKey()
Definition: Attributes.h:366
static bool isEqual(mlir::NamedAttribute lhs, mlir::NamedAttribute rhs)
Definition: Attributes.h:373
static mlir::Attribute getFromVoidPointer(void *ptr)
Definition: Attributes.h:353
static void * getAsVoidPointer(mlir::Attribute attr)
Definition: Attributes.h:350
static void walk(T param, AttrTypeImmediateSubElementWalker &walker)
Definition: Attributes.h:250
static T replace(T param, AttrSubElementReplacements &attrRepls, TypeSubElementReplacements &typeRepls)
Definition: Attributes.h:255
This class provides support for interacting with the SubElementInterfaces for different types of para...
This trait is used to determine if a storage user, like Type, is mutable or not.