xref: /llvm-project/mlir/lib/IR/Dialect.cpp (revision a5ef51d786f241cdd9d1bec62fbc2bf89a766b7d)
1 //===- Dialect.cpp - Dialect implementation -------------------------------===//
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 #include "mlir/IR/Dialect.h"
10 #include "mlir/IR/BuiltinDialect.h"
11 #include "mlir/IR/Diagnostics.h"
12 #include "mlir/IR/DialectImplementation.h"
13 #include "mlir/IR/DialectInterface.h"
14 #include "mlir/IR/ExtensibleDialect.h"
15 #include "mlir/IR/MLIRContext.h"
16 #include "mlir/IR/Operation.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/Regex.h"
22 
23 #define DEBUG_TYPE "dialect"
24 
25 using namespace mlir;
26 using namespace detail;
27 
28 //===----------------------------------------------------------------------===//
29 // Dialect
30 //===----------------------------------------------------------------------===//
31 
32 Dialect::Dialect(StringRef name, MLIRContext *context, TypeID id)
33     : name(name), dialectID(id), context(context) {
34   assert(isValidNamespace(name) && "invalid dialect namespace");
35 }
36 
37 Dialect::~Dialect() = default;
38 
39 /// Verify an attribute from this dialect on the argument at 'argIndex' for
40 /// the region at 'regionIndex' on the given operation. Returns failure if
41 /// the verification failed, success otherwise. This hook may optionally be
42 /// invoked from any operation containing a region.
43 LogicalResult Dialect::verifyRegionArgAttribute(Operation *, unsigned, unsigned,
44                                                 NamedAttribute) {
45   return success();
46 }
47 
48 /// Verify an attribute from this dialect on the result at 'resultIndex' for
49 /// the region at 'regionIndex' on the given operation. Returns failure if
50 /// the verification failed, success otherwise. This hook may optionally be
51 /// invoked from any operation containing a region.
52 LogicalResult Dialect::verifyRegionResultAttribute(Operation *, unsigned,
53                                                    unsigned, NamedAttribute) {
54   return success();
55 }
56 
57 /// Parse an attribute registered to this dialect.
58 Attribute Dialect::parseAttribute(DialectAsmParser &parser, Type type) const {
59   parser.emitError(parser.getNameLoc())
60       << "dialect '" << getNamespace()
61       << "' provides no attribute parsing hook";
62   return Attribute();
63 }
64 
65 /// Parse a type registered to this dialect.
66 Type Dialect::parseType(DialectAsmParser &parser) const {
67   // If this dialect allows unknown types, then represent this with OpaqueType.
68   if (allowsUnknownTypes()) {
69     StringAttr ns = StringAttr::get(getContext(), getNamespace());
70     return OpaqueType::get(ns, parser.getFullSymbolSpec());
71   }
72 
73   parser.emitError(parser.getNameLoc())
74       << "dialect '" << getNamespace() << "' provides no type parsing hook";
75   return Type();
76 }
77 
78 std::optional<Dialect::ParseOpHook>
79 Dialect::getParseOperationHook(StringRef opName) const {
80   return std::nullopt;
81 }
82 
83 llvm::unique_function<void(Operation *, OpAsmPrinter &printer)>
84 Dialect::getOperationPrinter(Operation *op) const {
85   assert(op->getDialect() == this &&
86          "Dialect hook invoked on non-dialect owned operation");
87   return nullptr;
88 }
89 
90 /// Utility function that returns if the given string is a valid dialect
91 /// namespace
92 bool Dialect::isValidNamespace(StringRef str) {
93   llvm::Regex dialectNameRegex("^[a-zA-Z_][a-zA-Z_0-9\\$]*$");
94   return dialectNameRegex.match(str);
95 }
96 
97 /// Register a set of dialect interfaces with this dialect instance.
98 void Dialect::addInterface(std::unique_ptr<DialectInterface> interface) {
99   // Handle the case where the models resolve a promised interface.
100   handleAdditionOfUndefinedPromisedInterface(interface->getID());
101 
102   auto it = registeredInterfaces.try_emplace(interface->getID(),
103                                              std::move(interface));
104   (void)it;
105   LLVM_DEBUG({
106     if (!it.second) {
107       llvm::dbgs() << "[" DEBUG_TYPE
108                       "] repeated interface registration for dialect "
109                    << getNamespace();
110     }
111   });
112 }
113 
114 //===----------------------------------------------------------------------===//
115 // Dialect Interface
116 //===----------------------------------------------------------------------===//
117 
118 DialectInterface::~DialectInterface() = default;
119 
120 MLIRContext *DialectInterface::getContext() const {
121   return dialect->getContext();
122 }
123 
124 DialectInterfaceCollectionBase::DialectInterfaceCollectionBase(
125     MLIRContext *ctx, TypeID interfaceKind) {
126   for (auto *dialect : ctx->getLoadedDialects()) {
127     if (auto *interface = dialect->getRegisteredInterface(interfaceKind)) {
128       interfaces.insert(interface);
129       orderedInterfaces.push_back(interface);
130     }
131   }
132 }
133 
134 DialectInterfaceCollectionBase::~DialectInterfaceCollectionBase() = default;
135 
136 /// Get the interface for the dialect of given operation, or null if one
137 /// is not registered.
138 const DialectInterface *
139 DialectInterfaceCollectionBase::getInterfaceFor(Operation *op) const {
140   return getInterfaceFor(op->getDialect());
141 }
142 
143 //===----------------------------------------------------------------------===//
144 // DialectExtension
145 //===----------------------------------------------------------------------===//
146 
147 DialectExtensionBase::~DialectExtensionBase() = default;
148 
149 void dialect_extension_detail::handleUseOfUndefinedPromisedInterface(
150     Dialect &dialect, TypeID interfaceID, StringRef interfaceName) {
151   dialect.handleUseOfUndefinedPromisedInterface(interfaceID, interfaceName);
152 }
153 
154 void dialect_extension_detail::handleAdditionOfUndefinedPromisedInterface(
155     Dialect &dialect, TypeID interfaceID) {
156   dialect.handleAdditionOfUndefinedPromisedInterface(interfaceID);
157 }
158 
159 //===----------------------------------------------------------------------===//
160 // DialectRegistry
161 //===----------------------------------------------------------------------===//
162 
163 DialectRegistry::DialectRegistry() { insert<BuiltinDialect>(); }
164 
165 DialectAllocatorFunctionRef
166 DialectRegistry::getDialectAllocator(StringRef name) const {
167   auto it = registry.find(name.str());
168   if (it == registry.end())
169     return nullptr;
170   return it->second.second;
171 }
172 
173 void DialectRegistry::insert(TypeID typeID, StringRef name,
174                              const DialectAllocatorFunction &ctor) {
175   auto inserted = registry.insert(
176       std::make_pair(std::string(name), std::make_pair(typeID, ctor)));
177   if (!inserted.second && inserted.first->second.first != typeID) {
178     llvm::report_fatal_error(
179         "Trying to register different dialects for the same namespace: " +
180         name);
181   }
182 }
183 
184 void DialectRegistry::insertDynamic(
185     StringRef name, const DynamicDialectPopulationFunction &ctor) {
186   // This TypeID marks dynamic dialects. We cannot give a TypeID for the
187   // dialect yet, since the TypeID of a dynamic dialect is defined at its
188   // construction.
189   TypeID typeID = TypeID::get<void>();
190 
191   // Create the dialect, and then call ctor, which allocates its components.
192   auto constructor = [nameStr = name.str(), ctor](MLIRContext *ctx) {
193     auto *dynDialect = ctx->getOrLoadDynamicDialect(
194         nameStr, [ctx, ctor](DynamicDialect *dialect) { ctor(ctx, dialect); });
195     assert(dynDialect && "Dynamic dialect creation unexpectedly failed");
196     return dynDialect;
197   };
198 
199   insert(typeID, name, constructor);
200 }
201 
202 void DialectRegistry::applyExtensions(Dialect *dialect) const {
203   MLIRContext *ctx = dialect->getContext();
204   StringRef dialectName = dialect->getNamespace();
205 
206   // Functor used to try to apply the given extension.
207   auto applyExtension = [&](const DialectExtensionBase &extension) {
208     ArrayRef<StringRef> dialectNames = extension.getRequiredDialects();
209 
210     // Handle the simple case of a single dialect name. In this case, the
211     // required dialect should be the current dialect.
212     if (dialectNames.size() == 1) {
213       if (dialectNames.front() == dialectName)
214         extension.apply(ctx, dialect);
215       return;
216     }
217 
218     // Otherwise, check to see if this extension requires this dialect.
219     const StringRef *nameIt = llvm::find(dialectNames, dialectName);
220     if (nameIt == dialectNames.end())
221       return;
222 
223     // If it does, ensure that all of the other required dialects have been
224     // loaded.
225     SmallVector<Dialect *> requiredDialects;
226     requiredDialects.reserve(dialectNames.size());
227     for (auto it = dialectNames.begin(), e = dialectNames.end(); it != e;
228          ++it) {
229       // The current dialect is known to be loaded.
230       if (it == nameIt) {
231         requiredDialects.push_back(dialect);
232         continue;
233       }
234       // Otherwise, check if it is loaded.
235       Dialect *loadedDialect = ctx->getLoadedDialect(*it);
236       if (!loadedDialect)
237         return;
238       requiredDialects.push_back(loadedDialect);
239     }
240     extension.apply(ctx, requiredDialects);
241   };
242 
243   for (const auto &extension : extensions)
244     applyExtension(*extension);
245 }
246 
247 void DialectRegistry::applyExtensions(MLIRContext *ctx) const {
248   // Functor used to try to apply the given extension.
249   auto applyExtension = [&](const DialectExtensionBase &extension) {
250     ArrayRef<StringRef> dialectNames = extension.getRequiredDialects();
251 
252     // Check to see if all of the dialects for this extension are loaded.
253     SmallVector<Dialect *> requiredDialects;
254     requiredDialects.reserve(dialectNames.size());
255     for (StringRef dialectName : dialectNames) {
256       Dialect *loadedDialect = ctx->getLoadedDialect(dialectName);
257       if (!loadedDialect)
258         return;
259       requiredDialects.push_back(loadedDialect);
260     }
261     extension.apply(ctx, requiredDialects);
262   };
263 
264   for (const auto &extension : extensions)
265     applyExtension(*extension);
266 }
267 
268 bool DialectRegistry::isSubsetOf(const DialectRegistry &rhs) const {
269   // Treat any extensions conservatively.
270   if (!extensions.empty())
271     return false;
272   // Check that the current dialects fully overlap with the dialects in 'rhs'.
273   return llvm::all_of(
274       registry, [&](const auto &it) { return rhs.registry.count(it.first); });
275 }
276