MLIR 24.0.0git
MLIRContext.h
Go to the documentation of this file.
1//===- MLIRContext.h - MLIR Global Context Class ----------------*- 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_MLIRCONTEXT_H
10#define MLIR_IR_MLIRCONTEXT_H
11
12#include "mlir/Support/LLVM.h"
13#include "mlir/Support/TypeID.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/Config/llvm-config.h"
16#include <functional>
17#include <memory>
18#include <vector>
19
20namespace llvm {
21class ThreadPoolInterface;
22} // namespace llvm
23
24namespace mlir {
25namespace tracing {
26class Action;
27}
29class Dialect;
30class DialectRegistry;
31class DynamicDialect;
33class Location;
34class MLIRContextImpl;
36class StorageUniquer;
37class IRUnit;
38namespace remark::detail {
39class RemarkEngine;
40} // namespace remark::detail
41
42/// MLIRContext is the top-level object for a collection of MLIR operations. It
43/// holds immortal uniqued objects like types, and the tables used to unique
44/// them.
45///
46/// MLIRContext gets a redundant "MLIR" prefix because otherwise it ends up with
47/// a very generic name ("Context") and because it is uncommon for clients to
48/// interact with it.
49///
50/// The context wrap some multi-threading facilities, and in particular by
51/// default it will implicitly create a thread pool.
52/// This can be undesirable if multiple context exists at the same time or if a
53/// process will be long-lived and create and destroy contexts.
54/// To control better thread spawning, an externally owned ThreadPool can be
55/// injected in the context. For example:
56///
57/// llvm::DefaultThreadPool myThreadPool;
58/// while (auto *request = nextCompilationRequests()) {
59/// MLIRContext ctx(registry, MLIRContext::Threading::DISABLED);
60/// ctx.setThreadPool(myThreadPool);
61/// processRequest(request, cxt);
62/// }
63///
65public:
66 enum class Threading { DISABLED, ENABLED };
67 /// Create a new Context.
68 explicit MLIRContext(Threading multithreading = Threading::ENABLED);
69 explicit MLIRContext(const DialectRegistry &registry,
70 Threading multithreading = Threading::ENABLED);
72
73 /// Return information about all IR dialects loaded in the context.
74 std::vector<Dialect *> getLoadedDialects();
75
76 /// Return the dialect registry associated with this context.
78
79 /// Append the contents of the given dialect registry to the registry
80 /// associated with this context.
81 void appendDialectRegistry(const DialectRegistry &registry);
82
83 /// Return information about all available dialects in the registry in this
84 /// context.
85 std::vector<StringRef> getAvailableDialects();
86
87 /// Get a registered IR dialect with the given namespace. If an exact match is
88 /// not found, then return nullptr.
89 Dialect *getLoadedDialect(StringRef name);
90
91 /// Get a registered IR dialect for the given derived dialect type. The
92 /// derived type must provide a static 'getDialectNamespace' method.
93 template <typename T>
95 return static_cast<T *>(getLoadedDialect(T::getDialectNamespace()));
96 }
97
98 /// Get (or create) a dialect for the given derived dialect type. The derived
99 /// type must provide a static 'getDialectNamespace' method.
100 template <typename T>
102 return static_cast<T *>(
103 getOrLoadDialect(T::getDialectNamespace(), TypeID::get<T>(), [this]() {
104 std::unique_ptr<T> dialect(new T(this));
105 return dialect;
106 }));
107 }
108
109 /// Load a dialect in the context.
110 template <typename Dialect>
111 void loadDialect() {
112 // Do not load the dialect if it is currently loading. This can happen if a
113 // dialect initializer triggers loading the same dialect recursively.
114 if (!isDialectLoading(Dialect::getDialectNamespace()))
116 }
117
118 /// Load a list dialects in the context.
119 template <typename Dialect, typename OtherDialect, typename... MoreDialects>
120 void loadDialect() {
122 loadDialect<OtherDialect, MoreDialects...>();
123 }
124
125 /// Get (or create) a dynamic dialect for the given name.
127 getOrLoadDynamicDialect(StringRef dialectNamespace,
128 function_ref<void(DynamicDialect *)> ctor);
129
130 /// Load all dialects available in the registry in this context.
132
133 /// Get (or create) a dialect for the given derived dialect name.
134 /// The dialect will be loaded from the registry if no dialect is found.
135 /// If no dialect is loaded for this name and none is available in the
136 /// registry, returns nullptr.
137 Dialect *getOrLoadDialect(StringRef name);
138
139 /// Return true if we allow to create operation for unregistered dialects.
140 [[nodiscard]] bool allowsUnregisteredDialects();
141
142 /// Enables creating operations in unregistered dialects.
143 /// This option is **heavily discouraged**: it is convenient during testing
144 /// but it is not a good practice to use it in production code. Some system
145 /// invariants can be broken (like loading a dialect after creating
146 /// operations) without being caught by assertions or other means.
147 void allowUnregisteredDialects(bool allow = true);
148
149 /// Begins a transient scope on the context, freezing the current state (all
150 /// loaded dialects, registered operations, types, attributes, affine
151 /// expressions, and singletons) as the base state. Subsequent types,
152 /// attributes, and expressions allocated will belong to the transient layer.
153 ///
154 /// Preconditions:
155 /// - The context must not already be in a transient scope.
156 /// - Must be called from a single-threaded execution context.
157 /// - Loading dialects, modifying dialect registries, or mutating base
158 /// storage instances is not supported while in a transient scope.
159 void beginTransientScope();
160
161 /// Ends the transient scope and resets the context to the base state, pruning
162 /// all types, attributes, affine expressions, distinct attributes, and
163 /// unregistered operations created during the transient scope.
164 ///
165 /// Preconditions:
166 /// - The context must be in a transient scope.
167 /// - There must be no remaining IR (operations, blocks, regions,
168 /// values) referencing the transient types/attributes.
169 /// - Must be called from a single-threaded execution context.
170 void endTransientScope();
171
172 /// Returns true if the context is currently in a transient scope.
173 bool isInTransientScope() const;
174
175 /// RAII scope guard that calls beginTransientScope() on construction and
176 /// endTransientScope() on destruction. Provides exception-safe and
177 /// forgetting-proof transient scope management.
179 public:
180 explicit TransientScope(MLIRContext &ctx) : ctx(ctx) {
181 ctx.beginTransientScope();
182 }
183 ~TransientScope() { ctx.endTransientScope(); }
184
187
188 private:
189 MLIRContext &ctx;
190 };
191
192 /// Return true if multi-threading is enabled by the context.
193#if LLVM_ENABLE_THREADS
195#else
196 bool isMultithreadingEnabled() { return false; }
197#endif
198
199 /// Set the flag specifying if multi-threading is disabled by the context.
200 /// The command line debugging flag `--mlir-disable-threading` is overriding
201 /// this call and making it a no-op!
202 void disableMultithreading(bool disable = true);
203 void enableMultithreading(bool enable = true) {
204 disableMultithreading(!enable);
205 }
206
207 /// Set a new thread pool to be used in this context. This method requires
208 /// that multithreading is disabled for this context prior to the call. This
209 /// allows to share a thread pool across multiple contexts, as well as
210 /// decoupling the lifetime of the threads from the contexts. The thread pool
211 /// must outlive the context. Multi-threading will be enabled as part of this
212 /// method.
213 /// The command line debugging flag `--mlir-disable-threading` will still
214 /// prevent threading from being enabled and threading won't be enabled after
215 /// this call in this case.
216 void setThreadPool(llvm::ThreadPoolInterface &pool);
217
218 /// Return the number of threads used by the thread pool in this context. The
219 /// number of computed hardware threads can change over the lifetime of a
220 /// process based on affinity changes, so users should use the number of
221 /// threads actually in the thread pool for dispatching work. Returns 1 if
222 /// multithreading is disabled.
223 unsigned getNumThreads();
224
225 /// Return the thread pool used by this context. This method requires that
226 /// multithreading be enabled within the context, and should generally not be
227 /// used directly. Users should instead prefer the threading utilities within
228 /// Threading.h.
229 llvm::ThreadPoolInterface &getThreadPool();
230
231 /// Return true if we should attach the operation to diagnostics emitted via
232 /// Operation::emit.
234
235 /// Set the flag specifying if we should attach the operation to diagnostics
236 /// emitted via Operation::emit.
237 void printOpOnDiagnostic(bool enable);
238
239 /// Return true if we should attach the current stacktrace to diagnostics when
240 /// emitted.
242
243 /// Set the flag specifying if we should attach the current stacktrace when
244 /// emitting diagnostics.
245 void printStackTraceOnDiagnostic(bool enable);
246
247 /// Return a sorted array containing the information about all registered
248 /// operations.
250
251 /// Return a sorted array containing the information for registered operations
252 /// filtered by dialect name.
254 getRegisteredOperationsByDialect(StringRef dialectName);
255
256 /// Return true if this operation name is registered in this context.
257 bool isOperationRegistered(StringRef name);
258
259 // This is effectively private given that only MLIRContext.cpp can see the
260 // MLIRContextImpl type.
262 const MLIRContextImpl &getImpl() const { return *impl; }
263
264 /// Returns the diagnostic engine for this context.
266
267 /// Returns the remark engine for this context, or nullptr if none has been
268 /// set.
270
271 /// Set the remark engine for this context.
272 void setRemarkEngine(std::unique_ptr<remark::detail::RemarkEngine> engine);
273
274 /// Returns the storage uniquer used for creating affine constructs.
276
277 /// Returns the storage uniquer used for constructing type storage instances.
278 /// This should not be used directly.
280
281 /// Returns the storage uniquer used for constructing attribute storage
282 /// instances. This should not be used directly.
284
285 /// These APIs are tracking whether the context will be used in a
286 /// multithreading environment: this has no effect other than enabling
287 /// assertions on misuses of some APIs.
290
291 /// Get a dialect for the provided namespace and TypeID: abort the program if
292 /// a dialect exist for this namespace with different TypeID. If a dialect has
293 /// not been loaded for this namespace/TypeID yet, use the provided ctor to
294 /// create one on the fly and load it. Returns a pointer to the dialect owned
295 /// by the context.
296 /// The use of this method is in general discouraged in favor of
297 /// 'getOrLoadDialect<DialectClass>()'.
298 Dialect *getOrLoadDialect(StringRef dialectNamespace, TypeID dialectID,
299 function_ref<std::unique_ptr<Dialect>()> ctor);
300
301 /// Returns a hash of the registry of the context that may be used to give
302 /// a rough indicator of if the state of the context registry has changed. The
303 /// context registry correlates to loaded dialects and their entities
304 /// (attributes, operations, types, etc.).
305 llvm::hash_code getRegistryHash();
306
307 //===--------------------------------------------------------------------===//
308 // Action API
309 //===--------------------------------------------------------------------===//
310
311 /// Signatures for the action handler that can be registered with the context.
312 using HandlerTy =
313 std::function<void(function_ref<void()>, const tracing::Action &)>;
314
315 /// Register a handler for handling actions that are dispatched through this
316 /// context. A nullptr handler can be set to disable a previously set handler.
317 void registerActionHandler(HandlerTy handler);
318
319 /// Return a reference to the currently registered action handler. Its target
320 /// can be used to gain access to the handler's state, if any.
321 const HandlerTy &getActionHandler() const;
323
324 /// Return true if a valid ActionHandler is set.
325 bool hasActionHandler();
326
327 /// Dispatch the provided action to the handler if any, or just execute it.
328 void executeAction(function_ref<void()> actionFn,
329 const tracing::Action &action) {
330 if (LLVM_UNLIKELY(hasActionHandler()))
331 executeActionInternal(actionFn, action);
332 else
333 actionFn();
334 }
335
336 /// Dispatch the provided action to the handler if any, or just execute it.
337 template <typename ActionTy, typename... Args>
338 void executeAction(function_ref<void()> actionFn, ArrayRef<IRUnit> irUnits,
339 Args &&...args) {
340 if (LLVM_UNLIKELY(hasActionHandler()))
341 executeActionInternal<ActionTy, Args...>(actionFn, irUnits,
342 std::forward<Args>(args)...);
343 else
344 actionFn();
345 }
346
347private:
348 /// Return true if the given dialect is currently loading.
349 bool isDialectLoading(StringRef dialectNamespace);
350
351 /// Internal helper for the dispatch method.
352 void executeActionInternal(function_ref<void()> actionFn,
353 const tracing::Action &action);
354
355 /// Internal helper for the dispatch method. We get here after checking that
356 /// there is a handler, for the purpose of keeping this code out-of-line. and
357 /// avoid calling the ctor for the Action unnecessarily.
358 template <typename ActionTy, typename... Args>
359 LLVM_ATTRIBUTE_NOINLINE void
360 executeActionInternal(function_ref<void()> actionFn, ArrayRef<IRUnit> irUnits,
361 Args &&...args) {
362 executeActionInternal(actionFn,
363 ActionTy(irUnits, std::forward<Args>(args)...));
364 }
365
366 const std::unique_ptr<MLIRContextImpl> impl;
367
368 MLIRContext(const MLIRContext &) = delete;
369 void operator=(const MLIRContext &) = delete;
370};
371
372//===----------------------------------------------------------------------===//
373// MLIRContext CommandLine Options
374//===----------------------------------------------------------------------===//
375
376/// Register a set of useful command-line options that can be used to configure
377/// various flags within the MLIRContext. These flags are used when constructing
378/// an MLIR context for initialization.
380
381} // namespace mlir
382
383#endif // MLIR_IR_MLIRCONTEXT_H
This class is the main interface for diagnostics.
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:38
A dialect that can be defined at runtime.
IRUnit is a union of the different types of IR objects that constitute the IR structure (other than T...
Definition Unit.h:28
This class represents a diagnostic that is inflight and set to be reported.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This is the implementation of the MLIRContext class, using the pImpl idiom.
TransientScope(const TransientScope &)=delete
TransientScope & operator=(const TransientScope &)=delete
void appendDialectRegistry(const DialectRegistry &registry)
Append the contents of the given dialect registry to the registry associated with this context.
bool shouldPrintStackTraceOnDiagnostic()
Return true if we should attach the current stacktrace to diagnostics when emitted.
unsigned getNumThreads()
Return the number of threads used by the thread pool in this context.
bool isInTransientScope() const
Returns true if the context is currently in a transient scope.
bool isOperationRegistered(StringRef name)
Return true if this operation name is registered in this context.
MLIRContext(Threading multithreading=Threading::ENABLED)
Create a new Context.
void disableMultithreading(bool disable=true)
Set the flag specifying if multi-threading is disabled by the context.
T * getOrLoadDialect()
Get (or create) a dialect for the given derived dialect type.
void printStackTraceOnDiagnostic(bool enable)
Set the flag specifying if we should attach the current stacktrace when emitting diagnostics.
bool hasActionHandler()
Return true if a valid ActionHandler is set.
void setRemarkEngine(std::unique_ptr< remark::detail::RemarkEngine > engine)
Set the remark engine for this context.
void setThreadPool(llvm::ThreadPoolInterface &pool)
Set a new thread pool to be used in this context.
void executeAction(function_ref< void()> actionFn, const tracing::Action &action)
Dispatch the provided action to the handler if any, or just execute it.
const HandlerTy & getActionHandler() const
Return a reference to the currently registered action handler.
void enableMultithreading(bool enable=true)
remark::detail::RemarkEngine * getRemarkEngine()
Returns the remark engine for this context, or nullptr if none has been set.
std::vector< Dialect * > getLoadedDialects()
Return information about all IR dialects loaded in the context.
ArrayRef< RegisteredOperationName > getRegisteredOperationsByDialect(StringRef dialectName)
Return a sorted array containing the information for registered operations filtered by dialect name.
void printOpOnDiagnostic(bool enable)
Set the flag specifying if we should attach the operation to diagnostics emitted via Operation::emit.
void executeAction(function_ref< void()> actionFn, ArrayRef< IRUnit > irUnits, Args &&...args)
Dispatch the provided action to the handler if any, or just execute it.
void registerActionHandler(HandlerTy handler)
Register a handler for handling actions that are dispatched through this context.
ArrayRef< RegisteredOperationName > getRegisteredOperations()
Return a sorted array containing the information about all registered operations.
llvm::hash_code getRegistryHash()
Returns a hash of the registry of the context that may be used to give a rough indicator of if the st...
void enterMultiThreadedExecution()
These APIs are tracking whether the context will be used in a multithreading environment: this has no...
const DialectRegistry & getDialectRegistry()
Return the dialect registry associated with this context.
void loadDialect()
Load a dialect in the context.
DynamicDialect * getOrLoadDynamicDialect(StringRef dialectNamespace, function_ref< void(DynamicDialect *)> ctor)
Get (or create) a dynamic dialect for the given name.
const MLIRContextImpl & getImpl() const
StorageUniquer & getAttributeUniquer()
Returns the storage uniquer used for constructing attribute storage instances.
StorageUniquer & getAffineUniquer()
Returns the storage uniquer used for creating affine constructs.
void endTransientScope()
Ends the transient scope and resets the context to the base state, pruning all types,...
std::function< void(function_ref< void()>, const tracing::Action &)> HandlerTy
Signatures for the action handler that can be registered with the context.
StorageUniquer & getTypeUniquer()
Returns the storage uniquer used for constructing type storage instances.
llvm::ThreadPoolInterface & getThreadPool()
Return the thread pool used by this context.
std::vector< StringRef > getAvailableDialects()
Return information about all available dialects in the registry in this context.
void allowUnregisteredDialects(bool allow=true)
Enables creating operations in unregistered dialects.
bool allowsUnregisteredDialects()
Return true if we allow to create operation for unregistered dialects.
DiagnosticEngine & getDiagEngine()
Returns the diagnostic engine for this context.
void loadDialect()
Load a list dialects in the context.
MLIRContextImpl & getImpl()
void exitMultiThreadedExecution()
bool isMultithreadingEnabled()
Return true if multi-threading is enabled by the context.
bool shouldPrintOpOnDiagnostic()
Return true if we should attach the operation to diagnostics emitted via Operation::emit.
void beginTransientScope()
Begins a transient scope on the context, freezing the current state (all loaded dialects,...
void loadAllAvailableDialects()
Load all dialects available in the registry in this context.
T * getLoadedDialect()
Get a registered IR dialect for the given derived dialect type.
Definition MLIRContext.h:94
This is a "type erased" representation of a registered operation.
A utility class to get or create instances of "storage classes".
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
An action is a specific action that is to be taken by the compiler, that can be toggled and controlle...
Definition Action.h:38
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:227
Include the generated interface declarations.
void registerMLIRContextCLOptions()
Register a set of useful command-line options that can be used to configure various flags within the ...
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155