MLIR  16.0.0git
Dialect.h
Go to the documentation of this file.
1 //===- Dialect.h - IR Dialect Description -----------------------*- 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 the 'dialect' abstraction.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef MLIR_IR_DIALECT_H
14 #define MLIR_IR_DIALECT_H
15 
18 #include "mlir/Support/TypeID.h"
19 
20 #include <map>
21 #include <tuple>
22 
23 namespace mlir {
24 class DialectAsmParser;
25 class DialectAsmPrinter;
26 class DialectInterface;
27 class OpBuilder;
28 class Type;
29 
30 //===----------------------------------------------------------------------===//
31 // Dialect
32 //===----------------------------------------------------------------------===//
33 
34 /// Dialects are groups of MLIR operations, types and attributes, as well as
35 /// behavior associated with the entire group. For example, hooks into other
36 /// systems for constant folding, interfaces, default named types for asm
37 /// printing, etc.
38 ///
39 /// Instances of the dialect object are loaded in a specific MLIRContext.
40 ///
41 class Dialect {
42 public:
43  /// Type for a callback provided by the dialect to parse a custom operation.
44  /// This is used for the dialect to provide an alternative way to parse custom
45  /// operations, including unregistered ones.
46  using ParseOpHook =
48 
49  virtual ~Dialect();
50 
51  /// Utility function that returns if the given string is a valid dialect
52  /// namespace
53  static bool isValidNamespace(StringRef str);
54 
55  MLIRContext *getContext() const { return context; }
56 
57  StringRef getNamespace() const { return name; }
58 
59  /// Returns the unique identifier that corresponds to this dialect.
60  TypeID getTypeID() const { return dialectID; }
61 
62  /// Returns true if this dialect allows for unregistered operations, i.e.
63  /// operations prefixed with the dialect namespace but not registered with
64  /// addOperation.
65  bool allowsUnknownOperations() const { return unknownOpsAllowed; }
66 
67  /// Return true if this dialect allows for unregistered types, i.e., types
68  /// prefixed with the dialect namespace but not registered with addType.
69  /// These are represented with OpaqueType.
70  bool allowsUnknownTypes() const { return unknownTypesAllowed; }
71 
72  /// Register dialect-wide canonicalization patterns. This method should only
73  /// be used to register canonicalization patterns that do not conceptually
74  /// belong to any single operation in the dialect. (In that case, use the op's
75  /// canonicalizer.) E.g., canonicalization patterns for op interfaces should
76  /// be registered here.
77  virtual void getCanonicalizationPatterns(RewritePatternSet &results) const {}
78 
79  /// Registered hook to materialize a single constant operation from a given
80  /// attribute value with the desired resultant type. This method should use
81  /// the provided builder to create the operation without changing the
82  /// insertion position. The generated operation is expected to be constant
83  /// like, i.e. single result, zero operands, non side-effecting, etc. On
84  /// success, this hook should return the value generated to represent the
85  /// constant value. Otherwise, it should return null on failure.
87  Type type, Location loc) {
88  return nullptr;
89  }
90 
91  //===--------------------------------------------------------------------===//
92  // Parsing Hooks
93  //===--------------------------------------------------------------------===//
94 
95  /// Parse an attribute registered to this dialect. If 'type' is nonnull, it
96  /// refers to the expected type of the attribute.
97  virtual Attribute parseAttribute(DialectAsmParser &parser, Type type) const;
98 
99  /// Print an attribute registered to this dialect. Note: The type of the
100  /// attribute need not be printed by this method as it is always printed by
101  /// the caller.
102  virtual void printAttribute(Attribute, DialectAsmPrinter &) const {
103  llvm_unreachable("dialect has no registered attribute printing hook");
104  }
105 
106  /// Parse a type registered to this dialect.
107  virtual Type parseType(DialectAsmParser &parser) const;
108 
109  /// Print a type registered to this dialect.
110  virtual void printType(Type, DialectAsmPrinter &) const {
111  llvm_unreachable("dialect has no registered type printing hook");
112  }
113 
114  /// Return the hook to parse an operation registered to this dialect, if any.
115  /// By default this will lookup for registered operations and return the
116  /// `parse()` method registered on the RegisteredOperationName. Dialects can
117  /// override this behavior and handle unregistered operations as well.
118  virtual Optional<ParseOpHook> getParseOperationHook(StringRef opName) const;
119 
120  /// Print an operation registered to this dialect.
121  /// This hook is invoked for registered operation which don't override the
122  /// `print()` method to define their own custom assembly.
123  virtual llvm::unique_function<void(Operation *, OpAsmPrinter &printer)>
124  getOperationPrinter(Operation *op) const;
125 
126  //===--------------------------------------------------------------------===//
127  // Verification Hooks
128  //===--------------------------------------------------------------------===//
129 
130  /// Verify an attribute from this dialect on the argument at 'argIndex' for
131  /// the region at 'regionIndex' on the given operation. Returns failure if
132  /// the verification failed, success otherwise. This hook may optionally be
133  /// invoked from any operation containing a region.
135  unsigned regionIndex,
136  unsigned argIndex,
138 
139  /// Verify an attribute from this dialect on the result at 'resultIndex' for
140  /// the region at 'regionIndex' on the given operation. Returns failure if
141  /// the verification failed, success otherwise. This hook may optionally be
142  /// invoked from any operation containing a region.
144  unsigned regionIndex,
145  unsigned resultIndex,
147 
148  /// Verify an attribute from this dialect on the given operation. Returns
149  /// failure if the verification failed, success otherwise.
151  return success();
152  }
153 
154  //===--------------------------------------------------------------------===//
155  // Interfaces
156  //===--------------------------------------------------------------------===//
157 
158  /// Lookup an interface for the given ID if one is registered, otherwise
159  /// nullptr.
161  auto it = registeredInterfaces.find(interfaceID);
162  return it != registeredInterfaces.end() ? it->getSecond().get() : nullptr;
163  }
164  template <typename InterfaceT>
165  InterfaceT *getRegisteredInterface() {
166  return static_cast<InterfaceT *>(
167  getRegisteredInterface(InterfaceT::getInterfaceID()));
168  }
169 
170  /// Lookup an op interface for the given ID if one is registered, otherwise
171  /// nullptr.
172  virtual void *getRegisteredInterfaceForOp(TypeID interfaceID,
173  OperationName opName) {
174  return nullptr;
175  }
176  template <typename InterfaceT>
177  typename InterfaceT::Concept *
179  return static_cast<typename InterfaceT::Concept *>(
180  getRegisteredInterfaceForOp(InterfaceT::getInterfaceID(), opName));
181  }
182 
183  /// Register a dialect interface with this dialect instance.
184  void addInterface(std::unique_ptr<DialectInterface> interface);
185 
186  /// Register a set of dialect interfaces with this dialect instance.
187  template <typename... Args>
188  void addInterfaces() {
189  (addInterface(std::make_unique<Args>(this)), ...);
190  }
191  template <typename InterfaceT, typename... Args>
192  InterfaceT &addInterface(Args &&...args) {
193  InterfaceT *interface = new InterfaceT(this, std::forward<Args>(args)...);
194  addInterface(std::unique_ptr<DialectInterface>(interface));
195  return *interface;
196  }
197 
198 protected:
199  /// The constructor takes a unique namespace for this dialect as well as the
200  /// context to bind to.
201  /// Note: The namespace must not contain '.' characters.
202  /// Note: All operations belonging to this dialect must have names starting
203  /// with the namespace followed by '.'.
204  /// Example:
205  /// - "tf" for the TensorFlow ops like "tf.add".
206  Dialect(StringRef name, MLIRContext *context, TypeID id);
207 
208  /// This method is used by derived classes to add their operations to the set.
209  ///
210  template <typename... Args>
211  void addOperations() {
212  // This initializer_list argument pack expansion is essentially equal to
213  // using a fold expression with a comma operator. Clang however, refuses
214  // to compile a fold expression with a depth of more than 256 by default.
215  // There seem to be no such limitations for initializer_list.
216  (void)std::initializer_list<int>{
217  0, (RegisteredOperationName::insert<Args>(*this), 0)...};
218  }
219 
220  /// Register a set of type classes with this dialect.
221  template <typename... Args>
222  void addTypes() {
223  (addType<Args>(), ...);
224  }
225 
226  /// Register a type instance with this dialect.
227  /// The use of this method is in general discouraged in favor of
228  /// 'addTypes<CustomType>()'.
229  void addType(TypeID typeID, AbstractType &&typeInfo);
230 
231  /// Register a set of attribute classes with this dialect.
232  template <typename... Args>
233  void addAttributes() {
234  (addAttribute<Args>(), ...);
235  }
236 
237  /// Register an attribute instance with this dialect.
238  /// The use of this method is in general discouraged in favor of
239  /// 'addAttributes<CustomAttr>()'.
240  void addAttribute(TypeID typeID, AbstractAttribute &&attrInfo);
241 
242  /// Enable support for unregistered operations.
243  void allowUnknownOperations(bool allow = true) { unknownOpsAllowed = allow; }
244 
245  /// Enable support for unregistered types.
246  void allowUnknownTypes(bool allow = true) { unknownTypesAllowed = allow; }
247 
248 private:
249  Dialect(const Dialect &) = delete;
250  void operator=(Dialect &) = delete;
251 
252  /// Register an attribute instance with this dialect.
253  template <typename T>
254  void addAttribute() {
255  // Add this attribute to the dialect and register it with the uniquer.
256  addAttribute(T::getTypeID(), AbstractAttribute::get<T>(*this));
257  detail::AttributeUniquer::registerAttribute<T>(context);
258  }
259 
260  /// Register a type instance with this dialect.
261  template <typename T>
262  void addType() {
263  // Add this type to the dialect and register it with the uniquer.
264  addType(T::getTypeID(), AbstractType::get<T>(*this));
265  detail::TypeUniquer::registerType<T>(context);
266  }
267 
268  /// The namespace of this dialect.
269  StringRef name;
270 
271  /// The unique identifier of the derived Op class, this is used in the context
272  /// to allow registering multiple times the same dialect.
273  TypeID dialectID;
274 
275  /// This is the context that owns this Dialect object.
276  MLIRContext *context;
277 
278  /// Flag that specifies whether this dialect supports unregistered operations,
279  /// i.e. operations prefixed with the dialect namespace but not registered
280  /// with addOperation.
281  bool unknownOpsAllowed = false;
282 
283  /// Flag that specifies whether this dialect allows unregistered types, i.e.
284  /// types prefixed with the dialect namespace but not registered with addType.
285  /// These types are represented with OpaqueType.
286  bool unknownTypesAllowed = false;
287 
288  /// A collection of registered dialect interfaces.
289  DenseMap<TypeID, std::unique_ptr<DialectInterface>> registeredInterfaces;
290 
291  friend class DialectRegistry;
292  friend void registerDialect();
293  friend class MLIRContext;
294 };
295 
296 } // namespace mlir
297 
298 namespace llvm {
299 /// Provide isa functionality for Dialects.
300 template <typename T>
301 struct isa_impl<T, ::mlir::Dialect,
302  std::enable_if_t<std::is_base_of<::mlir::Dialect, T>::value>> {
303  static inline bool doit(const ::mlir::Dialect &dialect) {
304  return mlir::TypeID::get<T>() == dialect.getTypeID();
305  }
306 };
307 template <typename T>
308 struct isa_impl<
309  T, ::mlir::Dialect,
310  std::enable_if_t<std::is_base_of<::mlir::DialectInterface, T>::value>> {
311  static inline bool doit(const ::mlir::Dialect &dialect) {
312  return const_cast<::mlir::Dialect &>(dialect).getRegisteredInterface<T>();
313  }
314 };
315 template <typename T>
316 struct cast_retty_impl<T, ::mlir::Dialect *> {
317  using ret_type = T *;
318 };
319 template <typename T>
320 struct cast_retty_impl<T, ::mlir::Dialect> {
321  using ret_type = T &;
322 };
323 
324 template <typename T>
325 struct cast_convert_val<T, ::mlir::Dialect, ::mlir::Dialect> {
326  template <typename To>
328  doitImpl(::mlir::Dialect &dialect) {
329  return static_cast<To &>(dialect);
330  }
331  template <typename To>
333  To &>
334  doitImpl(::mlir::Dialect &dialect) {
335  return *dialect.getRegisteredInterface<To>();
336  }
337 
338  static auto &doit(::mlir::Dialect &dialect) { return doitImpl<T>(dialect); }
339 };
340 template <class T>
341 struct cast_convert_val<T, ::mlir::Dialect *, ::mlir::Dialect *> {
342  static auto doit(::mlir::Dialect *dialect) {
343  return &cast_convert_val<T, ::mlir::Dialect, ::mlir::Dialect>::doit(
344  *dialect);
345  }
346 };
347 
348 } // namespace llvm
349 
350 #endif
static constexpr const bool value
static int resultIndex(int i)
Definition: Operator.cpp:308
This class contains all of the static information common to all instances of a registered Attribute.
This class contains all of the static information common to all instances of a registered Type.
Definition: TypeSupport.h:30
Attributes are known-constant values of operations.
Definition: Attributes.h:25
The DialectAsmParser has methods for interacting with the asm parser when parsing attributes and type...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
This class represents an interface overridden for a single dialect.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition: Dialect.h:41
void addAttributes()
Register a set of attribute classes with this dialect.
Definition: Dialect.h:233
void addInterfaces()
Register a set of dialect interfaces with this dialect instance.
Definition: Dialect.h:188
virtual ~Dialect()
virtual void * getRegisteredInterfaceForOp(TypeID interfaceID, OperationName opName)
Lookup an op interface for the given ID if one is registered, otherwise nullptr.
Definition: Dialect.h:172
friend class MLIRContext
Definition: Dialect.h:293
virtual Type parseType(DialectAsmParser &parser) const
Parse a type registered to this dialect.
Definition: Dialect.cpp:66
StringRef getNamespace() const
Definition: Dialect.h:57
static bool isValidNamespace(StringRef str)
Utility function that returns if the given string is a valid dialect namespace.
Definition: Dialect.cpp:92
virtual LogicalResult verifyRegionResultAttribute(Operation *, unsigned regionIndex, unsigned resultIndex, NamedAttribute)
Verify an attribute from this dialect on the result at 'resultIndex' for the region at 'regionIndex' ...
Definition: Dialect.cpp:52
DialectInterface * getRegisteredInterface(TypeID interfaceID)
Lookup an interface for the given ID if one is registered, otherwise nullptr.
Definition: Dialect.h:160
InterfaceT::Concept * getRegisteredInterfaceForOp(OperationName opName)
Definition: Dialect.h:178
virtual LogicalResult verifyRegionArgAttribute(Operation *, unsigned regionIndex, unsigned argIndex, NamedAttribute)
Verify an attribute from this dialect on the argument at 'argIndex' for the region at 'regionIndex' o...
Definition: Dialect.cpp:43
void addOperations()
This method is used by derived classes to add their operations to the set.
Definition: Dialect.h:211
InterfaceT * getRegisteredInterface()
Definition: Dialect.h:165
virtual llvm::unique_function< void(Operation *, OpAsmPrinter &printer)> getOperationPrinter(Operation *op) const
Print an operation registered to this dialect.
Definition: Dialect.cpp:84
bool allowsUnknownTypes() const
Return true if this dialect allows for unregistered types, i.e., types prefixed with the dialect name...
Definition: Dialect.h:70
virtual void printAttribute(Attribute, DialectAsmPrinter &) const
Print an attribute registered to this dialect.
Definition: Dialect.h:102
void addTypes()
Register a set of type classes with this dialect.
Definition: Dialect.h:222
virtual void printType(Type, DialectAsmPrinter &) const
Print a type registered to this dialect.
Definition: Dialect.h:110
MLIRContext * getContext() const
Definition: Dialect.h:55
void allowUnknownTypes(bool allow=true)
Enable support for unregistered types.
Definition: Dialect.h:246
virtual Optional< ParseOpHook > getParseOperationHook(StringRef opName) const
Return the hook to parse an operation registered to this dialect, if any.
Definition: Dialect.cpp:79
virtual LogicalResult verifyOperationAttribute(Operation *, NamedAttribute)
Verify an attribute from this dialect on the given operation.
Definition: Dialect.h:150
void allowUnknownOperations(bool allow=true)
Enable support for unregistered operations.
Definition: Dialect.h:243
bool allowsUnknownOperations() const
Returns true if this dialect allows for unregistered operations, i.e.
Definition: Dialect.h:65
virtual Attribute parseAttribute(DialectAsmParser &parser, Type type) const
Parse an attribute registered to this dialect.
Definition: Dialect.cpp:58
void addInterface(std::unique_ptr< DialectInterface > interface)
Register a dialect interface with this dialect instance.
Definition: Dialect.cpp:98
TypeID getTypeID() const
Returns the unique identifier that corresponds to this dialect.
Definition: Dialect.h:60
friend void registerDialect()
Dialect(StringRef name, MLIRContext *context, TypeID id)
The constructor takes a unique namespace for this dialect as well as the context to bind to.
Definition: Dialect.cpp:32
InterfaceT & addInterface(Args &&...args)
Definition: Dialect.h:192
virtual void getCanonicalizationPatterns(RewritePatternSet &results) const
Register dialect-wide canonicalization patterns.
Definition: Dialect.h:77
virtual Operation * materializeConstant(OpBuilder &builder, Attribute value, Type type, Location loc)
Registered hook to materialize a single constant operation from a given attribute value with the desi...
Definition: Dialect.h:86
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:64
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:150
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
This class helps build Operations.
Definition: Builders.h:198
Operation is a basic unit of execution within MLIR.
Definition: Operation.h:31
This class represents success/failure for parsing-like operations that find it important to chain tog...
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
Include the generated interface declarations.
Definition: CallGraph.h:229
@ Type
An inlay hint that for a type annotation.
Include the generated interface declarations.
LogicalResult success(bool isSuccess=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:56
static auto & doit(::mlir::Dialect &dialect)
Definition: Dialect.h:338
static std::enable_if_t< std::is_base_of<::mlir::Dialect, To >::value, To & > doitImpl(::mlir::Dialect &dialect)
Definition: Dialect.h:328
static std::enable_if_t< std::is_base_of<::mlir::DialectInterface, To >::value, To & > doitImpl(::mlir::Dialect &dialect)
Definition: Dialect.h:334
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26
This represents an operation in an abstracted form, suitable for use with the builder APIs.