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