1 //===- IRModules.h - IR Submodules of pybind module -----------------------===//
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_BINDINGS_PYTHON_IRMODULES_H
10 #define MLIR_BINDINGS_PYTHON_IRMODULES_H
11 
12 #include <vector>
13 
14 #include "PybindUtils.h"
15 
16 #include "mlir-c/AffineExpr.h"
17 #include "mlir-c/AffineMap.h"
18 #include "mlir-c/IR.h"
19 #include "mlir-c/IntegerSet.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/Optional.h"
22 
23 namespace mlir {
24 namespace python {
25 
26 class PyBlock;
27 class PyInsertionPoint;
28 class PyLocation;
29 class DefaultingPyLocation;
30 class PyMlirContext;
31 class DefaultingPyMlirContext;
32 class PyModule;
33 class PyOperation;
34 class PyType;
35 class PySymbolTable;
36 class PyValue;
37 
38 /// Template for a reference to a concrete type which captures a python
39 /// reference to its underlying python object.
40 template <typename T>
41 class PyObjectRef {
42 public:
43   PyObjectRef(T *referrent, pybind11::object object)
44       : referrent(referrent), object(std::move(object)) {
45     assert(this->referrent &&
46            "cannot construct PyObjectRef with null referrent");
47     assert(this->object && "cannot construct PyObjectRef with null object");
48   }
49   PyObjectRef(PyObjectRef &&other)
50       : referrent(other.referrent), object(std::move(other.object)) {
51     other.referrent = nullptr;
52     assert(!other.object);
53   }
54   PyObjectRef(const PyObjectRef &other)
55       : referrent(other.referrent), object(other.object /* copies */) {}
56   ~PyObjectRef() {}
57 
58   int getRefCount() {
59     if (!object)
60       return 0;
61     return object.ref_count();
62   }
63 
64   /// Releases the object held by this instance, returning it.
65   /// This is the proper thing to return from a function that wants to return
66   /// the reference. Note that this does not work from initializers.
67   pybind11::object releaseObject() {
68     assert(referrent && object);
69     referrent = nullptr;
70     auto stolen = std::move(object);
71     return stolen;
72   }
73 
74   T *get() { return referrent; }
75   T *operator->() {
76     assert(referrent && object);
77     return referrent;
78   }
79   pybind11::object getObject() {
80     assert(referrent && object);
81     return object;
82   }
83   operator bool() const { return referrent && object; }
84 
85 private:
86   T *referrent;
87   pybind11::object object;
88 };
89 
90 /// Tracks an entry in the thread context stack. New entries are pushed onto
91 /// here for each with block that activates a new InsertionPoint, Context or
92 /// Location.
93 ///
94 /// Pushing either a Location or InsertionPoint also pushes its associated
95 /// Context. Pushing a Context will not modify the Location or InsertionPoint
96 /// unless if they are from a different context, in which case, they are
97 /// cleared.
98 class PyThreadContextEntry {
99 public:
100   enum class FrameKind {
101     Context,
102     InsertionPoint,
103     Location,
104   };
105 
106   PyThreadContextEntry(FrameKind frameKind, pybind11::object context,
107                        pybind11::object insertionPoint,
108                        pybind11::object location)
109       : context(std::move(context)), insertionPoint(std::move(insertionPoint)),
110         location(std::move(location)), frameKind(frameKind) {}
111 
112   /// Gets the top of stack context and return nullptr if not defined.
113   static PyMlirContext *getDefaultContext();
114 
115   /// Gets the top of stack insertion point and return nullptr if not defined.
116   static PyInsertionPoint *getDefaultInsertionPoint();
117 
118   /// Gets the top of stack location and returns nullptr if not defined.
119   static PyLocation *getDefaultLocation();
120 
121   PyMlirContext *getContext();
122   PyInsertionPoint *getInsertionPoint();
123   PyLocation *getLocation();
124   FrameKind getFrameKind() { return frameKind; }
125 
126   /// Stack management.
127   static PyThreadContextEntry *getTopOfStack();
128   static pybind11::object pushContext(PyMlirContext &context);
129   static void popContext(PyMlirContext &context);
130   static pybind11::object pushInsertionPoint(PyInsertionPoint &insertionPoint);
131   static void popInsertionPoint(PyInsertionPoint &insertionPoint);
132   static pybind11::object pushLocation(PyLocation &location);
133   static void popLocation(PyLocation &location);
134 
135   /// Gets the thread local stack.
136   static std::vector<PyThreadContextEntry> &getStack();
137 
138 private:
139   static void push(FrameKind frameKind, pybind11::object context,
140                    pybind11::object insertionPoint, pybind11::object location);
141 
142   /// An object reference to the PyContext.
143   pybind11::object context;
144   /// An object reference to the current insertion point.
145   pybind11::object insertionPoint;
146   /// An object reference to the current location.
147   pybind11::object location;
148   // The kind of push that was performed.
149   FrameKind frameKind;
150 };
151 
152 /// Wrapper around MlirContext.
153 using PyMlirContextRef = PyObjectRef<PyMlirContext>;
154 class PyMlirContext {
155 public:
156   PyMlirContext() = delete;
157   PyMlirContext(const PyMlirContext &) = delete;
158   PyMlirContext(PyMlirContext &&) = delete;
159 
160   /// For the case of a python __init__ (py::init) method, pybind11 is quite
161   /// strict about needing to return a pointer that is not yet associated to
162   /// an py::object. Since the forContext() method acts like a pool, possibly
163   /// returning a recycled context, it does not satisfy this need. The usual
164   /// way in python to accomplish such a thing is to override __new__, but
165   /// that is also not supported by pybind11. Instead, we use this entry
166   /// point which always constructs a fresh context (which cannot alias an
167   /// existing one because it is fresh).
168   static PyMlirContext *createNewContextForInit();
169 
170   /// Returns a context reference for the singleton PyMlirContext wrapper for
171   /// the given context.
172   static PyMlirContextRef forContext(MlirContext context);
173   ~PyMlirContext();
174 
175   /// Accesses the underlying MlirContext.
176   MlirContext get() { return context; }
177 
178   /// Gets a strong reference to this context, which will ensure it is kept
179   /// alive for the life of the reference.
180   PyMlirContextRef getRef() {
181     return PyMlirContextRef(this, pybind11::cast(this));
182   }
183 
184   /// Gets a capsule wrapping the void* within the MlirContext.
185   pybind11::object getCapsule();
186 
187   /// Creates a PyMlirContext from the MlirContext wrapped by a capsule.
188   /// Note that PyMlirContext instances are uniqued, so the returned object
189   /// may be a pre-existing object. Ownership of the underlying MlirContext
190   /// is taken by calling this function.
191   static pybind11::object createFromCapsule(pybind11::object capsule);
192 
193   /// Gets the count of live context objects. Used for testing.
194   static size_t getLiveCount();
195 
196   /// Gets the count of live operations associated with this context.
197   /// Used for testing.
198   size_t getLiveOperationCount();
199 
200   /// Gets the count of live modules associated with this context.
201   /// Used for testing.
202   size_t getLiveModuleCount();
203 
204   /// Enter and exit the context manager.
205   pybind11::object contextEnter();
206   void contextExit(pybind11::object excType, pybind11::object excVal,
207                    pybind11::object excTb);
208 
209 private:
210   PyMlirContext(MlirContext context);
211   // Interns the mapping of live MlirContext::ptr to PyMlirContext instances,
212   // preserving the relationship that an MlirContext maps to a single
213   // PyMlirContext wrapper. This could be replaced in the future with an
214   // extension mechanism on the MlirContext for stashing user pointers.
215   // Note that this holds a handle, which does not imply ownership.
216   // Mappings will be removed when the context is destructed.
217   using LiveContextMap = llvm::DenseMap<void *, PyMlirContext *>;
218   static LiveContextMap &getLiveContexts();
219 
220   // Interns all live modules associated with this context. Modules tracked
221   // in this map are valid. When a module is invalidated, it is removed
222   // from this map, and while it still exists as an instance, any
223   // attempt to access it will raise an error.
224   using LiveModuleMap =
225       llvm::DenseMap<const void *, std::pair<pybind11::handle, PyModule *>>;
226   LiveModuleMap liveModules;
227 
228   // Interns all live operations associated with this context. Operations
229   // tracked in this map are valid. When an operation is invalidated, it is
230   // removed from this map, and while it still exists as an instance, any
231   // attempt to access it will raise an error.
232   using LiveOperationMap =
233       llvm::DenseMap<void *, std::pair<pybind11::handle, PyOperation *>>;
234   LiveOperationMap liveOperations;
235 
236   MlirContext context;
237   friend class PyModule;
238   friend class PyOperation;
239 };
240 
241 /// Used in function arguments when None should resolve to the current context
242 /// manager set instance.
243 class DefaultingPyMlirContext
244     : public Defaulting<DefaultingPyMlirContext, PyMlirContext> {
245 public:
246   using Defaulting::Defaulting;
247   static constexpr const char kTypeDescription[] =
248       "[ThreadContextAware] mlir.ir.Context";
249   static PyMlirContext &resolve();
250 };
251 
252 /// Base class for all objects that directly or indirectly depend on an
253 /// MlirContext. The lifetime of the context will extend at least to the
254 /// lifetime of these instances.
255 /// Immutable objects that depend on a context extend this directly.
256 class BaseContextObject {
257 public:
258   BaseContextObject(PyMlirContextRef ref) : contextRef(std::move(ref)) {
259     assert(this->contextRef &&
260            "context object constructed with null context ref");
261   }
262 
263   /// Accesses the context reference.
264   PyMlirContextRef &getContext() { return contextRef; }
265 
266 private:
267   PyMlirContextRef contextRef;
268 };
269 
270 /// Wrapper around an MlirDialect. This is exported as `DialectDescriptor` in
271 /// order to differentiate it from the `Dialect` base class which is extended by
272 /// plugins which extend dialect functionality through extension python code.
273 /// This should be seen as the "low-level" object and `Dialect` as the
274 /// high-level, user facing object.
275 class PyDialectDescriptor : public BaseContextObject {
276 public:
277   PyDialectDescriptor(PyMlirContextRef contextRef, MlirDialect dialect)
278       : BaseContextObject(std::move(contextRef)), dialect(dialect) {}
279 
280   MlirDialect get() { return dialect; }
281 
282 private:
283   MlirDialect dialect;
284 };
285 
286 /// User-level object for accessing dialects with dotted syntax such as:
287 ///   ctx.dialect.std
288 class PyDialects : public BaseContextObject {
289 public:
290   PyDialects(PyMlirContextRef contextRef)
291       : BaseContextObject(std::move(contextRef)) {}
292 
293   MlirDialect getDialectForKey(const std::string &key, bool attrError);
294 };
295 
296 /// User-level dialect object. For dialects that have a registered extension,
297 /// this will be the base class of the extension dialect type. For un-extended,
298 /// objects of this type will be returned directly.
299 class PyDialect {
300 public:
301   PyDialect(pybind11::object descriptor) : descriptor(std::move(descriptor)) {}
302 
303   pybind11::object getDescriptor() { return descriptor; }
304 
305 private:
306   pybind11::object descriptor;
307 };
308 
309 /// Wrapper around an MlirLocation.
310 class PyLocation : public BaseContextObject {
311 public:
312   PyLocation(PyMlirContextRef contextRef, MlirLocation loc)
313       : BaseContextObject(std::move(contextRef)), loc(loc) {}
314 
315   operator MlirLocation() const { return loc; }
316   MlirLocation get() const { return loc; }
317 
318   /// Enter and exit the context manager.
319   pybind11::object contextEnter();
320   void contextExit(pybind11::object excType, pybind11::object excVal,
321                    pybind11::object excTb);
322 
323   /// Gets a capsule wrapping the void* within the MlirLocation.
324   pybind11::object getCapsule();
325 
326   /// Creates a PyLocation from the MlirLocation wrapped by a capsule.
327   /// Note that PyLocation instances are uniqued, so the returned object
328   /// may be a pre-existing object. Ownership of the underlying MlirLocation
329   /// is taken by calling this function.
330   static PyLocation createFromCapsule(pybind11::object capsule);
331 
332 private:
333   MlirLocation loc;
334 };
335 
336 /// Used in function arguments when None should resolve to the current context
337 /// manager set instance.
338 class DefaultingPyLocation
339     : public Defaulting<DefaultingPyLocation, PyLocation> {
340 public:
341   using Defaulting::Defaulting;
342   static constexpr const char kTypeDescription[] =
343       "[ThreadContextAware] mlir.ir.Location";
344   static PyLocation &resolve();
345 
346   operator MlirLocation() const { return *get(); }
347 };
348 
349 /// Wrapper around MlirModule.
350 /// This is the top-level, user-owned object that contains regions/ops/blocks.
351 class PyModule;
352 using PyModuleRef = PyObjectRef<PyModule>;
353 class PyModule : public BaseContextObject {
354 public:
355   /// Returns a PyModule reference for the given MlirModule. This may return
356   /// a pre-existing or new object.
357   static PyModuleRef forModule(MlirModule module);
358   PyModule(PyModule &) = delete;
359   PyModule(PyMlirContext &&) = delete;
360   ~PyModule();
361 
362   /// Gets the backing MlirModule.
363   MlirModule get() { return module; }
364 
365   /// Gets a strong reference to this module.
366   PyModuleRef getRef() {
367     return PyModuleRef(this,
368                        pybind11::reinterpret_borrow<pybind11::object>(handle));
369   }
370 
371   /// Gets a capsule wrapping the void* within the MlirModule.
372   /// Note that the module does not (yet) provide a corresponding factory for
373   /// constructing from a capsule as that would require uniquing PyModule
374   /// instances, which is not currently done.
375   pybind11::object getCapsule();
376 
377   /// Creates a PyModule from the MlirModule wrapped by a capsule.
378   /// Note that PyModule instances are uniqued, so the returned object
379   /// may be a pre-existing object. Ownership of the underlying MlirModule
380   /// is taken by calling this function.
381   static pybind11::object createFromCapsule(pybind11::object capsule);
382 
383 private:
384   PyModule(PyMlirContextRef contextRef, MlirModule module);
385   MlirModule module;
386   pybind11::handle handle;
387 };
388 
389 /// Base class for PyOperation and PyOpView which exposes the primary, user
390 /// visible methods for manipulating it.
391 class PyOperationBase {
392 public:
393   virtual ~PyOperationBase() = default;
394   /// Implements the bound 'print' method and helps with others.
395   void print(pybind11::object fileObject, bool binary,
396              llvm::Optional<int64_t> largeElementsLimit, bool enableDebugInfo,
397              bool prettyDebugInfo, bool printGenericOpForm, bool useLocalScope);
398   pybind11::object getAsm(bool binary,
399                           llvm::Optional<int64_t> largeElementsLimit,
400                           bool enableDebugInfo, bool prettyDebugInfo,
401                           bool printGenericOpForm, bool useLocalScope);
402 
403   /// Moves the operation before or after the other operation.
404   void moveAfter(PyOperationBase &other);
405   void moveBefore(PyOperationBase &other);
406 
407   /// Each must provide access to the raw Operation.
408   virtual PyOperation &getOperation() = 0;
409 };
410 
411 /// Wrapper around PyOperation.
412 /// Operations exist in either an attached (dependent) or detached (top-level)
413 /// state. In the detached state (as on creation), an operation is owned by
414 /// the creator and its lifetime extends either until its reference count
415 /// drops to zero or it is attached to a parent, at which point its lifetime
416 /// is bounded by its top-level parent reference.
417 class PyOperation;
418 using PyOperationRef = PyObjectRef<PyOperation>;
419 class PyOperation : public PyOperationBase, public BaseContextObject {
420 public:
421   ~PyOperation();
422   PyOperation &getOperation() override { return *this; }
423 
424   /// Returns a PyOperation for the given MlirOperation, optionally associating
425   /// it with a parentKeepAlive.
426   static PyOperationRef
427   forOperation(PyMlirContextRef contextRef, MlirOperation operation,
428                pybind11::object parentKeepAlive = pybind11::object());
429 
430   /// Creates a detached operation. The operation must not be associated with
431   /// any existing live operation.
432   static PyOperationRef
433   createDetached(PyMlirContextRef contextRef, MlirOperation operation,
434                  pybind11::object parentKeepAlive = pybind11::object());
435 
436   /// Detaches the operation from its parent block and updates its state
437   /// accordingly.
438   void detachFromParent() {
439     mlirOperationRemoveFromParent(getOperation());
440     setDetached();
441     parentKeepAlive = pybind11::object();
442   }
443 
444   /// Gets the backing operation.
445   operator MlirOperation() const { return get(); }
446   MlirOperation get() const {
447     checkValid();
448     return operation;
449   }
450 
451   PyOperationRef getRef() {
452     return PyOperationRef(
453         this, pybind11::reinterpret_borrow<pybind11::object>(handle));
454   }
455 
456   bool isAttached() { return attached; }
457   void setAttached(pybind11::object parent = pybind11::object()) {
458     assert(!attached && "operation already attached");
459     attached = true;
460   }
461   void setDetached() {
462     assert(attached && "operation already detached");
463     attached = false;
464   }
465   void checkValid() const;
466 
467   /// Gets the owning block or raises an exception if the operation has no
468   /// owning block.
469   PyBlock getBlock();
470 
471   /// Gets the parent operation or raises an exception if the operation has
472   /// no parent.
473   llvm::Optional<PyOperationRef> getParentOperation();
474 
475   /// Gets a capsule wrapping the void* within the MlirOperation.
476   pybind11::object getCapsule();
477 
478   /// Creates a PyOperation from the MlirOperation wrapped by a capsule.
479   /// Ownership of the underlying MlirOperation is taken by calling this
480   /// function.
481   static pybind11::object createFromCapsule(pybind11::object capsule);
482 
483   /// Creates an operation. See corresponding python docstring.
484   static pybind11::object
485   create(std::string name, llvm::Optional<std::vector<PyType *>> results,
486          llvm::Optional<std::vector<PyValue *>> operands,
487          llvm::Optional<pybind11::dict> attributes,
488          llvm::Optional<std::vector<PyBlock *>> successors, int regions,
489          DefaultingPyLocation location, pybind11::object ip);
490 
491   /// Creates an OpView suitable for this operation.
492   pybind11::object createOpView();
493 
494   /// Erases the underlying MlirOperation, removes its pointer from the
495   /// parent context's live operations map, and sets the valid bit false.
496   void erase();
497 
498 private:
499   PyOperation(PyMlirContextRef contextRef, MlirOperation operation);
500   static PyOperationRef createInstance(PyMlirContextRef contextRef,
501                                        MlirOperation operation,
502                                        pybind11::object parentKeepAlive);
503 
504   MlirOperation operation;
505   pybind11::handle handle;
506   // Keeps the parent alive, regardless of whether it is an Operation or
507   // Module.
508   // TODO: As implemented, this facility is only sufficient for modeling the
509   // trivial module parent back-reference. Generalize this to also account for
510   // transitions from detached to attached and address TODOs in the
511   // ir_operation.py regarding testing corresponding lifetime guarantees.
512   pybind11::object parentKeepAlive;
513   bool attached = true;
514   bool valid = true;
515 
516   friend class PyOperationBase;
517   friend class PySymbolTable;
518 };
519 
520 /// A PyOpView is equivalent to the C++ "Op" wrappers: these are the basis for
521 /// providing more instance-specific accessors and serve as the base class for
522 /// custom ODS-style operation classes. Since this class is subclass on the
523 /// python side, it must present an __init__ method that operates in pure
524 /// python types.
525 class PyOpView : public PyOperationBase {
526 public:
527   PyOpView(pybind11::object operationObject);
528   PyOperation &getOperation() override { return operation; }
529 
530   static pybind11::object createRawSubclass(pybind11::object userClass);
531 
532   pybind11::object getOperationObject() { return operationObject; }
533 
534   static pybind11::object
535   buildGeneric(pybind11::object cls, pybind11::list resultTypeList,
536                pybind11::list operandList,
537                llvm::Optional<pybind11::dict> attributes,
538                llvm::Optional<std::vector<PyBlock *>> successors,
539                llvm::Optional<int> regions, DefaultingPyLocation location,
540                pybind11::object maybeIp);
541 
542 private:
543   PyOperation &operation;           // For efficient, cast-free access from C++
544   pybind11::object operationObject; // Holds the reference.
545 };
546 
547 /// Wrapper around an MlirRegion.
548 /// Regions are managed completely by their containing operation. Unlike the
549 /// C++ API, the python API does not support detached regions.
550 class PyRegion {
551 public:
552   PyRegion(PyOperationRef parentOperation, MlirRegion region)
553       : parentOperation(std::move(parentOperation)), region(region) {
554     assert(!mlirRegionIsNull(region) && "python region cannot be null");
555   }
556   operator MlirRegion() const { return region; }
557 
558   MlirRegion get() { return region; }
559   PyOperationRef &getParentOperation() { return parentOperation; }
560 
561   void checkValid() { return parentOperation->checkValid(); }
562 
563 private:
564   PyOperationRef parentOperation;
565   MlirRegion region;
566 };
567 
568 /// Wrapper around an MlirBlock.
569 /// Blocks are managed completely by their containing operation. Unlike the
570 /// C++ API, the python API does not support detached blocks.
571 class PyBlock {
572 public:
573   PyBlock(PyOperationRef parentOperation, MlirBlock block)
574       : parentOperation(std::move(parentOperation)), block(block) {
575     assert(!mlirBlockIsNull(block) && "python block cannot be null");
576   }
577 
578   MlirBlock get() { return block; }
579   PyOperationRef &getParentOperation() { return parentOperation; }
580 
581   void checkValid() { return parentOperation->checkValid(); }
582 
583 private:
584   PyOperationRef parentOperation;
585   MlirBlock block;
586 };
587 
588 /// An insertion point maintains a pointer to a Block and a reference operation.
589 /// Calls to insert() will insert a new operation before the
590 /// reference operation. If the reference operation is null, then appends to
591 /// the end of the block.
592 class PyInsertionPoint {
593 public:
594   /// Creates an insertion point positioned after the last operation in the
595   /// block, but still inside the block.
596   PyInsertionPoint(PyBlock &block);
597   /// Creates an insertion point positioned before a reference operation.
598   PyInsertionPoint(PyOperationBase &beforeOperationBase);
599 
600   /// Shortcut to create an insertion point at the beginning of the block.
601   static PyInsertionPoint atBlockBegin(PyBlock &block);
602   /// Shortcut to create an insertion point before the block terminator.
603   static PyInsertionPoint atBlockTerminator(PyBlock &block);
604 
605   /// Inserts an operation.
606   void insert(PyOperationBase &operationBase);
607 
608   /// Enter and exit the context manager.
609   pybind11::object contextEnter();
610   void contextExit(pybind11::object excType, pybind11::object excVal,
611                    pybind11::object excTb);
612 
613   PyBlock &getBlock() { return block; }
614 
615 private:
616   // Trampoline constructor that avoids null initializing members while
617   // looking up parents.
618   PyInsertionPoint(PyBlock block, llvm::Optional<PyOperationRef> refOperation)
619       : refOperation(std::move(refOperation)), block(std::move(block)) {}
620 
621   llvm::Optional<PyOperationRef> refOperation;
622   PyBlock block;
623 };
624 /// Wrapper around the generic MlirType.
625 /// The lifetime of a type is bound by the PyContext that created it.
626 class PyType : public BaseContextObject {
627 public:
628   PyType(PyMlirContextRef contextRef, MlirType type)
629       : BaseContextObject(std::move(contextRef)), type(type) {}
630   bool operator==(const PyType &other);
631   operator MlirType() const { return type; }
632   MlirType get() const { return type; }
633 
634   /// Gets a capsule wrapping the void* within the MlirType.
635   pybind11::object getCapsule();
636 
637   /// Creates a PyType from the MlirType wrapped by a capsule.
638   /// Note that PyType instances are uniqued, so the returned object
639   /// may be a pre-existing object. Ownership of the underlying MlirType
640   /// is taken by calling this function.
641   static PyType createFromCapsule(pybind11::object capsule);
642 
643 private:
644   MlirType type;
645 };
646 
647 /// CRTP base classes for Python types that subclass Type and should be
648 /// castable from it (i.e. via something like IntegerType(t)).
649 /// By default, type class hierarchies are one level deep (i.e. a
650 /// concrete type class extends PyType); however, intermediate python-visible
651 /// base classes can be modeled by specifying a BaseTy.
652 template <typename DerivedTy, typename BaseTy = PyType>
653 class PyConcreteType : public BaseTy {
654 public:
655   // Derived classes must define statics for:
656   //   IsAFunctionTy isaFunction
657   //   const char *pyClassName
658   using ClassTy = pybind11::class_<DerivedTy, BaseTy>;
659   using IsAFunctionTy = bool (*)(MlirType);
660 
661   PyConcreteType() = default;
662   PyConcreteType(PyMlirContextRef contextRef, MlirType t)
663       : BaseTy(std::move(contextRef), t) {}
664   PyConcreteType(PyType &orig)
665       : PyConcreteType(orig.getContext(), castFrom(orig)) {}
666 
667   static MlirType castFrom(PyType &orig) {
668     if (!DerivedTy::isaFunction(orig)) {
669       auto origRepr = pybind11::repr(pybind11::cast(orig)).cast<std::string>();
670       throw SetPyError(PyExc_ValueError, llvm::Twine("Cannot cast type to ") +
671                                              DerivedTy::pyClassName +
672                                              " (from " + origRepr + ")");
673     }
674     return orig;
675   }
676 
677   static void bind(pybind11::module &m) {
678     auto cls = ClassTy(m, DerivedTy::pyClassName, pybind11::module_local());
679     cls.def(pybind11::init<PyType &>(), pybind11::keep_alive<0, 1>());
680     cls.def_static("isinstance", [](PyType &otherType) -> bool {
681       return DerivedTy::isaFunction(otherType);
682     });
683     DerivedTy::bindDerived(cls);
684   }
685 
686   /// Implemented by derived classes to add methods to the Python subclass.
687   static void bindDerived(ClassTy &m) {}
688 };
689 
690 /// Wrapper around the generic MlirAttribute.
691 /// The lifetime of a type is bound by the PyContext that created it.
692 class PyAttribute : public BaseContextObject {
693 public:
694   PyAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
695       : BaseContextObject(std::move(contextRef)), attr(attr) {}
696   bool operator==(const PyAttribute &other);
697   operator MlirAttribute() const { return attr; }
698   MlirAttribute get() const { return attr; }
699 
700   /// Gets a capsule wrapping the void* within the MlirAttribute.
701   pybind11::object getCapsule();
702 
703   /// Creates a PyAttribute from the MlirAttribute wrapped by a capsule.
704   /// Note that PyAttribute instances are uniqued, so the returned object
705   /// may be a pre-existing object. Ownership of the underlying MlirAttribute
706   /// is taken by calling this function.
707   static PyAttribute createFromCapsule(pybind11::object capsule);
708 
709 private:
710   MlirAttribute attr;
711 };
712 
713 /// Represents a Python MlirNamedAttr, carrying an optional owned name.
714 /// TODO: Refactor this and the C-API to be based on an Identifier owned
715 /// by the context so as to avoid ownership issues here.
716 class PyNamedAttribute {
717 public:
718   /// Constructs a PyNamedAttr that retains an owned name. This should be
719   /// used in any code that originates an MlirNamedAttribute from a python
720   /// string.
721   /// The lifetime of the PyNamedAttr must extend to the lifetime of the
722   /// passed attribute.
723   PyNamedAttribute(MlirAttribute attr, std::string ownedName);
724 
725   MlirNamedAttribute namedAttr;
726 
727 private:
728   // Since the MlirNamedAttr contains an internal pointer to the actual
729   // memory of the owned string, it must be heap allocated to remain valid.
730   // Otherwise, strings that fit within the small object optimization threshold
731   // will have their memory address change as the containing object is moved,
732   // resulting in an invalid aliased pointer.
733   std::unique_ptr<std::string> ownedName;
734 };
735 
736 /// CRTP base classes for Python attributes that subclass Attribute and should
737 /// be castable from it (i.e. via something like StringAttr(attr)).
738 /// By default, attribute class hierarchies are one level deep (i.e. a
739 /// concrete attribute class extends PyAttribute); however, intermediate
740 /// python-visible base classes can be modeled by specifying a BaseTy.
741 template <typename DerivedTy, typename BaseTy = PyAttribute>
742 class PyConcreteAttribute : public BaseTy {
743 public:
744   // Derived classes must define statics for:
745   //   IsAFunctionTy isaFunction
746   //   const char *pyClassName
747   using ClassTy = pybind11::class_<DerivedTy, BaseTy>;
748   using IsAFunctionTy = bool (*)(MlirAttribute);
749 
750   PyConcreteAttribute() = default;
751   PyConcreteAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
752       : BaseTy(std::move(contextRef), attr) {}
753   PyConcreteAttribute(PyAttribute &orig)
754       : PyConcreteAttribute(orig.getContext(), castFrom(orig)) {}
755 
756   static MlirAttribute castFrom(PyAttribute &orig) {
757     if (!DerivedTy::isaFunction(orig)) {
758       auto origRepr = pybind11::repr(pybind11::cast(orig)).cast<std::string>();
759       throw SetPyError(PyExc_ValueError,
760                        llvm::Twine("Cannot cast attribute to ") +
761                            DerivedTy::pyClassName + " (from " + origRepr + ")");
762     }
763     return orig;
764   }
765 
766   static void bind(pybind11::module &m) {
767     auto cls = ClassTy(m, DerivedTy::pyClassName, pybind11::buffer_protocol(),
768                        pybind11::module_local());
769     cls.def(pybind11::init<PyAttribute &>(), pybind11::keep_alive<0, 1>());
770     cls.def_static("isinstance", [](PyAttribute &otherAttr) -> bool {
771       return DerivedTy::isaFunction(otherAttr);
772     });
773     cls.def_property_readonly("type", [](PyAttribute &attr) {
774       return PyType(attr.getContext(), mlirAttributeGetType(attr));
775     });
776     DerivedTy::bindDerived(cls);
777   }
778 
779   /// Implemented by derived classes to add methods to the Python subclass.
780   static void bindDerived(ClassTy &m) {}
781 };
782 
783 /// Wrapper around the generic MlirValue.
784 /// Values are managed completely by the operation that resulted in their
785 /// definition. For op result value, this is the operation that defines the
786 /// value. For block argument values, this is the operation that contains the
787 /// block to which the value is an argument (blocks cannot be detached in Python
788 /// bindings so such operation always exists).
789 class PyValue {
790 public:
791   PyValue(PyOperationRef parentOperation, MlirValue value)
792       : parentOperation(parentOperation), value(value) {}
793   operator MlirValue() const { return value; }
794 
795   MlirValue get() { return value; }
796   PyOperationRef &getParentOperation() { return parentOperation; }
797 
798   void checkValid() { return parentOperation->checkValid(); }
799 
800   /// Gets a capsule wrapping the void* within the MlirValue.
801   pybind11::object getCapsule();
802 
803   /// Creates a PyValue from the MlirValue wrapped by a capsule. Ownership of
804   /// the underlying MlirValue is still tied to the owning operation.
805   static PyValue createFromCapsule(pybind11::object capsule);
806 
807 private:
808   PyOperationRef parentOperation;
809   MlirValue value;
810 };
811 
812 /// Wrapper around MlirAffineExpr. Affine expressions are owned by the context.
813 class PyAffineExpr : public BaseContextObject {
814 public:
815   PyAffineExpr(PyMlirContextRef contextRef, MlirAffineExpr affineExpr)
816       : BaseContextObject(std::move(contextRef)), affineExpr(affineExpr) {}
817   bool operator==(const PyAffineExpr &other);
818   operator MlirAffineExpr() const { return affineExpr; }
819   MlirAffineExpr get() const { return affineExpr; }
820 
821   /// Gets a capsule wrapping the void* within the MlirAffineExpr.
822   pybind11::object getCapsule();
823 
824   /// Creates a PyAffineExpr from the MlirAffineExpr wrapped by a capsule.
825   /// Note that PyAffineExpr instances are uniqued, so the returned object
826   /// may be a pre-existing object. Ownership of the underlying MlirAffineExpr
827   /// is taken by calling this function.
828   static PyAffineExpr createFromCapsule(pybind11::object capsule);
829 
830   PyAffineExpr add(const PyAffineExpr &other) const;
831   PyAffineExpr mul(const PyAffineExpr &other) const;
832   PyAffineExpr floorDiv(const PyAffineExpr &other) const;
833   PyAffineExpr ceilDiv(const PyAffineExpr &other) const;
834   PyAffineExpr mod(const PyAffineExpr &other) const;
835 
836 private:
837   MlirAffineExpr affineExpr;
838 };
839 
840 class PyAffineMap : public BaseContextObject {
841 public:
842   PyAffineMap(PyMlirContextRef contextRef, MlirAffineMap affineMap)
843       : BaseContextObject(std::move(contextRef)), affineMap(affineMap) {}
844   bool operator==(const PyAffineMap &other);
845   operator MlirAffineMap() const { return affineMap; }
846   MlirAffineMap get() const { return affineMap; }
847 
848   /// Gets a capsule wrapping the void* within the MlirAffineMap.
849   pybind11::object getCapsule();
850 
851   /// Creates a PyAffineMap from the MlirAffineMap wrapped by a capsule.
852   /// Note that PyAffineMap instances are uniqued, so the returned object
853   /// may be a pre-existing object. Ownership of the underlying MlirAffineMap
854   /// is taken by calling this function.
855   static PyAffineMap createFromCapsule(pybind11::object capsule);
856 
857 private:
858   MlirAffineMap affineMap;
859 };
860 
861 class PyIntegerSet : public BaseContextObject {
862 public:
863   PyIntegerSet(PyMlirContextRef contextRef, MlirIntegerSet integerSet)
864       : BaseContextObject(std::move(contextRef)), integerSet(integerSet) {}
865   bool operator==(const PyIntegerSet &other);
866   operator MlirIntegerSet() const { return integerSet; }
867   MlirIntegerSet get() const { return integerSet; }
868 
869   /// Gets a capsule wrapping the void* within the MlirIntegerSet.
870   pybind11::object getCapsule();
871 
872   /// Creates a PyIntegerSet from the MlirAffineMap wrapped by a capsule.
873   /// Note that PyIntegerSet instances may be uniqued, so the returned object
874   /// may be a pre-existing object. Integer sets are owned by the context.
875   static PyIntegerSet createFromCapsule(pybind11::object capsule);
876 
877 private:
878   MlirIntegerSet integerSet;
879 };
880 
881 /// Bindings for MLIR symbol tables.
882 class PySymbolTable {
883 public:
884   /// Constructs a symbol table for the given operation.
885   explicit PySymbolTable(PyOperationBase &operation);
886 
887   /// Destroys the symbol table.
888   ~PySymbolTable() { mlirSymbolTableDestroy(symbolTable); }
889 
890   /// Returns the symbol (opview) with the given name, throws if there is no
891   /// such symbol in the table.
892   pybind11::object dunderGetItem(const std::string &name);
893 
894   /// Removes the given operation from the symbol table and erases it.
895   void erase(PyOperationBase &symbol);
896 
897   /// Removes the operation with the given name from the symbol table and erases
898   /// it, throws if there is no such symbol in the table.
899   void dunderDel(const std::string &name);
900 
901   /// Inserts the given operation into the symbol table. The operation must have
902   /// the symbol trait.
903   PyAttribute insert(PyOperationBase &symbol);
904 
905   /// Casts the bindings class into the C API structure.
906   operator MlirSymbolTable() { return symbolTable; }
907 
908 private:
909   PyOperationRef operation;
910   MlirSymbolTable symbolTable;
911 };
912 
913 void populateIRAffine(pybind11::module &m);
914 void populateIRAttributes(pybind11::module &m);
915 void populateIRCore(pybind11::module &m);
916 void populateIRInterfaces(pybind11::module &m);
917 void populateIRTypes(pybind11::module &m);
918 
919 } // namespace python
920 } // namespace mlir
921 
922 namespace pybind11 {
923 namespace detail {
924 
925 template <>
926 struct type_caster<mlir::python::DefaultingPyMlirContext>
927     : MlirDefaultingCaster<mlir::python::DefaultingPyMlirContext> {};
928 template <>
929 struct type_caster<mlir::python::DefaultingPyLocation>
930     : MlirDefaultingCaster<mlir::python::DefaultingPyLocation> {};
931 
932 } // namespace detail
933 } // namespace pybind11
934 
935 #endif // MLIR_BINDINGS_PYTHON_IRMODULES_H
936