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 605 /// Wrapper around the generic MlirAttribute. 606 /// The lifetime of a type is bound by the PyContext that created it. 607 class PyAttribute : public BaseContextObject { 608 public: 609 PyAttribute(PyMlirContextRef contextRef, MlirAttribute attr) 610 : BaseContextObject(std::move(contextRef)), attr(attr) {} 611 bool operator==(const PyAttribute &other); 612 operator MlirAttribute() const { return attr; } 613 MlirAttribute get() const { return attr; } 614 615 /// Gets a capsule wrapping the void* within the MlirAttribute. 616 pybind11::object getCapsule(); 617 618 /// Creates a PyAttribute from the MlirAttribute wrapped by a capsule. 619 /// Note that PyAttribute instances are uniqued, so the returned object 620 /// may be a pre-existing object. Ownership of the underlying MlirAttribute 621 /// is taken by calling this function. 622 static PyAttribute createFromCapsule(pybind11::object capsule); 623 624 private: 625 MlirAttribute attr; 626 }; 627 628 /// Represents a Python MlirNamedAttr, carrying an optional owned name. 629 /// TODO: Refactor this and the C-API to be based on an Identifier owned 630 /// by the context so as to avoid ownership issues here. 631 class PyNamedAttribute { 632 public: 633 /// Constructs a PyNamedAttr that retains an owned name. This should be 634 /// used in any code that originates an MlirNamedAttribute from a python 635 /// string. 636 /// The lifetime of the PyNamedAttr must extend to the lifetime of the 637 /// passed attribute. 638 PyNamedAttribute(MlirAttribute attr, std::string ownedName); 639 640 MlirNamedAttribute namedAttr; 641 642 private: 643 // Since the MlirNamedAttr contains an internal pointer to the actual 644 // memory of the owned string, it must be heap allocated to remain valid. 645 // Otherwise, strings that fit within the small object optimization threshold 646 // will have their memory address change as the containing object is moved, 647 // resulting in an invalid aliased pointer. 648 std::unique_ptr<std::string> ownedName; 649 }; 650 651 /// CRTP base classes for Python attributes that subclass Attribute and should 652 /// be castable from it (i.e. via something like StringAttr(attr)). 653 /// By default, attribute class hierarchies are one level deep (i.e. a 654 /// concrete attribute class extends PyAttribute); however, intermediate 655 /// python-visible base classes can be modeled by specifying a BaseTy. 656 template <typename DerivedTy, typename BaseTy = PyAttribute> 657 class PyConcreteAttribute : public BaseTy { 658 public: 659 // Derived classes must define statics for: 660 // IsAFunctionTy isaFunction 661 // const char *pyClassName 662 using ClassTy = pybind11::class_<DerivedTy, BaseTy>; 663 using IsAFunctionTy = bool (*)(MlirAttribute); 664 665 PyConcreteAttribute() = default; 666 PyConcreteAttribute(PyMlirContextRef contextRef, MlirAttribute attr) 667 : BaseTy(std::move(contextRef), attr) {} 668 PyConcreteAttribute(PyAttribute &orig) 669 : PyConcreteAttribute(orig.getContext(), castFrom(orig)) {} 670 671 static MlirAttribute castFrom(PyAttribute &orig) { 672 if (!DerivedTy::isaFunction(orig)) { 673 auto origRepr = pybind11::repr(pybind11::cast(orig)).cast<std::string>(); 674 throw SetPyError(PyExc_ValueError, 675 llvm::Twine("Cannot cast attribute to ") + 676 DerivedTy::pyClassName + " (from " + origRepr + ")"); 677 } 678 return orig; 679 } 680 681 static void bind(pybind11::module &m) { 682 auto cls = ClassTy(m, DerivedTy::pyClassName, pybind11::buffer_protocol(), 683 pybind11::module_local()); 684 cls.def(pybind11::init<PyAttribute &>(), pybind11::keep_alive<0, 1>()); 685 cls.def_static("isinstance", [](PyAttribute &otherAttr) -> bool { 686 return DerivedTy::isaFunction(otherAttr); 687 }); 688 DerivedTy::bindDerived(cls); 689 } 690 691 /// Implemented by derived classes to add methods to the Python subclass. 692 static void bindDerived(ClassTy &m) {} 693 }; 694 695 /// Wrapper around the generic MlirType. 696 /// The lifetime of a type is bound by the PyContext that created it. 697 class PyType : public BaseContextObject { 698 public: 699 PyType(PyMlirContextRef contextRef, MlirType type) 700 : BaseContextObject(std::move(contextRef)), type(type) {} 701 bool operator==(const PyType &other); 702 operator MlirType() const { return type; } 703 MlirType get() const { return type; } 704 705 /// Gets a capsule wrapping the void* within the MlirType. 706 pybind11::object getCapsule(); 707 708 /// Creates a PyType from the MlirType wrapped by a capsule. 709 /// Note that PyType instances are uniqued, so the returned object 710 /// may be a pre-existing object. Ownership of the underlying MlirType 711 /// is taken by calling this function. 712 static PyType createFromCapsule(pybind11::object capsule); 713 714 private: 715 MlirType type; 716 }; 717 718 /// CRTP base classes for Python types that subclass Type and should be 719 /// castable from it (i.e. via something like IntegerType(t)). 720 /// By default, type class hierarchies are one level deep (i.e. a 721 /// concrete type class extends PyType); however, intermediate python-visible 722 /// base classes can be modeled by specifying a BaseTy. 723 template <typename DerivedTy, typename BaseTy = PyType> 724 class PyConcreteType : public BaseTy { 725 public: 726 // Derived classes must define statics for: 727 // IsAFunctionTy isaFunction 728 // const char *pyClassName 729 using ClassTy = pybind11::class_<DerivedTy, BaseTy>; 730 using IsAFunctionTy = bool (*)(MlirType); 731 732 PyConcreteType() = default; 733 PyConcreteType(PyMlirContextRef contextRef, MlirType t) 734 : BaseTy(std::move(contextRef), t) {} 735 PyConcreteType(PyType &orig) 736 : PyConcreteType(orig.getContext(), castFrom(orig)) {} 737 738 static MlirType castFrom(PyType &orig) { 739 if (!DerivedTy::isaFunction(orig)) { 740 auto origRepr = pybind11::repr(pybind11::cast(orig)).cast<std::string>(); 741 throw SetPyError(PyExc_ValueError, llvm::Twine("Cannot cast type to ") + 742 DerivedTy::pyClassName + 743 " (from " + origRepr + ")"); 744 } 745 return orig; 746 } 747 748 static void bind(pybind11::module &m) { 749 auto cls = ClassTy(m, DerivedTy::pyClassName, pybind11::module_local()); 750 cls.def(pybind11::init<PyType &>(), pybind11::keep_alive<0, 1>()); 751 cls.def_static("isinstance", [](PyType &otherType) -> bool { 752 return DerivedTy::isaFunction(otherType); 753 }); 754 DerivedTy::bindDerived(cls); 755 } 756 757 /// Implemented by derived classes to add methods to the Python subclass. 758 static void bindDerived(ClassTy &m) {} 759 }; 760 761 /// Wrapper around the generic MlirValue. 762 /// Values are managed completely by the operation that resulted in their 763 /// definition. For op result value, this is the operation that defines the 764 /// value. For block argument values, this is the operation that contains the 765 /// block to which the value is an argument (blocks cannot be detached in Python 766 /// bindings so such operation always exists). 767 class PyValue { 768 public: 769 PyValue(PyOperationRef parentOperation, MlirValue value) 770 : parentOperation(parentOperation), value(value) {} 771 operator MlirValue() const { return value; } 772 773 MlirValue get() { return value; } 774 PyOperationRef &getParentOperation() { return parentOperation; } 775 776 void checkValid() { return parentOperation->checkValid(); } 777 778 /// Gets a capsule wrapping the void* within the MlirValue. 779 pybind11::object getCapsule(); 780 781 /// Creates a PyValue from the MlirValue wrapped by a capsule. Ownership of 782 /// the underlying MlirValue is still tied to the owning operation. 783 static PyValue createFromCapsule(pybind11::object capsule); 784 785 private: 786 PyOperationRef parentOperation; 787 MlirValue value; 788 }; 789 790 /// Wrapper around MlirAffineExpr. Affine expressions are owned by the context. 791 class PyAffineExpr : public BaseContextObject { 792 public: 793 PyAffineExpr(PyMlirContextRef contextRef, MlirAffineExpr affineExpr) 794 : BaseContextObject(std::move(contextRef)), affineExpr(affineExpr) {} 795 bool operator==(const PyAffineExpr &other); 796 operator MlirAffineExpr() const { return affineExpr; } 797 MlirAffineExpr get() const { return affineExpr; } 798 799 /// Gets a capsule wrapping the void* within the MlirAffineExpr. 800 pybind11::object getCapsule(); 801 802 /// Creates a PyAffineExpr from the MlirAffineExpr wrapped by a capsule. 803 /// Note that PyAffineExpr instances are uniqued, so the returned object 804 /// may be a pre-existing object. Ownership of the underlying MlirAffineExpr 805 /// is taken by calling this function. 806 static PyAffineExpr createFromCapsule(pybind11::object capsule); 807 808 PyAffineExpr add(const PyAffineExpr &other) const; 809 PyAffineExpr mul(const PyAffineExpr &other) const; 810 PyAffineExpr floorDiv(const PyAffineExpr &other) const; 811 PyAffineExpr ceilDiv(const PyAffineExpr &other) const; 812 PyAffineExpr mod(const PyAffineExpr &other) const; 813 814 private: 815 MlirAffineExpr affineExpr; 816 }; 817 818 class PyAffineMap : public BaseContextObject { 819 public: 820 PyAffineMap(PyMlirContextRef contextRef, MlirAffineMap affineMap) 821 : BaseContextObject(std::move(contextRef)), affineMap(affineMap) {} 822 bool operator==(const PyAffineMap &other); 823 operator MlirAffineMap() const { return affineMap; } 824 MlirAffineMap get() const { return affineMap; } 825 826 /// Gets a capsule wrapping the void* within the MlirAffineMap. 827 pybind11::object getCapsule(); 828 829 /// Creates a PyAffineMap from the MlirAffineMap wrapped by a capsule. 830 /// Note that PyAffineMap instances are uniqued, so the returned object 831 /// may be a pre-existing object. Ownership of the underlying MlirAffineMap 832 /// is taken by calling this function. 833 static PyAffineMap createFromCapsule(pybind11::object capsule); 834 835 private: 836 MlirAffineMap affineMap; 837 }; 838 839 class PyIntegerSet : public BaseContextObject { 840 public: 841 PyIntegerSet(PyMlirContextRef contextRef, MlirIntegerSet integerSet) 842 : BaseContextObject(std::move(contextRef)), integerSet(integerSet) {} 843 bool operator==(const PyIntegerSet &other); 844 operator MlirIntegerSet() const { return integerSet; } 845 MlirIntegerSet get() const { return integerSet; } 846 847 /// Gets a capsule wrapping the void* within the MlirIntegerSet. 848 pybind11::object getCapsule(); 849 850 /// Creates a PyIntegerSet from the MlirAffineMap wrapped by a capsule. 851 /// Note that PyIntegerSet instances may be uniqued, so the returned object 852 /// may be a pre-existing object. Integer sets are owned by the context. 853 static PyIntegerSet createFromCapsule(pybind11::object capsule); 854 855 private: 856 MlirIntegerSet integerSet; 857 }; 858 859 void populateIRAffine(pybind11::module &m); 860 void populateIRAttributes(pybind11::module &m); 861 void populateIRCore(pybind11::module &m); 862 void populateIRTypes(pybind11::module &m); 863 864 } // namespace python 865 } // namespace mlir 866 867 namespace pybind11 { 868 namespace detail { 869 870 template <> 871 struct type_caster<mlir::python::DefaultingPyMlirContext> 872 : MlirDefaultingCaster<mlir::python::DefaultingPyMlirContext> {}; 873 template <> 874 struct type_caster<mlir::python::DefaultingPyLocation> 875 : MlirDefaultingCaster<mlir::python::DefaultingPyLocation> {}; 876 877 } // namespace detail 878 } // namespace pybind11 879 880 #endif // MLIR_BINDINGS_PYTHON_IRMODULES_H 881