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              bool assumeVerified);
399   pybind11::object getAsm(bool binary,
400                           llvm::Optional<int64_t> largeElementsLimit,
401                           bool enableDebugInfo, bool prettyDebugInfo,
402                           bool printGenericOpForm, bool useLocalScope,
403                           bool assumeVerified);
404 
405   /// Moves the operation before or after the other operation.
406   void moveAfter(PyOperationBase &other);
407   void moveBefore(PyOperationBase &other);
408 
409   /// Each must provide access to the raw Operation.
410   virtual PyOperation &getOperation() = 0;
411 };
412 
413 /// Wrapper around PyOperation.
414 /// Operations exist in either an attached (dependent) or detached (top-level)
415 /// state. In the detached state (as on creation), an operation is owned by
416 /// the creator and its lifetime extends either until its reference count
417 /// drops to zero or it is attached to a parent, at which point its lifetime
418 /// is bounded by its top-level parent reference.
419 class PyOperation;
420 using PyOperationRef = PyObjectRef<PyOperation>;
421 class PyOperation : public PyOperationBase, public BaseContextObject {
422 public:
423   ~PyOperation();
424   PyOperation &getOperation() override { return *this; }
425 
426   /// Returns a PyOperation for the given MlirOperation, optionally associating
427   /// it with a parentKeepAlive.
428   static PyOperationRef
429   forOperation(PyMlirContextRef contextRef, MlirOperation operation,
430                pybind11::object parentKeepAlive = pybind11::object());
431 
432   /// Creates a detached operation. The operation must not be associated with
433   /// any existing live operation.
434   static PyOperationRef
435   createDetached(PyMlirContextRef contextRef, MlirOperation operation,
436                  pybind11::object parentKeepAlive = pybind11::object());
437 
438   /// Detaches the operation from its parent block and updates its state
439   /// accordingly.
440   void detachFromParent() {
441     mlirOperationRemoveFromParent(getOperation());
442     setDetached();
443     parentKeepAlive = pybind11::object();
444   }
445 
446   /// Gets the backing operation.
447   operator MlirOperation() const { return get(); }
448   MlirOperation get() const {
449     checkValid();
450     return operation;
451   }
452 
453   PyOperationRef getRef() {
454     return PyOperationRef(
455         this, pybind11::reinterpret_borrow<pybind11::object>(handle));
456   }
457 
458   bool isAttached() { return attached; }
459   void setAttached(pybind11::object parent = pybind11::object()) {
460     assert(!attached && "operation already attached");
461     attached = true;
462   }
463   void setDetached() {
464     assert(attached && "operation already detached");
465     attached = false;
466   }
467   void checkValid() const;
468 
469   /// Gets the owning block or raises an exception if the operation has no
470   /// owning block.
471   PyBlock getBlock();
472 
473   /// Gets the parent operation or raises an exception if the operation has
474   /// no parent.
475   llvm::Optional<PyOperationRef> getParentOperation();
476 
477   /// Gets a capsule wrapping the void* within the MlirOperation.
478   pybind11::object getCapsule();
479 
480   /// Creates a PyOperation from the MlirOperation wrapped by a capsule.
481   /// Ownership of the underlying MlirOperation is taken by calling this
482   /// function.
483   static pybind11::object createFromCapsule(pybind11::object capsule);
484 
485   /// Creates an operation. See corresponding python docstring.
486   static pybind11::object
487   create(std::string name, llvm::Optional<std::vector<PyType *>> results,
488          llvm::Optional<std::vector<PyValue *>> operands,
489          llvm::Optional<pybind11::dict> attributes,
490          llvm::Optional<std::vector<PyBlock *>> successors, int regions,
491          DefaultingPyLocation location, pybind11::object ip);
492 
493   /// Creates an OpView suitable for this operation.
494   pybind11::object createOpView();
495 
496   /// Erases the underlying MlirOperation, removes its pointer from the
497   /// parent context's live operations map, and sets the valid bit false.
498   void erase();
499 
500 private:
501   PyOperation(PyMlirContextRef contextRef, MlirOperation operation);
502   static PyOperationRef createInstance(PyMlirContextRef contextRef,
503                                        MlirOperation operation,
504                                        pybind11::object parentKeepAlive);
505 
506   MlirOperation operation;
507   pybind11::handle handle;
508   // Keeps the parent alive, regardless of whether it is an Operation or
509   // Module.
510   // TODO: As implemented, this facility is only sufficient for modeling the
511   // trivial module parent back-reference. Generalize this to also account for
512   // transitions from detached to attached and address TODOs in the
513   // ir_operation.py regarding testing corresponding lifetime guarantees.
514   pybind11::object parentKeepAlive;
515   bool attached = true;
516   bool valid = true;
517 
518   friend class PyOperationBase;
519   friend class PySymbolTable;
520 };
521 
522 /// A PyOpView is equivalent to the C++ "Op" wrappers: these are the basis for
523 /// providing more instance-specific accessors and serve as the base class for
524 /// custom ODS-style operation classes. Since this class is subclass on the
525 /// python side, it must present an __init__ method that operates in pure
526 /// python types.
527 class PyOpView : public PyOperationBase {
528 public:
529   PyOpView(pybind11::object operationObject);
530   PyOperation &getOperation() override { return operation; }
531 
532   static pybind11::object createRawSubclass(pybind11::object userClass);
533 
534   pybind11::object getOperationObject() { return operationObject; }
535 
536   static pybind11::object
537   buildGeneric(pybind11::object cls, pybind11::list resultTypeList,
538                pybind11::list operandList,
539                llvm::Optional<pybind11::dict> attributes,
540                llvm::Optional<std::vector<PyBlock *>> successors,
541                llvm::Optional<int> regions, DefaultingPyLocation location,
542                pybind11::object maybeIp);
543 
544 private:
545   PyOperation &operation;           // For efficient, cast-free access from C++
546   pybind11::object operationObject; // Holds the reference.
547 };
548 
549 /// Wrapper around an MlirRegion.
550 /// Regions are managed completely by their containing operation. Unlike the
551 /// C++ API, the python API does not support detached regions.
552 class PyRegion {
553 public:
554   PyRegion(PyOperationRef parentOperation, MlirRegion region)
555       : parentOperation(std::move(parentOperation)), region(region) {
556     assert(!mlirRegionIsNull(region) && "python region cannot be null");
557   }
558   operator MlirRegion() const { return region; }
559 
560   MlirRegion get() { return region; }
561   PyOperationRef &getParentOperation() { return parentOperation; }
562 
563   void checkValid() { return parentOperation->checkValid(); }
564 
565 private:
566   PyOperationRef parentOperation;
567   MlirRegion region;
568 };
569 
570 /// Wrapper around an MlirBlock.
571 /// Blocks are managed completely by their containing operation. Unlike the
572 /// C++ API, the python API does not support detached blocks.
573 class PyBlock {
574 public:
575   PyBlock(PyOperationRef parentOperation, MlirBlock block)
576       : parentOperation(std::move(parentOperation)), block(block) {
577     assert(!mlirBlockIsNull(block) && "python block cannot be null");
578   }
579 
580   MlirBlock get() { return block; }
581   PyOperationRef &getParentOperation() { return parentOperation; }
582 
583   void checkValid() { return parentOperation->checkValid(); }
584 
585 private:
586   PyOperationRef parentOperation;
587   MlirBlock block;
588 };
589 
590 /// An insertion point maintains a pointer to a Block and a reference operation.
591 /// Calls to insert() will insert a new operation before the
592 /// reference operation. If the reference operation is null, then appends to
593 /// the end of the block.
594 class PyInsertionPoint {
595 public:
596   /// Creates an insertion point positioned after the last operation in the
597   /// block, but still inside the block.
598   PyInsertionPoint(PyBlock &block);
599   /// Creates an insertion point positioned before a reference operation.
600   PyInsertionPoint(PyOperationBase &beforeOperationBase);
601 
602   /// Shortcut to create an insertion point at the beginning of the block.
603   static PyInsertionPoint atBlockBegin(PyBlock &block);
604   /// Shortcut to create an insertion point before the block terminator.
605   static PyInsertionPoint atBlockTerminator(PyBlock &block);
606 
607   /// Inserts an operation.
608   void insert(PyOperationBase &operationBase);
609 
610   /// Enter and exit the context manager.
611   pybind11::object contextEnter();
612   void contextExit(pybind11::object excType, pybind11::object excVal,
613                    pybind11::object excTb);
614 
615   PyBlock &getBlock() { return block; }
616 
617 private:
618   // Trampoline constructor that avoids null initializing members while
619   // looking up parents.
620   PyInsertionPoint(PyBlock block, llvm::Optional<PyOperationRef> refOperation)
621       : refOperation(std::move(refOperation)), block(std::move(block)) {}
622 
623   llvm::Optional<PyOperationRef> refOperation;
624   PyBlock block;
625 };
626 /// Wrapper around the generic MlirType.
627 /// The lifetime of a type is bound by the PyContext that created it.
628 class PyType : public BaseContextObject {
629 public:
630   PyType(PyMlirContextRef contextRef, MlirType type)
631       : BaseContextObject(std::move(contextRef)), type(type) {}
632   bool operator==(const PyType &other);
633   operator MlirType() const { return type; }
634   MlirType get() const { return type; }
635 
636   /// Gets a capsule wrapping the void* within the MlirType.
637   pybind11::object getCapsule();
638 
639   /// Creates a PyType from the MlirType wrapped by a capsule.
640   /// Note that PyType instances are uniqued, so the returned object
641   /// may be a pre-existing object. Ownership of the underlying MlirType
642   /// is taken by calling this function.
643   static PyType createFromCapsule(pybind11::object capsule);
644 
645 private:
646   MlirType type;
647 };
648 
649 /// CRTP base classes for Python types that subclass Type and should be
650 /// castable from it (i.e. via something like IntegerType(t)).
651 /// By default, type class hierarchies are one level deep (i.e. a
652 /// concrete type class extends PyType); however, intermediate python-visible
653 /// base classes can be modeled by specifying a BaseTy.
654 template <typename DerivedTy, typename BaseTy = PyType>
655 class PyConcreteType : public BaseTy {
656 public:
657   // Derived classes must define statics for:
658   //   IsAFunctionTy isaFunction
659   //   const char *pyClassName
660   using ClassTy = pybind11::class_<DerivedTy, BaseTy>;
661   using IsAFunctionTy = bool (*)(MlirType);
662 
663   PyConcreteType() = default;
664   PyConcreteType(PyMlirContextRef contextRef, MlirType t)
665       : BaseTy(std::move(contextRef), t) {}
666   PyConcreteType(PyType &orig)
667       : PyConcreteType(orig.getContext(), castFrom(orig)) {}
668 
669   static MlirType castFrom(PyType &orig) {
670     if (!DerivedTy::isaFunction(orig)) {
671       auto origRepr = pybind11::repr(pybind11::cast(orig)).cast<std::string>();
672       throw SetPyError(PyExc_ValueError, llvm::Twine("Cannot cast type to ") +
673                                              DerivedTy::pyClassName +
674                                              " (from " + origRepr + ")");
675     }
676     return orig;
677   }
678 
679   static void bind(pybind11::module &m) {
680     auto cls = ClassTy(m, DerivedTy::pyClassName, pybind11::module_local());
681     cls.def(pybind11::init<PyType &>(), pybind11::keep_alive<0, 1>());
682     cls.def_static("isinstance", [](PyType &otherType) -> bool {
683       return DerivedTy::isaFunction(otherType);
684     });
685     DerivedTy::bindDerived(cls);
686   }
687 
688   /// Implemented by derived classes to add methods to the Python subclass.
689   static void bindDerived(ClassTy &m) {}
690 };
691 
692 /// Wrapper around the generic MlirAttribute.
693 /// The lifetime of a type is bound by the PyContext that created it.
694 class PyAttribute : public BaseContextObject {
695 public:
696   PyAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
697       : BaseContextObject(std::move(contextRef)), attr(attr) {}
698   bool operator==(const PyAttribute &other);
699   operator MlirAttribute() const { return attr; }
700   MlirAttribute get() const { return attr; }
701 
702   /// Gets a capsule wrapping the void* within the MlirAttribute.
703   pybind11::object getCapsule();
704 
705   /// Creates a PyAttribute from the MlirAttribute wrapped by a capsule.
706   /// Note that PyAttribute instances are uniqued, so the returned object
707   /// may be a pre-existing object. Ownership of the underlying MlirAttribute
708   /// is taken by calling this function.
709   static PyAttribute createFromCapsule(pybind11::object capsule);
710 
711 private:
712   MlirAttribute attr;
713 };
714 
715 /// Represents a Python MlirNamedAttr, carrying an optional owned name.
716 /// TODO: Refactor this and the C-API to be based on an Identifier owned
717 /// by the context so as to avoid ownership issues here.
718 class PyNamedAttribute {
719 public:
720   /// Constructs a PyNamedAttr that retains an owned name. This should be
721   /// used in any code that originates an MlirNamedAttribute from a python
722   /// string.
723   /// The lifetime of the PyNamedAttr must extend to the lifetime of the
724   /// passed attribute.
725   PyNamedAttribute(MlirAttribute attr, std::string ownedName);
726 
727   MlirNamedAttribute namedAttr;
728 
729 private:
730   // Since the MlirNamedAttr contains an internal pointer to the actual
731   // memory of the owned string, it must be heap allocated to remain valid.
732   // Otherwise, strings that fit within the small object optimization threshold
733   // will have their memory address change as the containing object is moved,
734   // resulting in an invalid aliased pointer.
735   std::unique_ptr<std::string> ownedName;
736 };
737 
738 /// CRTP base classes for Python attributes that subclass Attribute and should
739 /// be castable from it (i.e. via something like StringAttr(attr)).
740 /// By default, attribute class hierarchies are one level deep (i.e. a
741 /// concrete attribute class extends PyAttribute); however, intermediate
742 /// python-visible base classes can be modeled by specifying a BaseTy.
743 template <typename DerivedTy, typename BaseTy = PyAttribute>
744 class PyConcreteAttribute : public BaseTy {
745 public:
746   // Derived classes must define statics for:
747   //   IsAFunctionTy isaFunction
748   //   const char *pyClassName
749   using ClassTy = pybind11::class_<DerivedTy, BaseTy>;
750   using IsAFunctionTy = bool (*)(MlirAttribute);
751 
752   PyConcreteAttribute() = default;
753   PyConcreteAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
754       : BaseTy(std::move(contextRef), attr) {}
755   PyConcreteAttribute(PyAttribute &orig)
756       : PyConcreteAttribute(orig.getContext(), castFrom(orig)) {}
757 
758   static MlirAttribute castFrom(PyAttribute &orig) {
759     if (!DerivedTy::isaFunction(orig)) {
760       auto origRepr = pybind11::repr(pybind11::cast(orig)).cast<std::string>();
761       throw SetPyError(PyExc_ValueError,
762                        llvm::Twine("Cannot cast attribute to ") +
763                            DerivedTy::pyClassName + " (from " + origRepr + ")");
764     }
765     return orig;
766   }
767 
768   static void bind(pybind11::module &m) {
769     auto cls = ClassTy(m, DerivedTy::pyClassName, pybind11::buffer_protocol(),
770                        pybind11::module_local());
771     cls.def(pybind11::init<PyAttribute &>(), pybind11::keep_alive<0, 1>());
772     cls.def_static("isinstance", [](PyAttribute &otherAttr) -> bool {
773       return DerivedTy::isaFunction(otherAttr);
774     });
775     cls.def_property_readonly("type", [](PyAttribute &attr) {
776       return PyType(attr.getContext(), mlirAttributeGetType(attr));
777     });
778     DerivedTy::bindDerived(cls);
779   }
780 
781   /// Implemented by derived classes to add methods to the Python subclass.
782   static void bindDerived(ClassTy &m) {}
783 };
784 
785 /// Wrapper around the generic MlirValue.
786 /// Values are managed completely by the operation that resulted in their
787 /// definition. For op result value, this is the operation that defines the
788 /// value. For block argument values, this is the operation that contains the
789 /// block to which the value is an argument (blocks cannot be detached in Python
790 /// bindings so such operation always exists).
791 class PyValue {
792 public:
793   PyValue(PyOperationRef parentOperation, MlirValue value)
794       : parentOperation(parentOperation), value(value) {}
795   operator MlirValue() const { return value; }
796 
797   MlirValue get() { return value; }
798   PyOperationRef &getParentOperation() { return parentOperation; }
799 
800   void checkValid() { return parentOperation->checkValid(); }
801 
802   /// Gets a capsule wrapping the void* within the MlirValue.
803   pybind11::object getCapsule();
804 
805   /// Creates a PyValue from the MlirValue wrapped by a capsule. Ownership of
806   /// the underlying MlirValue is still tied to the owning operation.
807   static PyValue createFromCapsule(pybind11::object capsule);
808 
809 private:
810   PyOperationRef parentOperation;
811   MlirValue value;
812 };
813 
814 /// Wrapper around MlirAffineExpr. Affine expressions are owned by the context.
815 class PyAffineExpr : public BaseContextObject {
816 public:
817   PyAffineExpr(PyMlirContextRef contextRef, MlirAffineExpr affineExpr)
818       : BaseContextObject(std::move(contextRef)), affineExpr(affineExpr) {}
819   bool operator==(const PyAffineExpr &other);
820   operator MlirAffineExpr() const { return affineExpr; }
821   MlirAffineExpr get() const { return affineExpr; }
822 
823   /// Gets a capsule wrapping the void* within the MlirAffineExpr.
824   pybind11::object getCapsule();
825 
826   /// Creates a PyAffineExpr from the MlirAffineExpr wrapped by a capsule.
827   /// Note that PyAffineExpr instances are uniqued, so the returned object
828   /// may be a pre-existing object. Ownership of the underlying MlirAffineExpr
829   /// is taken by calling this function.
830   static PyAffineExpr createFromCapsule(pybind11::object capsule);
831 
832   PyAffineExpr add(const PyAffineExpr &other) const;
833   PyAffineExpr mul(const PyAffineExpr &other) const;
834   PyAffineExpr floorDiv(const PyAffineExpr &other) const;
835   PyAffineExpr ceilDiv(const PyAffineExpr &other) const;
836   PyAffineExpr mod(const PyAffineExpr &other) const;
837 
838 private:
839   MlirAffineExpr affineExpr;
840 };
841 
842 class PyAffineMap : public BaseContextObject {
843 public:
844   PyAffineMap(PyMlirContextRef contextRef, MlirAffineMap affineMap)
845       : BaseContextObject(std::move(contextRef)), affineMap(affineMap) {}
846   bool operator==(const PyAffineMap &other);
847   operator MlirAffineMap() const { return affineMap; }
848   MlirAffineMap get() const { return affineMap; }
849 
850   /// Gets a capsule wrapping the void* within the MlirAffineMap.
851   pybind11::object getCapsule();
852 
853   /// Creates a PyAffineMap from the MlirAffineMap wrapped by a capsule.
854   /// Note that PyAffineMap instances are uniqued, so the returned object
855   /// may be a pre-existing object. Ownership of the underlying MlirAffineMap
856   /// is taken by calling this function.
857   static PyAffineMap createFromCapsule(pybind11::object capsule);
858 
859 private:
860   MlirAffineMap affineMap;
861 };
862 
863 class PyIntegerSet : public BaseContextObject {
864 public:
865   PyIntegerSet(PyMlirContextRef contextRef, MlirIntegerSet integerSet)
866       : BaseContextObject(std::move(contextRef)), integerSet(integerSet) {}
867   bool operator==(const PyIntegerSet &other);
868   operator MlirIntegerSet() const { return integerSet; }
869   MlirIntegerSet get() const { return integerSet; }
870 
871   /// Gets a capsule wrapping the void* within the MlirIntegerSet.
872   pybind11::object getCapsule();
873 
874   /// Creates a PyIntegerSet from the MlirAffineMap wrapped by a capsule.
875   /// Note that PyIntegerSet instances may be uniqued, so the returned object
876   /// may be a pre-existing object. Integer sets are owned by the context.
877   static PyIntegerSet createFromCapsule(pybind11::object capsule);
878 
879 private:
880   MlirIntegerSet integerSet;
881 };
882 
883 /// Bindings for MLIR symbol tables.
884 class PySymbolTable {
885 public:
886   /// Constructs a symbol table for the given operation.
887   explicit PySymbolTable(PyOperationBase &operation);
888 
889   /// Destroys the symbol table.
890   ~PySymbolTable() { mlirSymbolTableDestroy(symbolTable); }
891 
892   /// Returns the symbol (opview) with the given name, throws if there is no
893   /// such symbol in the table.
894   pybind11::object dunderGetItem(const std::string &name);
895 
896   /// Removes the given operation from the symbol table and erases it.
897   void erase(PyOperationBase &symbol);
898 
899   /// Removes the operation with the given name from the symbol table and erases
900   /// it, throws if there is no such symbol in the table.
901   void dunderDel(const std::string &name);
902 
903   /// Inserts the given operation into the symbol table. The operation must have
904   /// the symbol trait.
905   PyAttribute insert(PyOperationBase &symbol);
906 
907   /// Casts the bindings class into the C API structure.
908   operator MlirSymbolTable() { return symbolTable; }
909 
910 private:
911   PyOperationRef operation;
912   MlirSymbolTable symbolTable;
913 };
914 
915 void populateIRAffine(pybind11::module &m);
916 void populateIRAttributes(pybind11::module &m);
917 void populateIRCore(pybind11::module &m);
918 void populateIRInterfaces(pybind11::module &m);
919 void populateIRTypes(pybind11::module &m);
920 
921 } // namespace python
922 } // namespace mlir
923 
924 namespace pybind11 {
925 namespace detail {
926 
927 template <>
928 struct type_caster<mlir::python::DefaultingPyMlirContext>
929     : MlirDefaultingCaster<mlir::python::DefaultingPyMlirContext> {};
930 template <>
931 struct type_caster<mlir::python::DefaultingPyLocation>
932     : MlirDefaultingCaster<mlir::python::DefaultingPyLocation> {};
933 
934 } // namespace detail
935 } // namespace pybind11
936 
937 #endif // MLIR_BINDINGS_PYTHON_IRMODULES_H
938