1 //===- MLIRContext.cpp - MLIR Type Classes --------------------------------===//
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/MLIRContext.h"
10 #include "AffineExprDetail.h"
11 #include "AffineMapDetail.h"
12 #include "AttributeDetail.h"
13 #include "IntegerSetDetail.h"
14 #include "TypeDetail.h"
15 #include "mlir/IR/AffineExpr.h"
16 #include "mlir/IR/AffineMap.h"
17 #include "mlir/IR/Attributes.h"
18 #include "mlir/IR/BuiltinDialect.h"
19 #include "mlir/IR/Diagnostics.h"
20 #include "mlir/IR/Dialect.h"
21 #include "mlir/IR/Identifier.h"
22 #include "mlir/IR/IntegerSet.h"
23 #include "mlir/IR/Location.h"
24 #include "mlir/IR/OpImplementation.h"
25 #include "mlir/IR/Types.h"
26 #include "mlir/Support/DebugAction.h"
27 #include "mlir/Support/ThreadLocalCache.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/SetVector.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringSet.h"
33 #include "llvm/ADT/Twine.h"
34 #include "llvm/Support/Allocator.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/RWMutex.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <memory>
40 
41 #define DEBUG_TYPE "mlircontext"
42 
43 using namespace mlir;
44 using namespace mlir::detail;
45 
46 using llvm::hash_combine;
47 using llvm::hash_combine_range;
48 
49 //===----------------------------------------------------------------------===//
50 // MLIRContext CommandLine Options
51 //===----------------------------------------------------------------------===//
52 
53 namespace {
54 /// This struct contains command line options that can be used to initialize
55 /// various bits of an MLIRContext. This uses a struct wrapper to avoid the need
56 /// for global command line options.
57 struct MLIRContextOptions {
58   llvm::cl::opt<bool> disableThreading{
59       "mlir-disable-threading",
60       llvm::cl::desc("Disabling multi-threading within MLIR")};
61 
62   llvm::cl::opt<bool> printOpOnDiagnostic{
63       "mlir-print-op-on-diagnostic",
64       llvm::cl::desc("When a diagnostic is emitted on an operation, also print "
65                      "the operation as an attached note"),
66       llvm::cl::init(true)};
67 
68   llvm::cl::opt<bool> printStackTraceOnDiagnostic{
69       "mlir-print-stacktrace-on-diagnostic",
70       llvm::cl::desc("When a diagnostic is emitted, also print the stack trace "
71                      "as an attached note")};
72 };
73 } // end anonymous namespace
74 
75 static llvm::ManagedStatic<MLIRContextOptions> clOptions;
76 
77 /// Register a set of useful command-line options that can be used to configure
78 /// various flags within the MLIRContext. These flags are used when constructing
79 /// an MLIR context for initialization.
80 void mlir::registerMLIRContextCLOptions() {
81   // Make sure that the options struct has been initialized.
82   *clOptions;
83 }
84 
85 //===----------------------------------------------------------------------===//
86 // Locking Utilities
87 //===----------------------------------------------------------------------===//
88 
89 namespace {
90 /// Utility reader lock that takes a runtime flag that specifies if we really
91 /// need to lock.
92 struct ScopedReaderLock {
93   ScopedReaderLock(llvm::sys::SmartRWMutex<true> &mutexParam, bool shouldLock)
94       : mutex(shouldLock ? &mutexParam : nullptr) {
95     if (mutex)
96       mutex->lock_shared();
97   }
98   ~ScopedReaderLock() {
99     if (mutex)
100       mutex->unlock_shared();
101   }
102   llvm::sys::SmartRWMutex<true> *mutex;
103 };
104 /// Utility writer lock that takes a runtime flag that specifies if we really
105 /// need to lock.
106 struct ScopedWriterLock {
107   ScopedWriterLock(llvm::sys::SmartRWMutex<true> &mutexParam, bool shouldLock)
108       : mutex(shouldLock ? &mutexParam : nullptr) {
109     if (mutex)
110       mutex->lock();
111   }
112   ~ScopedWriterLock() {
113     if (mutex)
114       mutex->unlock();
115   }
116   llvm::sys::SmartRWMutex<true> *mutex;
117 };
118 } // end anonymous namespace.
119 
120 //===----------------------------------------------------------------------===//
121 // AffineMap and IntegerSet hashing
122 //===----------------------------------------------------------------------===//
123 
124 /// A utility function to safely get or create a uniqued instance within the
125 /// given set container.
126 template <typename ValueT, typename DenseInfoT, typename KeyT,
127           typename ConstructorFn>
128 static ValueT safeGetOrCreate(DenseSet<ValueT, DenseInfoT> &container,
129                               KeyT &&key, llvm::sys::SmartRWMutex<true> &mutex,
130                               bool threadingIsEnabled,
131                               ConstructorFn &&constructorFn) {
132   // Check for an existing instance in read-only mode.
133   if (threadingIsEnabled) {
134     llvm::sys::SmartScopedReader<true> instanceLock(mutex);
135     auto it = container.find_as(key);
136     if (it != container.end())
137       return *it;
138   }
139 
140   // Acquire a writer-lock so that we can safely create the new instance.
141   ScopedWriterLock instanceLock(mutex, threadingIsEnabled);
142 
143   // Check for an existing instance again here, because another writer thread
144   // may have already created one. Otherwise, construct a new instance.
145   auto existing = container.insert_as(ValueT(), key);
146   if (existing.second)
147     return *existing.first = constructorFn();
148   return *existing.first;
149 }
150 
151 namespace {
152 struct AffineMapKeyInfo : DenseMapInfo<AffineMap> {
153   // Affine maps are uniqued based on their dim/symbol counts and affine
154   // expressions.
155   using KeyTy = std::tuple<unsigned, unsigned, ArrayRef<AffineExpr>>;
156   using DenseMapInfo<AffineMap>::isEqual;
157 
158   static unsigned getHashValue(const AffineMap &key) {
159     return getHashValue(
160         KeyTy(key.getNumDims(), key.getNumSymbols(), key.getResults()));
161   }
162 
163   static unsigned getHashValue(KeyTy key) {
164     return hash_combine(
165         std::get<0>(key), std::get<1>(key),
166         hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()));
167   }
168 
169   static bool isEqual(const KeyTy &lhs, AffineMap rhs) {
170     if (rhs == getEmptyKey() || rhs == getTombstoneKey())
171       return false;
172     return lhs == std::make_tuple(rhs.getNumDims(), rhs.getNumSymbols(),
173                                   rhs.getResults());
174   }
175 };
176 
177 struct IntegerSetKeyInfo : DenseMapInfo<IntegerSet> {
178   // Integer sets are uniqued based on their dim/symbol counts, affine
179   // expressions appearing in the LHS of constraints, and eqFlags.
180   using KeyTy =
181       std::tuple<unsigned, unsigned, ArrayRef<AffineExpr>, ArrayRef<bool>>;
182   using DenseMapInfo<IntegerSet>::isEqual;
183 
184   static unsigned getHashValue(const IntegerSet &key) {
185     return getHashValue(KeyTy(key.getNumDims(), key.getNumSymbols(),
186                               key.getConstraints(), key.getEqFlags()));
187   }
188 
189   static unsigned getHashValue(KeyTy key) {
190     return hash_combine(
191         std::get<0>(key), std::get<1>(key),
192         hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()),
193         hash_combine_range(std::get<3>(key).begin(), std::get<3>(key).end()));
194   }
195 
196   static bool isEqual(const KeyTy &lhs, IntegerSet rhs) {
197     if (rhs == getEmptyKey() || rhs == getTombstoneKey())
198       return false;
199     return lhs == std::make_tuple(rhs.getNumDims(), rhs.getNumSymbols(),
200                                   rhs.getConstraints(), rhs.getEqFlags());
201   }
202 };
203 } // end anonymous namespace.
204 
205 //===----------------------------------------------------------------------===//
206 // MLIRContextImpl
207 //===----------------------------------------------------------------------===//
208 
209 namespace mlir {
210 /// This is the implementation of the MLIRContext class, using the pImpl idiom.
211 /// This class is completely private to this file, so everything is public.
212 class MLIRContextImpl {
213 public:
214   //===--------------------------------------------------------------------===//
215   // Debugging
216   //===--------------------------------------------------------------------===//
217 
218   /// An action manager for use within the context.
219   DebugActionManager debugActionManager;
220 
221   //===--------------------------------------------------------------------===//
222   // Identifier uniquing
223   //===--------------------------------------------------------------------===//
224 
225   // Identifier allocator and mutex for thread safety.
226   llvm::BumpPtrAllocator identifierAllocator;
227   llvm::sys::SmartRWMutex<true> identifierMutex;
228 
229   //===--------------------------------------------------------------------===//
230   // Diagnostics
231   //===--------------------------------------------------------------------===//
232   DiagnosticEngine diagEngine;
233 
234   //===--------------------------------------------------------------------===//
235   // Options
236   //===--------------------------------------------------------------------===//
237 
238   /// In most cases, creating operation in unregistered dialect is not desired
239   /// and indicate a misconfiguration of the compiler. This option enables to
240   /// detect such use cases
241   bool allowUnregisteredDialects = false;
242 
243   /// Enable support for multi-threading within MLIR.
244   bool threadingIsEnabled = true;
245 
246   /// Track if we are currently executing in a threaded execution environment
247   /// (like the pass-manager): this is only a debugging feature to help reducing
248   /// the chances of data races one some context APIs.
249 #ifndef NDEBUG
250   std::atomic<int> multiThreadedExecutionContext{0};
251 #endif
252 
253   /// If the operation should be attached to diagnostics printed via the
254   /// Operation::emit methods.
255   bool printOpOnDiagnostic = true;
256 
257   /// If the current stack trace should be attached when emitting diagnostics.
258   bool printStackTraceOnDiagnostic = false;
259 
260   //===--------------------------------------------------------------------===//
261   // Other
262   //===--------------------------------------------------------------------===//
263 
264   /// This is a list of dialects that are created referring to this context.
265   /// The MLIRContext owns the objects.
266   DenseMap<StringRef, std::unique_ptr<Dialect>> loadedDialects;
267   DialectRegistry dialectsRegistry;
268 
269   /// This is a mapping from operation name to AbstractOperation for registered
270   /// operations.
271   llvm::StringMap<AbstractOperation> registeredOperations;
272 
273   /// Identifiers are uniqued by string value and use the internal string set
274   /// for storage.
275   llvm::StringMap<PointerUnion<Dialect *, MLIRContext *>,
276                   llvm::BumpPtrAllocator &>
277       identifiers;
278   /// A thread local cache of identifiers to reduce lock contention.
279   ThreadLocalCache<llvm::StringMap<
280       llvm::StringMapEntry<PointerUnion<Dialect *, MLIRContext *>> *>>
281       localIdentifierCache;
282 
283   /// An allocator used for AbstractAttribute and AbstractType objects.
284   llvm::BumpPtrAllocator abstractDialectSymbolAllocator;
285 
286   //===--------------------------------------------------------------------===//
287   // Affine uniquing
288   //===--------------------------------------------------------------------===//
289 
290   // Affine allocator and mutex for thread safety.
291   llvm::BumpPtrAllocator affineAllocator;
292   llvm::sys::SmartRWMutex<true> affineMutex;
293 
294   // Affine map uniquing.
295   using AffineMapSet = DenseSet<AffineMap, AffineMapKeyInfo>;
296   AffineMapSet affineMaps;
297 
298   // Integer set uniquing.
299   using IntegerSets = DenseSet<IntegerSet, IntegerSetKeyInfo>;
300   IntegerSets integerSets;
301 
302   // Affine expression uniquing.
303   StorageUniquer affineUniquer;
304 
305   //===--------------------------------------------------------------------===//
306   // Type uniquing
307   //===--------------------------------------------------------------------===//
308 
309   DenseMap<TypeID, const AbstractType *> registeredTypes;
310   StorageUniquer typeUniquer;
311 
312   /// Cached Type Instances.
313   BFloat16Type bf16Ty;
314   Float16Type f16Ty;
315   Float32Type f32Ty;
316   Float64Type f64Ty;
317   Float80Type f80Ty;
318   Float128Type f128Ty;
319   IndexType indexTy;
320   IntegerType int1Ty, int8Ty, int16Ty, int32Ty, int64Ty, int128Ty;
321   NoneType noneType;
322 
323   //===--------------------------------------------------------------------===//
324   // Attribute uniquing
325   //===--------------------------------------------------------------------===//
326 
327   DenseMap<TypeID, const AbstractAttribute *> registeredAttributes;
328   StorageUniquer attributeUniquer;
329 
330   /// Cached Attribute Instances.
331   BoolAttr falseAttr, trueAttr;
332   UnitAttr unitAttr;
333   UnknownLoc unknownLocAttr;
334   DictionaryAttr emptyDictionaryAttr;
335 
336 public:
337   MLIRContextImpl() : identifiers(identifierAllocator) {}
338   ~MLIRContextImpl() {
339     for (auto typeMapping : registeredTypes)
340       typeMapping.second->~AbstractType();
341     for (auto attrMapping : registeredAttributes)
342       attrMapping.second->~AbstractAttribute();
343   }
344 };
345 } // end namespace mlir
346 
347 MLIRContext::MLIRContext() : MLIRContext(DialectRegistry()) {}
348 
349 MLIRContext::MLIRContext(const DialectRegistry &registry)
350     : impl(new MLIRContextImpl) {
351   // Initialize values based on the command line flags if they were provided.
352   if (clOptions.isConstructed()) {
353     disableMultithreading(clOptions->disableThreading);
354     printOpOnDiagnostic(clOptions->printOpOnDiagnostic);
355     printStackTraceOnDiagnostic(clOptions->printStackTraceOnDiagnostic);
356   }
357 
358   // Ensure the builtin dialect is always pre-loaded.
359   getOrLoadDialect<BuiltinDialect>();
360 
361   // Pre-populate the registry.
362   registry.appendTo(impl->dialectsRegistry);
363 
364   // Initialize several common attributes and types to avoid the need to lock
365   // the context when accessing them.
366 
367   //// Types.
368   /// Floating-point Types.
369   impl->bf16Ty = TypeUniquer::get<BFloat16Type>(this);
370   impl->f16Ty = TypeUniquer::get<Float16Type>(this);
371   impl->f32Ty = TypeUniquer::get<Float32Type>(this);
372   impl->f64Ty = TypeUniquer::get<Float64Type>(this);
373   impl->f80Ty = TypeUniquer::get<Float80Type>(this);
374   impl->f128Ty = TypeUniquer::get<Float128Type>(this);
375   /// Index Type.
376   impl->indexTy = TypeUniquer::get<IndexType>(this);
377   /// Integer Types.
378   impl->int1Ty = TypeUniquer::get<IntegerType>(this, 1, IntegerType::Signless);
379   impl->int8Ty = TypeUniquer::get<IntegerType>(this, 8, IntegerType::Signless);
380   impl->int16Ty =
381       TypeUniquer::get<IntegerType>(this, 16, IntegerType::Signless);
382   impl->int32Ty =
383       TypeUniquer::get<IntegerType>(this, 32, IntegerType::Signless);
384   impl->int64Ty =
385       TypeUniquer::get<IntegerType>(this, 64, IntegerType::Signless);
386   impl->int128Ty =
387       TypeUniquer::get<IntegerType>(this, 128, IntegerType::Signless);
388   /// None Type.
389   impl->noneType = TypeUniquer::get<NoneType>(this);
390 
391   //// Attributes.
392   //// Note: These must be registered after the types as they may generate one
393   //// of the above types internally.
394   /// Unknown Location Attribute.
395   impl->unknownLocAttr = AttributeUniquer::get<UnknownLoc>(this);
396   /// Bool Attributes.
397   impl->falseAttr = IntegerAttr::getBoolAttrUnchecked(impl->int1Ty, false);
398   impl->trueAttr = IntegerAttr::getBoolAttrUnchecked(impl->int1Ty, true);
399   /// Unit Attribute.
400   impl->unitAttr = AttributeUniquer::get<UnitAttr>(this);
401   /// The empty dictionary attribute.
402   impl->emptyDictionaryAttr = DictionaryAttr::getEmptyUnchecked(this);
403 
404   // Register the affine storage objects with the uniquer.
405   impl->affineUniquer
406       .registerParametricStorageType<AffineBinaryOpExprStorage>();
407   impl->affineUniquer
408       .registerParametricStorageType<AffineConstantExprStorage>();
409   impl->affineUniquer.registerParametricStorageType<AffineDimExprStorage>();
410 }
411 
412 MLIRContext::~MLIRContext() {}
413 
414 /// Copy the specified array of elements into memory managed by the provided
415 /// bump pointer allocator.  This assumes the elements are all PODs.
416 template <typename T>
417 static ArrayRef<T> copyArrayRefInto(llvm::BumpPtrAllocator &allocator,
418                                     ArrayRef<T> elements) {
419   auto result = allocator.Allocate<T>(elements.size());
420   std::uninitialized_copy(elements.begin(), elements.end(), result);
421   return ArrayRef<T>(result, elements.size());
422 }
423 
424 //===----------------------------------------------------------------------===//
425 // Debugging
426 //===----------------------------------------------------------------------===//
427 
428 DebugActionManager &MLIRContext::getDebugActionManager() {
429   return getImpl().debugActionManager;
430 }
431 
432 //===----------------------------------------------------------------------===//
433 // Diagnostic Handlers
434 //===----------------------------------------------------------------------===//
435 
436 /// Returns the diagnostic engine for this context.
437 DiagnosticEngine &MLIRContext::getDiagEngine() { return getImpl().diagEngine; }
438 
439 //===----------------------------------------------------------------------===//
440 // Dialect and Operation Registration
441 //===----------------------------------------------------------------------===//
442 
443 void MLIRContext::appendDialectRegistry(const DialectRegistry &registry) {
444   registry.appendTo(impl->dialectsRegistry);
445 
446   // For the already loaded dialects, register the interfaces immediately.
447   for (const auto &kvp : impl->loadedDialects)
448     registry.registerDelayedInterfaces(kvp.second.get());
449 }
450 
451 const DialectRegistry &MLIRContext::getDialectRegistry() {
452   return impl->dialectsRegistry;
453 }
454 
455 /// Return information about all registered IR dialects.
456 std::vector<Dialect *> MLIRContext::getLoadedDialects() {
457   std::vector<Dialect *> result;
458   result.reserve(impl->loadedDialects.size());
459   for (auto &dialect : impl->loadedDialects)
460     result.push_back(dialect.second.get());
461   llvm::array_pod_sort(result.begin(), result.end(),
462                        [](Dialect *const *lhs, Dialect *const *rhs) -> int {
463                          return (*lhs)->getNamespace() < (*rhs)->getNamespace();
464                        });
465   return result;
466 }
467 std::vector<StringRef> MLIRContext::getAvailableDialects() {
468   std::vector<StringRef> result;
469   for (auto dialect : impl->dialectsRegistry.getDialectNames())
470     result.push_back(dialect);
471   return result;
472 }
473 
474 /// Get a registered IR dialect with the given namespace. If none is found,
475 /// then return nullptr.
476 Dialect *MLIRContext::getLoadedDialect(StringRef name) {
477   // Dialects are sorted by name, so we can use binary search for lookup.
478   auto it = impl->loadedDialects.find(name);
479   return (it != impl->loadedDialects.end()) ? it->second.get() : nullptr;
480 }
481 
482 Dialect *MLIRContext::getOrLoadDialect(StringRef name) {
483   Dialect *dialect = getLoadedDialect(name);
484   if (dialect)
485     return dialect;
486   DialectAllocatorFunctionRef allocator =
487       impl->dialectsRegistry.getDialectAllocator(name);
488   return allocator ? allocator(this) : nullptr;
489 }
490 
491 /// Get a dialect for the provided namespace and TypeID: abort the program if a
492 /// dialect exist for this namespace with different TypeID. Returns a pointer to
493 /// the dialect owned by the context.
494 Dialect *
495 MLIRContext::getOrLoadDialect(StringRef dialectNamespace, TypeID dialectID,
496                               function_ref<std::unique_ptr<Dialect>()> ctor) {
497   auto &impl = getImpl();
498   // Get the correct insertion position sorted by namespace.
499   std::unique_ptr<Dialect> &dialect = impl.loadedDialects[dialectNamespace];
500 
501   if (!dialect) {
502     LLVM_DEBUG(llvm::dbgs()
503                << "Load new dialect in Context " << dialectNamespace << "\n");
504 #ifndef NDEBUG
505     if (impl.multiThreadedExecutionContext != 0)
506       llvm::report_fatal_error(
507           "Loading a dialect (" + dialectNamespace +
508           ") while in a multi-threaded execution context (maybe "
509           "the PassManager): this can indicate a "
510           "missing `dependentDialects` in a pass for example.");
511 #endif
512     dialect = ctor();
513     assert(dialect && "dialect ctor failed");
514 
515     // Refresh all the identifiers dialect field, this catches cases where a
516     // dialect may be loaded after identifier prefixed with this dialect name
517     // were already created.
518     llvm::SmallString<32> dialectPrefix(dialectNamespace);
519     dialectPrefix.push_back('.');
520     for (auto &identifierEntry : impl.identifiers)
521       if (identifierEntry.second.is<MLIRContext *>() &&
522           identifierEntry.first().startswith(dialectPrefix))
523         identifierEntry.second = dialect.get();
524 
525     // Actually register the interfaces with delayed registration.
526     impl.dialectsRegistry.registerDelayedInterfaces(dialect.get());
527     return dialect.get();
528   }
529 
530   // Abort if dialect with namespace has already been registered.
531   if (dialect->getTypeID() != dialectID)
532     llvm::report_fatal_error("a dialect with namespace '" + dialectNamespace +
533                              "' has already been registered");
534 
535   return dialect.get();
536 }
537 
538 void MLIRContext::loadAllAvailableDialects() {
539   for (StringRef name : getAvailableDialects())
540     getOrLoadDialect(name);
541 }
542 
543 llvm::hash_code MLIRContext::getRegistryHash() {
544   llvm::hash_code hash(0);
545   // Factor in number of loaded dialects, attributes, operations, types.
546   hash = llvm::hash_combine(hash, impl->loadedDialects.size());
547   hash = llvm::hash_combine(hash, impl->registeredAttributes.size());
548   hash = llvm::hash_combine(hash, impl->registeredOperations.size());
549   hash = llvm::hash_combine(hash, impl->registeredTypes.size());
550   return hash;
551 }
552 
553 bool MLIRContext::allowsUnregisteredDialects() {
554   return impl->allowUnregisteredDialects;
555 }
556 
557 void MLIRContext::allowUnregisteredDialects(bool allowing) {
558   impl->allowUnregisteredDialects = allowing;
559 }
560 
561 /// Return true if multi-threading is disabled by the context.
562 bool MLIRContext::isMultithreadingEnabled() {
563   return impl->threadingIsEnabled && llvm::llvm_is_multithreaded();
564 }
565 
566 /// Set the flag specifying if multi-threading is disabled by the context.
567 void MLIRContext::disableMultithreading(bool disable) {
568   impl->threadingIsEnabled = !disable;
569 
570   // Update the threading mode for each of the uniquers.
571   impl->affineUniquer.disableMultithreading(disable);
572   impl->attributeUniquer.disableMultithreading(disable);
573   impl->typeUniquer.disableMultithreading(disable);
574 }
575 
576 void MLIRContext::enterMultiThreadedExecution() {
577 #ifndef NDEBUG
578   ++impl->multiThreadedExecutionContext;
579 #endif
580 }
581 void MLIRContext::exitMultiThreadedExecution() {
582 #ifndef NDEBUG
583   --impl->multiThreadedExecutionContext;
584 #endif
585 }
586 
587 /// Return true if we should attach the operation to diagnostics emitted via
588 /// Operation::emit.
589 bool MLIRContext::shouldPrintOpOnDiagnostic() {
590   return impl->printOpOnDiagnostic;
591 }
592 
593 /// Set the flag specifying if we should attach the operation to diagnostics
594 /// emitted via Operation::emit.
595 void MLIRContext::printOpOnDiagnostic(bool enable) {
596   impl->printOpOnDiagnostic = enable;
597 }
598 
599 /// Return true if we should attach the current stacktrace to diagnostics when
600 /// emitted.
601 bool MLIRContext::shouldPrintStackTraceOnDiagnostic() {
602   return impl->printStackTraceOnDiagnostic;
603 }
604 
605 /// Set the flag specifying if we should attach the current stacktrace when
606 /// emitting diagnostics.
607 void MLIRContext::printStackTraceOnDiagnostic(bool enable) {
608   impl->printStackTraceOnDiagnostic = enable;
609 }
610 
611 /// Return information about all registered operations.  This isn't very
612 /// efficient, typically you should ask the operations about their properties
613 /// directly.
614 std::vector<AbstractOperation *> MLIRContext::getRegisteredOperations() {
615   // We just have the operations in a non-deterministic hash table order. Dump
616   // into a temporary array, then sort it by operation name to get a stable
617   // ordering.
618   llvm::StringMap<AbstractOperation> &registeredOps =
619       impl->registeredOperations;
620 
621   std::vector<AbstractOperation *> result;
622   result.reserve(registeredOps.size());
623   for (auto &elt : registeredOps)
624     result.push_back(&elt.second);
625   llvm::array_pod_sort(
626       result.begin(), result.end(),
627       [](AbstractOperation *const *lhs, AbstractOperation *const *rhs) {
628         return (*lhs)->name.compare((*rhs)->name);
629       });
630 
631   return result;
632 }
633 
634 bool MLIRContext::isOperationRegistered(StringRef name) {
635   return impl->registeredOperations.count(name);
636 }
637 
638 void Dialect::addType(TypeID typeID, AbstractType &&typeInfo) {
639   auto &impl = context->getImpl();
640   assert(impl.multiThreadedExecutionContext == 0 &&
641          "Registering a new type kind while in a multi-threaded execution "
642          "context");
643   auto *newInfo =
644       new (impl.abstractDialectSymbolAllocator.Allocate<AbstractType>())
645           AbstractType(std::move(typeInfo));
646   if (!impl.registeredTypes.insert({typeID, newInfo}).second)
647     llvm::report_fatal_error("Dialect Type already registered.");
648 }
649 
650 void Dialect::addAttribute(TypeID typeID, AbstractAttribute &&attrInfo) {
651   auto &impl = context->getImpl();
652   assert(impl.multiThreadedExecutionContext == 0 &&
653          "Registering a new attribute kind while in a multi-threaded execution "
654          "context");
655   auto *newInfo =
656       new (impl.abstractDialectSymbolAllocator.Allocate<AbstractAttribute>())
657           AbstractAttribute(std::move(attrInfo));
658   if (!impl.registeredAttributes.insert({typeID, newInfo}).second)
659     llvm::report_fatal_error("Dialect Attribute already registered.");
660 }
661 
662 //===----------------------------------------------------------------------===//
663 // AbstractAttribute
664 //===----------------------------------------------------------------------===//
665 
666 /// Get the dialect that registered the attribute with the provided typeid.
667 const AbstractAttribute &AbstractAttribute::lookup(TypeID typeID,
668                                                    MLIRContext *context) {
669   auto &impl = context->getImpl();
670   auto it = impl.registeredAttributes.find(typeID);
671   if (it == impl.registeredAttributes.end())
672     llvm::report_fatal_error("Trying to create an Attribute that was not "
673                              "registered in this MLIRContext.");
674   return *it->second;
675 }
676 
677 //===----------------------------------------------------------------------===//
678 // AbstractOperation
679 //===----------------------------------------------------------------------===//
680 
681 ParseResult AbstractOperation::parseAssembly(OpAsmParser &parser,
682                                              OperationState &result) const {
683   return parseAssemblyFn(parser, result);
684 }
685 
686 /// Look up the specified operation in the operation set and return a pointer
687 /// to it if present. Otherwise, return a null pointer.
688 const AbstractOperation *AbstractOperation::lookup(StringRef opName,
689                                                    MLIRContext *context) {
690   auto &impl = context->getImpl();
691   auto it = impl.registeredOperations.find(opName);
692   if (it != impl.registeredOperations.end())
693     return &it->second;
694   return nullptr;
695 }
696 
697 void AbstractOperation::insert(
698     StringRef name, Dialect &dialect, TypeID typeID,
699     ParseAssemblyFn parseAssembly, PrintAssemblyFn printAssembly,
700     VerifyInvariantsFn verifyInvariants, FoldHookFn foldHook,
701     GetCanonicalizationPatternsFn getCanonicalizationPatterns,
702     detail::InterfaceMap &&interfaceMap, HasTraitFn hasTrait) {
703   AbstractOperation opInfo(
704       name, dialect, typeID, parseAssembly, printAssembly, verifyInvariants,
705       foldHook, getCanonicalizationPatterns, std::move(interfaceMap), hasTrait);
706 
707   auto &impl = dialect.getContext()->getImpl();
708   assert(impl.multiThreadedExecutionContext == 0 &&
709          "Registering a new operation kind while in a multi-threaded execution "
710          "context");
711   if (!impl.registeredOperations.insert({name, std::move(opInfo)}).second) {
712     llvm::errs() << "error: operation named '" << name
713                  << "' is already registered.\n";
714     abort();
715   }
716 }
717 
718 AbstractOperation::AbstractOperation(
719     StringRef name, Dialect &dialect, TypeID typeID,
720     ParseAssemblyFn parseAssembly, PrintAssemblyFn printAssembly,
721     VerifyInvariantsFn verifyInvariants, FoldHookFn foldHook,
722     GetCanonicalizationPatternsFn getCanonicalizationPatterns,
723     detail::InterfaceMap &&interfaceMap, HasTraitFn hasTrait)
724     : name(Identifier::get(name, dialect.getContext())), dialect(dialect),
725       typeID(typeID), interfaceMap(std::move(interfaceMap)),
726       foldHookFn(foldHook),
727       getCanonicalizationPatternsFn(getCanonicalizationPatterns),
728       hasTraitFn(hasTrait), parseAssemblyFn(parseAssembly),
729       printAssemblyFn(printAssembly), verifyInvariantsFn(verifyInvariants) {}
730 
731 //===----------------------------------------------------------------------===//
732 // AbstractType
733 //===----------------------------------------------------------------------===//
734 
735 const AbstractType &AbstractType::lookup(TypeID typeID, MLIRContext *context) {
736   auto &impl = context->getImpl();
737   auto it = impl.registeredTypes.find(typeID);
738   if (it == impl.registeredTypes.end())
739     llvm::report_fatal_error(
740         "Trying to create a Type that was not registered in this MLIRContext.");
741   return *it->second;
742 }
743 
744 //===----------------------------------------------------------------------===//
745 // Identifier uniquing
746 //===----------------------------------------------------------------------===//
747 
748 /// Return an identifier for the specified string.
749 Identifier Identifier::get(StringRef str, MLIRContext *context) {
750   // Check invariants after seeing if we already have something in the
751   // identifier table - if we already had it in the table, then it already
752   // passed invariant checks.
753   assert(!str.empty() && "Cannot create an empty identifier");
754   assert(str.find('\0') == StringRef::npos &&
755          "Cannot create an identifier with a nul character");
756 
757   auto getDialectOrContext = [&]() {
758     PointerUnion<Dialect *, MLIRContext *> dialectOrContext = context;
759     auto dialectNamePair = str.split('.');
760     if (!dialectNamePair.first.empty())
761       if (Dialect *dialect = context->getLoadedDialect(dialectNamePair.first))
762         dialectOrContext = dialect;
763     return dialectOrContext;
764   };
765 
766   auto &impl = context->getImpl();
767   if (!context->isMultithreadingEnabled()) {
768     auto insertedIt = impl.identifiers.insert({str, nullptr});
769     if (insertedIt.second)
770       insertedIt.first->second = getDialectOrContext();
771     return Identifier(&*insertedIt.first);
772   }
773 
774   // Check for an existing instance in the local cache.
775   auto *&localEntry = (*impl.localIdentifierCache)[str];
776   if (localEntry)
777     return Identifier(localEntry);
778 
779   // Check for an existing identifier in read-only mode.
780   {
781     llvm::sys::SmartScopedReader<true> contextLock(impl.identifierMutex);
782     auto it = impl.identifiers.find(str);
783     if (it != impl.identifiers.end()) {
784       localEntry = &*it;
785       return Identifier(localEntry);
786     }
787   }
788 
789   // Acquire a writer-lock so that we can safely create the new instance.
790   llvm::sys::SmartScopedWriter<true> contextLock(impl.identifierMutex);
791   auto it = impl.identifiers.insert({str, getDialectOrContext()}).first;
792   localEntry = &*it;
793   return Identifier(localEntry);
794 }
795 
796 Dialect *Identifier::getDialect() {
797   return entry->second.dyn_cast<Dialect *>();
798 }
799 
800 MLIRContext *Identifier::getContext() {
801   if (Dialect *dialect = getDialect())
802     return dialect->getContext();
803   return entry->second.get<MLIRContext *>();
804 }
805 
806 //===----------------------------------------------------------------------===//
807 // Type uniquing
808 //===----------------------------------------------------------------------===//
809 
810 /// Returns the storage uniquer used for constructing type storage instances.
811 /// This should not be used directly.
812 StorageUniquer &MLIRContext::getTypeUniquer() { return getImpl().typeUniquer; }
813 
814 BFloat16Type BFloat16Type::get(MLIRContext *context) {
815   return context->getImpl().bf16Ty;
816 }
817 Float16Type Float16Type::get(MLIRContext *context) {
818   return context->getImpl().f16Ty;
819 }
820 Float32Type Float32Type::get(MLIRContext *context) {
821   return context->getImpl().f32Ty;
822 }
823 Float64Type Float64Type::get(MLIRContext *context) {
824   return context->getImpl().f64Ty;
825 }
826 Float80Type Float80Type::get(MLIRContext *context) {
827   return context->getImpl().f80Ty;
828 }
829 Float128Type Float128Type::get(MLIRContext *context) {
830   return context->getImpl().f128Ty;
831 }
832 
833 /// Get an instance of the IndexType.
834 IndexType IndexType::get(MLIRContext *context) {
835   return context->getImpl().indexTy;
836 }
837 
838 /// Return an existing integer type instance if one is cached within the
839 /// context.
840 static IntegerType
841 getCachedIntegerType(unsigned width,
842                      IntegerType::SignednessSemantics signedness,
843                      MLIRContext *context) {
844   if (signedness != IntegerType::Signless)
845     return IntegerType();
846 
847   switch (width) {
848   case 1:
849     return context->getImpl().int1Ty;
850   case 8:
851     return context->getImpl().int8Ty;
852   case 16:
853     return context->getImpl().int16Ty;
854   case 32:
855     return context->getImpl().int32Ty;
856   case 64:
857     return context->getImpl().int64Ty;
858   case 128:
859     return context->getImpl().int128Ty;
860   default:
861     return IntegerType();
862   }
863 }
864 
865 IntegerType IntegerType::get(MLIRContext *context, unsigned width,
866                              IntegerType::SignednessSemantics signedness) {
867   if (auto cached = getCachedIntegerType(width, signedness, context))
868     return cached;
869   return Base::get(context, width, signedness);
870 }
871 
872 IntegerType
873 IntegerType::getChecked(function_ref<InFlightDiagnostic()> emitError,
874                         MLIRContext *context, unsigned width,
875                         SignednessSemantics signedness) {
876   if (auto cached = getCachedIntegerType(width, signedness, context))
877     return cached;
878   return Base::getChecked(emitError, context, width, signedness);
879 }
880 
881 /// Get an instance of the NoneType.
882 NoneType NoneType::get(MLIRContext *context) {
883   if (NoneType cachedInst = context->getImpl().noneType)
884     return cachedInst;
885   // Note: May happen when initializing the singleton attributes of the builtin
886   // dialect.
887   return Base::get(context);
888 }
889 
890 //===----------------------------------------------------------------------===//
891 // Attribute uniquing
892 //===----------------------------------------------------------------------===//
893 
894 /// Returns the storage uniquer used for constructing attribute storage
895 /// instances. This should not be used directly.
896 StorageUniquer &MLIRContext::getAttributeUniquer() {
897   return getImpl().attributeUniquer;
898 }
899 
900 /// Initialize the given attribute storage instance.
901 void AttributeUniquer::initializeAttributeStorage(AttributeStorage *storage,
902                                                   MLIRContext *ctx,
903                                                   TypeID attrID) {
904   storage->initialize(AbstractAttribute::lookup(attrID, ctx));
905 
906   // If the attribute did not provide a type, then default to NoneType.
907   if (!storage->getType())
908     storage->setType(NoneType::get(ctx));
909 }
910 
911 BoolAttr BoolAttr::get(MLIRContext *context, bool value) {
912   return value ? context->getImpl().trueAttr : context->getImpl().falseAttr;
913 }
914 
915 UnitAttr UnitAttr::get(MLIRContext *context) {
916   return context->getImpl().unitAttr;
917 }
918 
919 UnknownLoc UnknownLoc::get(MLIRContext *context) {
920   return context->getImpl().unknownLocAttr;
921 }
922 
923 /// Return empty dictionary.
924 DictionaryAttr DictionaryAttr::getEmpty(MLIRContext *context) {
925   return context->getImpl().emptyDictionaryAttr;
926 }
927 
928 //===----------------------------------------------------------------------===//
929 // AffineMap uniquing
930 //===----------------------------------------------------------------------===//
931 
932 StorageUniquer &MLIRContext::getAffineUniquer() {
933   return getImpl().affineUniquer;
934 }
935 
936 AffineMap AffineMap::getImpl(unsigned dimCount, unsigned symbolCount,
937                              ArrayRef<AffineExpr> results,
938                              MLIRContext *context) {
939   auto &impl = context->getImpl();
940   auto key = std::make_tuple(dimCount, symbolCount, results);
941 
942   // Safely get or create an AffineMap instance.
943   return safeGetOrCreate(
944       impl.affineMaps, key, impl.affineMutex, impl.threadingIsEnabled, [&] {
945         auto *res = impl.affineAllocator.Allocate<detail::AffineMapStorage>();
946 
947         // Copy the results into the bump pointer.
948         results = copyArrayRefInto(impl.affineAllocator, results);
949 
950         // Initialize the memory using placement new.
951         new (res)
952             detail::AffineMapStorage{dimCount, symbolCount, results, context};
953         return AffineMap(res);
954       });
955 }
956 
957 AffineMap AffineMap::get(MLIRContext *context) {
958   return getImpl(/*dimCount=*/0, /*symbolCount=*/0, /*results=*/{}, context);
959 }
960 
961 AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
962                          MLIRContext *context) {
963   return getImpl(dimCount, symbolCount, /*results=*/{}, context);
964 }
965 
966 AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
967                          AffineExpr result) {
968   return getImpl(dimCount, symbolCount, {result}, result.getContext());
969 }
970 
971 AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
972                          ArrayRef<AffineExpr> results, MLIRContext *context) {
973   return getImpl(dimCount, symbolCount, results, context);
974 }
975 
976 //===----------------------------------------------------------------------===//
977 // Integer Sets: these are allocated into the bump pointer, and are immutable.
978 // Unlike AffineMap's, these are uniqued only if they are small.
979 //===----------------------------------------------------------------------===//
980 
981 IntegerSet IntegerSet::get(unsigned dimCount, unsigned symbolCount,
982                            ArrayRef<AffineExpr> constraints,
983                            ArrayRef<bool> eqFlags) {
984   // The number of constraints can't be zero.
985   assert(!constraints.empty());
986   assert(constraints.size() == eqFlags.size());
987 
988   auto &impl = constraints[0].getContext()->getImpl();
989 
990   // A utility function to construct a new IntegerSetStorage instance.
991   auto constructorFn = [&] {
992     auto *res = impl.affineAllocator.Allocate<detail::IntegerSetStorage>();
993 
994     // Copy the results and equality flags into the bump pointer.
995     constraints = copyArrayRefInto(impl.affineAllocator, constraints);
996     eqFlags = copyArrayRefInto(impl.affineAllocator, eqFlags);
997 
998     // Initialize the memory using placement new.
999     new (res)
1000         detail::IntegerSetStorage{dimCount, symbolCount, constraints, eqFlags};
1001     return IntegerSet(res);
1002   };
1003 
1004   // If this instance is uniqued, then we handle it separately so that multiple
1005   // threads may simultaneously access existing instances.
1006   if (constraints.size() < IntegerSet::kUniquingThreshold) {
1007     auto key = std::make_tuple(dimCount, symbolCount, constraints, eqFlags);
1008     return safeGetOrCreate(impl.integerSets, key, impl.affineMutex,
1009                            impl.threadingIsEnabled, constructorFn);
1010   }
1011 
1012   // Otherwise, acquire a writer-lock so that we can safely create the new
1013   // instance.
1014   ScopedWriterLock affineLock(impl.affineMutex, impl.threadingIsEnabled);
1015   return constructorFn();
1016 }
1017 
1018 //===----------------------------------------------------------------------===//
1019 // StorageUniquerSupport
1020 //===----------------------------------------------------------------------===//
1021 
1022 /// Utility method to generate a callback that can be used to generate a
1023 /// diagnostic when checking the construction invariants of a storage object.
1024 /// This is defined out-of-line to avoid the need to include Location.h.
1025 llvm::unique_function<InFlightDiagnostic()>
1026 mlir::detail::getDefaultDiagnosticEmitFn(MLIRContext *ctx) {
1027   return [ctx] { return emitError(UnknownLoc::get(ctx)); };
1028 }
1029 llvm::unique_function<InFlightDiagnostic()>
1030 mlir::detail::getDefaultDiagnosticEmitFn(const Location &loc) {
1031   return [=] { return emitError(loc); };
1032 }
1033