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 537 MlirRegion get() { return region; } 538 PyOperationRef &getParentOperation() { return parentOperation; } 539 540 void checkValid() { return parentOperation->checkValid(); } 541 542 private: 543 PyOperationRef parentOperation; 544 MlirRegion region; 545 }; 546 547 /// Wrapper around an MlirBlock. 548 /// Blocks are managed completely by their containing operation. Unlike the 549 /// C++ API, the python API does not support detached blocks. 550 class PyBlock { 551 public: 552 PyBlock(PyOperationRef parentOperation, MlirBlock block) 553 : parentOperation(std::move(parentOperation)), block(block) { 554 assert(!mlirBlockIsNull(block) && "python block cannot be null"); 555 } 556 557 MlirBlock get() { return block; } 558 PyOperationRef &getParentOperation() { return parentOperation; } 559 560 void checkValid() { return parentOperation->checkValid(); } 561 562 private: 563 PyOperationRef parentOperation; 564 MlirBlock block; 565 }; 566 567 /// An insertion point maintains a pointer to a Block and a reference operation. 568 /// Calls to insert() will insert a new operation before the 569 /// reference operation. If the reference operation is null, then appends to 570 /// the end of the block. 571 class PyInsertionPoint { 572 public: 573 /// Creates an insertion point positioned after the last operation in the 574 /// block, but still inside the block. 575 PyInsertionPoint(PyBlock &block); 576 /// Creates an insertion point positioned before a reference operation. 577 PyInsertionPoint(PyOperationBase &beforeOperationBase); 578 579 /// Shortcut to create an insertion point at the beginning of the block. 580 static PyInsertionPoint atBlockBegin(PyBlock &block); 581 /// Shortcut to create an insertion point before the block terminator. 582 static PyInsertionPoint atBlockTerminator(PyBlock &block); 583 584 /// Inserts an operation. 585 void insert(PyOperationBase &operationBase); 586 587 /// Enter and exit the context manager. 588 pybind11::object contextEnter(); 589 void contextExit(pybind11::object excType, pybind11::object excVal, 590 pybind11::object excTb); 591 592 PyBlock &getBlock() { return block; } 593 594 private: 595 // Trampoline constructor that avoids null initializing members while 596 // looking up parents. 597 PyInsertionPoint(PyBlock block, llvm::Optional<PyOperationRef> refOperation) 598 : refOperation(std::move(refOperation)), block(std::move(block)) {} 599 600 llvm::Optional<PyOperationRef> refOperation; 601 PyBlock block; 602 }; 603 604 /// Wrapper around the generic MlirAttribute. 605 /// The lifetime of a type is bound by the PyContext that created it. 606 class PyAttribute : public BaseContextObject { 607 public: 608 PyAttribute(PyMlirContextRef contextRef, MlirAttribute attr) 609 : BaseContextObject(std::move(contextRef)), attr(attr) {} 610 bool operator==(const PyAttribute &other); 611 operator MlirAttribute() const { return attr; } 612 MlirAttribute get() const { return attr; } 613 614 /// Gets a capsule wrapping the void* within the MlirAttribute. 615 pybind11::object getCapsule(); 616 617 /// Creates a PyAttribute from the MlirAttribute wrapped by a capsule. 618 /// Note that PyAttribute instances are uniqued, so the returned object 619 /// may be a pre-existing object. Ownership of the underlying MlirAttribute 620 /// is taken by calling this function. 621 static PyAttribute createFromCapsule(pybind11::object capsule); 622 623 private: 624 MlirAttribute attr; 625 }; 626 627 /// Represents a Python MlirNamedAttr, carrying an optional owned name. 628 /// TODO: Refactor this and the C-API to be based on an Identifier owned 629 /// by the context so as to avoid ownership issues here. 630 class PyNamedAttribute { 631 public: 632 /// Constructs a PyNamedAttr that retains an owned name. This should be 633 /// used in any code that originates an MlirNamedAttribute from a python 634 /// string. 635 /// The lifetime of the PyNamedAttr must extend to the lifetime of the 636 /// passed attribute. 637 PyNamedAttribute(MlirAttribute attr, std::string ownedName); 638 639 MlirNamedAttribute namedAttr; 640 641 private: 642 // Since the MlirNamedAttr contains an internal pointer to the actual 643 // memory of the owned string, it must be heap allocated to remain valid. 644 // Otherwise, strings that fit within the small object optimization threshold 645 // will have their memory address change as the containing object is moved, 646 // resulting in an invalid aliased pointer. 647 std::unique_ptr<std::string> ownedName; 648 }; 649 650 /// CRTP base classes for Python attributes that subclass Attribute and should 651 /// be castable from it (i.e. via something like StringAttr(attr)). 652 /// By default, attribute class hierarchies are one level deep (i.e. a 653 /// concrete attribute class extends PyAttribute); however, intermediate 654 /// python-visible base classes can be modeled by specifying a BaseTy. 655 template <typename DerivedTy, typename BaseTy = PyAttribute> 656 class PyConcreteAttribute : public BaseTy { 657 public: 658 // Derived classes must define statics for: 659 // IsAFunctionTy isaFunction 660 // const char *pyClassName 661 using ClassTy = pybind11::class_<DerivedTy, BaseTy>; 662 using IsAFunctionTy = bool (*)(MlirAttribute); 663 664 PyConcreteAttribute() = default; 665 PyConcreteAttribute(PyMlirContextRef contextRef, MlirAttribute attr) 666 : BaseTy(std::move(contextRef), attr) {} 667 PyConcreteAttribute(PyAttribute &orig) 668 : PyConcreteAttribute(orig.getContext(), castFrom(orig)) {} 669 670 static MlirAttribute castFrom(PyAttribute &orig) { 671 if (!DerivedTy::isaFunction(orig)) { 672 auto origRepr = pybind11::repr(pybind11::cast(orig)).cast<std::string>(); 673 throw SetPyError(PyExc_ValueError, 674 llvm::Twine("Cannot cast attribute to ") + 675 DerivedTy::pyClassName + " (from " + origRepr + ")"); 676 } 677 return orig; 678 } 679 680 static void bind(pybind11::module &m) { 681 auto cls = ClassTy(m, DerivedTy::pyClassName, pybind11::buffer_protocol()); 682 cls.def(pybind11::init<PyAttribute &>(), pybind11::keep_alive<0, 1>()); 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 MlirType. 691 /// The lifetime of a type is bound by the PyContext that created it. 692 class PyType : public BaseContextObject { 693 public: 694 PyType(PyMlirContextRef contextRef, MlirType type) 695 : BaseContextObject(std::move(contextRef)), type(type) {} 696 bool operator==(const PyType &other); 697 operator MlirType() const { return type; } 698 MlirType get() const { return type; } 699 700 /// Gets a capsule wrapping the void* within the MlirType. 701 pybind11::object getCapsule(); 702 703 /// Creates a PyType from the MlirType wrapped by a capsule. 704 /// Note that PyType instances are uniqued, so the returned object 705 /// may be a pre-existing object. Ownership of the underlying MlirType 706 /// is taken by calling this function. 707 static PyType createFromCapsule(pybind11::object capsule); 708 709 private: 710 MlirType type; 711 }; 712 713 /// CRTP base classes for Python types that subclass Type and should be 714 /// castable from it (i.e. via something like IntegerType(t)). 715 /// By default, type class hierarchies are one level deep (i.e. a 716 /// concrete type class extends PyType); however, intermediate python-visible 717 /// base classes can be modeled by specifying a BaseTy. 718 template <typename DerivedTy, typename BaseTy = PyType> 719 class PyConcreteType : public BaseTy { 720 public: 721 // Derived classes must define statics for: 722 // IsAFunctionTy isaFunction 723 // const char *pyClassName 724 using ClassTy = pybind11::class_<DerivedTy, BaseTy>; 725 using IsAFunctionTy = bool (*)(MlirType); 726 727 PyConcreteType() = default; 728 PyConcreteType(PyMlirContextRef contextRef, MlirType t) 729 : BaseTy(std::move(contextRef), t) {} 730 PyConcreteType(PyType &orig) 731 : PyConcreteType(orig.getContext(), castFrom(orig)) {} 732 733 static MlirType castFrom(PyType &orig) { 734 if (!DerivedTy::isaFunction(orig)) { 735 auto origRepr = pybind11::repr(pybind11::cast(orig)).cast<std::string>(); 736 throw SetPyError(PyExc_ValueError, llvm::Twine("Cannot cast type to ") + 737 DerivedTy::pyClassName + 738 " (from " + origRepr + ")"); 739 } 740 return orig; 741 } 742 743 static void bind(pybind11::module &m) { 744 auto cls = ClassTy(m, DerivedTy::pyClassName); 745 cls.def(pybind11::init<PyType &>(), pybind11::keep_alive<0, 1>()); 746 cls.def_static("isinstance", [](PyType &otherType) -> bool { 747 return DerivedTy::isaFunction(otherType); 748 }); 749 DerivedTy::bindDerived(cls); 750 } 751 752 /// Implemented by derived classes to add methods to the Python subclass. 753 static void bindDerived(ClassTy &m) {} 754 }; 755 756 /// Wrapper around the generic MlirValue. 757 /// Values are managed completely by the operation that resulted in their 758 /// definition. For op result value, this is the operation that defines the 759 /// value. For block argument values, this is the operation that contains the 760 /// block to which the value is an argument (blocks cannot be detached in Python 761 /// bindings so such operation always exists). 762 class PyValue { 763 public: 764 PyValue(PyOperationRef parentOperation, MlirValue value) 765 : parentOperation(parentOperation), value(value) {} 766 767 MlirValue get() { return value; } 768 PyOperationRef &getParentOperation() { return parentOperation; } 769 770 void checkValid() { return parentOperation->checkValid(); } 771 772 /// Gets a capsule wrapping the void* within the MlirValue. 773 pybind11::object getCapsule(); 774 775 /// Creates a PyValue from the MlirValue wrapped by a capsule. Ownership of 776 /// the underlying MlirValue is still tied to the owning operation. 777 static PyValue createFromCapsule(pybind11::object capsule); 778 779 private: 780 PyOperationRef parentOperation; 781 MlirValue value; 782 }; 783 784 /// Wrapper around MlirAffineExpr. Affine expressions are owned by the context. 785 class PyAffineExpr : public BaseContextObject { 786 public: 787 PyAffineExpr(PyMlirContextRef contextRef, MlirAffineExpr affineExpr) 788 : BaseContextObject(std::move(contextRef)), affineExpr(affineExpr) {} 789 bool operator==(const PyAffineExpr &other); 790 operator MlirAffineExpr() const { return affineExpr; } 791 MlirAffineExpr get() const { return affineExpr; } 792 793 /// Gets a capsule wrapping the void* within the MlirAffineExpr. 794 pybind11::object getCapsule(); 795 796 /// Creates a PyAffineExpr from the MlirAffineExpr wrapped by a capsule. 797 /// Note that PyAffineExpr instances are uniqued, so the returned object 798 /// may be a pre-existing object. Ownership of the underlying MlirAffineExpr 799 /// is taken by calling this function. 800 static PyAffineExpr createFromCapsule(pybind11::object capsule); 801 802 PyAffineExpr add(const PyAffineExpr &other) const; 803 PyAffineExpr mul(const PyAffineExpr &other) const; 804 PyAffineExpr floorDiv(const PyAffineExpr &other) const; 805 PyAffineExpr ceilDiv(const PyAffineExpr &other) const; 806 PyAffineExpr mod(const PyAffineExpr &other) const; 807 808 private: 809 MlirAffineExpr affineExpr; 810 }; 811 812 class PyAffineMap : public BaseContextObject { 813 public: 814 PyAffineMap(PyMlirContextRef contextRef, MlirAffineMap affineMap) 815 : BaseContextObject(std::move(contextRef)), affineMap(affineMap) {} 816 bool operator==(const PyAffineMap &other); 817 operator MlirAffineMap() const { return affineMap; } 818 MlirAffineMap get() const { return affineMap; } 819 820 /// Gets a capsule wrapping the void* within the MlirAffineMap. 821 pybind11::object getCapsule(); 822 823 /// Creates a PyAffineMap from the MlirAffineMap wrapped by a capsule. 824 /// Note that PyAffineMap instances are uniqued, so the returned object 825 /// may be a pre-existing object. Ownership of the underlying MlirAffineMap 826 /// is taken by calling this function. 827 static PyAffineMap createFromCapsule(pybind11::object capsule); 828 829 private: 830 MlirAffineMap affineMap; 831 }; 832 833 class PyIntegerSet : public BaseContextObject { 834 public: 835 PyIntegerSet(PyMlirContextRef contextRef, MlirIntegerSet integerSet) 836 : BaseContextObject(std::move(contextRef)), integerSet(integerSet) {} 837 bool operator==(const PyIntegerSet &other); 838 operator MlirIntegerSet() const { return integerSet; } 839 MlirIntegerSet get() const { return integerSet; } 840 841 /// Gets a capsule wrapping the void* within the MlirIntegerSet. 842 pybind11::object getCapsule(); 843 844 /// Creates a PyIntegerSet from the MlirAffineMap wrapped by a capsule. 845 /// Note that PyIntegerSet instances may be uniqued, so the returned object 846 /// may be a pre-existing object. Integer sets are owned by the context. 847 static PyIntegerSet createFromCapsule(pybind11::object capsule); 848 849 private: 850 MlirIntegerSet integerSet; 851 }; 852 853 void populateIRAffine(pybind11::module &m); 854 void populateIRAttributes(pybind11::module &m); 855 void populateIRCore(pybind11::module &m); 856 void populateIRTypes(pybind11::module &m); 857 858 } // namespace python 859 } // namespace mlir 860 861 namespace pybind11 { 862 namespace detail { 863 864 template <> 865 struct type_caster<mlir::python::DefaultingPyMlirContext> 866 : MlirDefaultingCaster<mlir::python::DefaultingPyMlirContext> {}; 867 template <> 868 struct type_caster<mlir::python::DefaultingPyLocation> 869 : MlirDefaultingCaster<mlir::python::DefaultingPyLocation> {}; 870 871 } // namespace detail 872 } // namespace pybind11 873 874 #endif // MLIR_BINDINGS_PYTHON_IRMODULES_H 875