10 #ifndef MLIR_BINDINGS_PYTHON_IRMODULES_H
11 #define MLIR_BINDINGS_PYTHON_IRMODULES_H
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/Support/ThreadPool.h"
37 class PyDiagnosticHandler;
38 class PyInsertionPoint;
40 class DefaultingPyLocation;
42 class DefaultingPyMlirContext;
45 class PyOperationBase;
56 : referrent(referrent), object(std::move(object)) {
57 assert(this->referrent &&
58 "cannot construct PyObjectRef with null referrent");
59 assert(this->
object &&
"cannot construct PyObjectRef with null object");
62 : referrent(other.referrent), object(std::move(other.object)) {
63 other.referrent =
nullptr;
64 assert(!other.object);
67 : referrent(other.referrent), object(other.object ) {}
73 return Py_REFCNT(
object.ptr());
80 assert(referrent &&
object);
82 auto stolen = std::move(
object);
86 T *
get() {
return referrent; }
88 assert(referrent &&
object);
92 assert(referrent &&
object);
95 operator bool()
const {
return referrent && object; }
97 using NBTypedT = nanobind::typed<nanobind::object, T>;
101 nanobind::object object;
121 nanobind::object insertionPoint,
122 nanobind::object location)
123 : context(std::move(context)), insertionPoint(std::move(insertionPoint)),
124 location(std::move(location)), frameKind(frameKind) {}
142 static nanobind::object
pushContext(nanobind::object context);
146 static nanobind::object
pushLocation(nanobind::object location);
150 static std::vector<PyThreadContextEntry> &
getStack();
153 static void push(
FrameKind frameKind, nanobind::object context,
154 nanobind::object insertionPoint, nanobind::object location);
157 nanobind::object context;
159 nanobind::object insertionPoint;
161 nanobind::object location;
171 ownedThreadPool = std::make_unique<llvm::DefaultThreadPool>();
177 MlirLlvmThreadPool
get() {
return wrap(ownedThreadPool.get()); }
180 std::stringstream ss;
181 ss << ownedThreadPool.get();
186 std::unique_ptr<llvm::ThreadPoolInterface> ownedThreadPool;
204 MlirContext
get() {
return context; }
229 static nanobind::object
contextEnter(nanobind::object context);
231 const nanobind::object &excVal,
232 const nanobind::object &excTb);
252 static nanobind::ft_mutex live_contexts_mutex;
253 static LiveContextMap &getLiveContexts();
259 using LiveModuleMap =
261 LiveModuleMap liveModules;
263 bool emitErrorDiagnostics =
false;
273 :
public Defaulting<DefaultingPyMlirContext, PyMlirContext> {
287 assert(this->contextRef &&
288 "context object constructed with null context ref");
304 operator MlirLocation()
const {
return loc; }
305 MlirLocation
get()
const {
return loc; }
308 static nanobind::object
contextEnter(nanobind::object location);
310 const nanobind::object &excVal,
311 const nanobind::object &excTb);
357 std::optional<nanobind::tuple> materializedNotes;
393 const nanobind::object &excVal,
394 const nanobind::object &excTb) {
400 nanobind::object callback;
401 std::optional<MlirDiagnosticHandlerID> registeredID;
402 bool hadError =
false;
411 ctx->
get(), handler, this,
415 assert(errors.empty() &&
"unhandled captured errors");
418 std::vector<PyDiagnostic::DiagnosticInfo>
take() {
419 return std::move(errors);
425 std::vector<PyDiagnostic::DiagnosticInfo> errors;
440 MlirDialect
get() {
return dialect; }
461 PyDialect(nanobind::object descriptor) : descriptor(std::move(descriptor)) {}
466 nanobind::object descriptor;
482 : registry(other.registry) {
483 other.registry = {
nullptr};
486 operator MlirDialectRegistry()
const {
return registry; }
487 MlirDialectRegistry
get()
const {
return registry; }
493 MlirDialectRegistry registry;
499 :
public Defaulting<DefaultingPyLocation, PyLocation> {
505 operator MlirLocation()
const {
return *
get(); }
522 MlirModule
get() {
return module; }
526 return PyModuleRef(
this, nanobind::borrow<nanobind::object>(handle));
545 nanobind::handle handle;
556 void print(std::optional<int64_t> largeElementsLimit,
557 std::optional<int64_t> largeResourceLimit,
bool enableDebugInfo,
558 bool prettyDebugInfo,
bool printGenericOpForm,
bool useLocalScope,
559 bool useNameLocAsPrefix,
bool assumeVerified,
560 nanobind::object fileObject,
bool binary,
bool skipRegions);
564 getAsm(
bool binary, std::optional<int64_t> largeElementsLimit,
565 std::optional<int64_t> largeResourceLimit,
bool enableDebugInfo,
566 bool prettyDebugInfo,
bool printGenericOpForm,
bool useLocalScope,
567 bool useNameLocAsPrefix,
bool assumeVerified,
bool skipRegions);
571 std::optional<int64_t> bytecodeVersion);
614 nanobind::object parentKeepAlive = nanobind::object());
620 nanobind::object parentKeepAlive = nanobind::object());
625 const std::string &sourceStr,
626 const std::string &sourceName);
633 parentKeepAlive = nanobind::object();
637 operator MlirOperation()
const {
return get(); }
638 MlirOperation
get()
const {
644 return PyOperationRef(
this, nanobind::borrow<nanobind::object>(handle));
648 void setAttached(
const nanobind::object &parent = nanobind::object()) {
649 assert(!attached &&
"operation already attached");
653 assert(attached &&
"operation already detached");
675 static nanobind::object
676 create(std::string_view name, std::optional<std::vector<PyType *>> results,
678 std::optional<nanobind::dict> attributes,
679 std::optional<std::vector<PyBlock *>> successors,
int regions,
680 PyLocation &location,
const nanobind::object &ip,
bool inferType);
693 nanobind::object
clone(
const nanobind::object &ip);
699 MlirOperation operation,
700 nanobind::object parentKeepAlive);
702 MlirOperation operation;
703 nanobind::handle handle;
710 nanobind::object parentKeepAlive;
711 bool attached =
true;
725 PyOpView(
const nanobind::object &operationObject);
730 static nanobind::object
731 buildGeneric(std::string_view name, std::tuple<int, bool> opRegionSpec,
732 nanobind::object operandSegmentSpecObj,
733 nanobind::object resultSegmentSpecObj,
734 std::optional<nanobind::list> resultTypeList,
735 nanobind::list operandList,
736 std::optional<nanobind::dict> attributes,
737 std::optional<std::vector<PyBlock *>> successors,
738 std::optional<int> regions,
PyLocation &location,
739 const nanobind::object &maybeIp);
749 const nanobind::object &operation);
753 nanobind::object operationObject;
762 : parentOperation(std::move(parentOperation)), region(region) {
765 operator MlirRegion()
const {
return region; }
767 MlirRegion
get() {
return region; }
803 MlirAsmState
get() {
return state; }
807 MlirOpPrintingFlags flags;
816 : parentOperation(std::move(parentOperation)), block(block) {
820 MlirBlock
get() {
return block; }
859 static nanobind::object
contextEnter(nanobind::object insertionPoint);
861 const nanobind::object &excVal,
862 const nanobind::object &excTb);
871 : refOperation(std::move(refOperation)), block(std::move(block)) {}
873 std::optional<PyOperationRef> refOperation;
883 operator MlirType()
const {
return type; }
884 MlirType
get()
const {
return type; }
911 operator MlirTypeID()
const {
return typeID; }
912 MlirTypeID
get() {
return typeID; }
929 template <
typename DerivedTy,
typename BaseTy = PyType>
935 using ClassTy = nanobind::class_<DerivedTy, BaseTy>;
942 : BaseTy(std::move(contextRef), t) {}
947 if (!DerivedTy::isaFunction(orig)) {
949 nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
950 throw nanobind::value_error((llvm::Twine(
"Cannot cast type to ") +
951 DerivedTy::pyClassName +
" (from " +
959 static void bind(nanobind::module_ &m) {
960 auto cls =
ClassTy(m, DerivedTy::pyClassName);
961 cls.def(nanobind::init<PyType &>(), nanobind::keep_alive<0, 1>(),
962 nanobind::arg(
"cast_from_type"));
965 [](
PyType &otherType) ->
bool {
966 return DerivedTy::isaFunction(otherType);
968 nanobind::arg(
"other"));
969 cls.def_prop_ro_static(
971 [](nanobind::object & ) {
972 if (DerivedTy::getTypeIdFunction)
973 return PyTypeID(DerivedTy::getTypeIdFunction());
974 throw nanobind::attribute_error(
975 (DerivedTy::pyClassName + llvm::Twine(
" has no typeid."))
979 nanobind::sig(
"def static_typeid(/) -> TypeID"));
980 cls.def_prop_ro(
"typeid", [](
PyType &
self) {
981 return nanobind::cast<PyTypeID>(nanobind::cast(
self).attr(
"typeid"));
983 cls.def(
"__repr__", [](
DerivedTy &
self) {
985 printAccum.
parts.append(DerivedTy::pyClassName);
986 printAccum.
parts.append(
"(");
988 printAccum.
parts.append(
")");
989 return printAccum.
join();
992 if (DerivedTy::getTypeIdFunction) {
994 DerivedTy::getTypeIdFunction(),
995 nanobind::cast<nanobind::callable>(nanobind::cpp_function(
999 DerivedTy::bindDerived(cls);
1013 operator MlirAttribute()
const {
return attr; }
1014 MlirAttribute
get()
const {
return attr; }
1051 std::unique_ptr<std::string> ownedName;
1059 template <
typename DerivedTy,
typename BaseTy = PyAttribute>
1065 using ClassTy = nanobind::class_<DerivedTy, BaseTy>;
1072 : BaseTy(std::move(contextRef), attr) {}
1077 if (!DerivedTy::isaFunction(orig)) {
1079 nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
1080 throw nanobind::value_error((llvm::Twine(
"Cannot cast attribute to ") +
1081 DerivedTy::pyClassName +
" (from " +
1089 static void bind(nanobind::module_ &m, PyType_Slot *slots =
nullptr) {
1092 cls =
ClassTy(m, DerivedTy::pyClassName, nanobind::type_slots(slots));
1094 cls =
ClassTy(m, DerivedTy::pyClassName);
1096 cls.def(nanobind::init<PyAttribute &>(), nanobind::keep_alive<0, 1>(),
1097 nanobind::arg(
"cast_from_attr"));
1101 return DerivedTy::isaFunction(otherAttr);
1103 nanobind::arg(
"other"));
1106 [](
PyAttribute &attr) -> nanobind::typed<nanobind::object, PyType> {
1110 cls.def_prop_ro_static(
1112 [](nanobind::object & ) ->
PyTypeID {
1113 if (DerivedTy::getTypeIdFunction)
1114 return PyTypeID(DerivedTy::getTypeIdFunction());
1115 throw nanobind::attribute_error(
1116 (DerivedTy::pyClassName + llvm::Twine(
" has no typeid."))
1120 nanobind::sig(
"def static_typeid(/) -> TypeID"));
1122 return nanobind::cast<PyTypeID>(nanobind::cast(
self).attr(
"typeid"));
1124 cls.def(
"__repr__", [](
DerivedTy &
self) {
1126 printAccum.
parts.append(DerivedTy::pyClassName);
1127 printAccum.
parts.append(
"(");
1130 printAccum.
parts.append(
")");
1131 return printAccum.
join();
1134 if (DerivedTy::getTypeIdFunction) {
1136 DerivedTy::getTypeIdFunction(),
1137 nanobind::cast<nanobind::callable>(
1143 DerivedTy::bindDerived(cls);
1174 : parentOperation(std::move(parentOperation)), value(value) {}
1175 operator MlirValue()
const {
return value; }
1177 MlirValue
get() {
return value; }
1202 operator MlirAffineExpr()
const {
return affineExpr; }
1203 MlirAffineExpr
get()
const {
return affineExpr; }
1221 MlirAffineExpr affineExpr;
1229 operator MlirAffineMap()
const {
return affineMap; }
1230 MlirAffineMap
get()
const {
return affineMap; }
1242 MlirAffineMap affineMap;
1250 operator MlirIntegerSet()
const {
return integerSet; }
1251 MlirIntegerSet
get()
const {
return integerSet; }
1262 MlirIntegerSet integerSet;
1283 void dunderDel(
const std::string &name);
1296 const std::string &visibility);
1301 const std::string &newSymbol,
1306 nanobind::object callback);
1309 operator MlirSymbolTable() {
return symbolTable; }
1313 MlirSymbolTable symbolTable;
1339 struct type_caster<
mlir::python::DefaultingPyMlirContext>
1342 struct type_caster<
mlir::python::DefaultingPyLocation>
static std::string diag(const llvm::Value &value)
Base class for all objects that directly or indirectly depend on an MlirContext.
PyMlirContextRef & getContext()
Accesses the context reference.
BaseContextObject(PyMlirContextRef ref)
Used in function arguments when None should resolve to the current context manager set instance.
static PyLocation & resolve()
static constexpr const char kTypeDescription[]
Used in function arguments when None should resolve to the current context manager set instance.
static constexpr const char kTypeDescription[]
static PyMlirContext & resolve()
CRTP template for special wrapper types that are allowed to be passed in as 'None' function arguments...
ReferrentTy * get() const
Defaulting()=default
Type casters require the type to be default constructible, but using such an instance is illegal.
Wrapper around MlirAffineExpr. Affine expressions are owned by the context.
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirAffineExpr.
static PyAffineExpr createFromCapsule(const nanobind::object &capsule)
Creates a PyAffineExpr from the MlirAffineExpr wrapped by a capsule.
PyAffineExpr(PyMlirContextRef contextRef, MlirAffineExpr affineExpr)
PyAffineExpr ceilDiv(const PyAffineExpr &other) const
PyAffineExpr mul(const PyAffineExpr &other) const
PyAffineExpr mod(const PyAffineExpr &other) const
PyAffineExpr floorDiv(const PyAffineExpr &other) const
bool operator==(const PyAffineExpr &other) const
PyAffineExpr add(const PyAffineExpr &other) const
MlirAffineExpr get() const
PyAffineMap(PyMlirContextRef contextRef, MlirAffineMap affineMap)
bool operator==(const PyAffineMap &other) const
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirAffineMap.
MlirAffineMap get() const
static PyAffineMap createFromCapsule(const nanobind::object &capsule)
Creates a PyAffineMap from the MlirAffineMap wrapped by a capsule.
Wrapper around an MlirAsmState.
PyAsmState(PyOperationBase &operation, bool useLocalScope)
PyAsmState(MlirValue value, bool useLocalScope)
PyAsmState(PyAsmState &other)=delete
PyAsmState(const PyAsmState &other)=delete
Wrapper around the generic MlirAttribute.
static PyAttribute createFromCapsule(const nanobind::object &capsule)
Creates a PyAttribute from the MlirAttribute wrapped by a capsule.
PyAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirAttribute.
nanobind::object maybeDownCast()
MlirAttribute get() const
bool operator==(const PyAttribute &other) const
Wrapper around an MlirBlock.
PyOperationRef & getParentOperation()
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirBlock.
PyBlock(PyOperationRef parentOperation, MlirBlock block)
CRTP base classes for Python attributes that subclass Attribute and should be castable from it (i....
MlirTypeID(*)() GetTypeIDFunctionTy
static MlirAttribute castFrom(PyAttribute &orig)
nanobind::class_< DerivedTy, BaseTy > ClassTy
static constexpr GetTypeIDFunctionTy getTypeIdFunction
PyConcreteAttribute()=default
static void bind(nanobind::module_ &m, PyType_Slot *slots=nullptr)
bool(*)(MlirAttribute) IsAFunctionTy
PyConcreteAttribute(PyAttribute &orig)
PyConcreteAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
static void bindDerived(ClassTy &m)
Implemented by derived classes to add methods to the Python subclass.
CRTP base classes for Python types that subclass Type and should be castable from it (i....
nanobind::class_< DerivedTy, BaseTy > ClassTy
static void bind(nanobind::module_ &m)
PyConcreteType(PyType &orig)
MlirTypeID(*)() GetTypeIDFunctionTy
bool(*)(MlirType) IsAFunctionTy
static void bindDerived(ClassTy &m)
Implemented by derived classes to add methods to the Python subclass.
static constexpr GetTypeIDFunctionTy getTypeIdFunction
PyConcreteType(PyMlirContextRef contextRef, MlirType t)
static MlirType castFrom(PyType &orig)
Represents a diagnostic handler attached to the context.
PyDiagnosticHandler(MlirContext context, nanobind::object callback)
nanobind::object contextEnter()
void detach()
Detaches the handler. Does nothing if not attached.
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
Python class mirroring the C MlirDiagnostic struct.
nanobind::tuple getNotes()
nanobind::str getMessage()
PyDiagnostic(MlirDiagnostic diagnostic)
MlirDiagnosticSeverity getSeverity()
Wrapper around an MlirDialect.
PyDialectDescriptor(PyMlirContextRef contextRef, MlirDialect dialect)
Wrapper around an MlirDialectRegistry.
PyDialectRegistry(PyDialectRegistry &&other) noexcept
nanobind::object getCapsule()
PyDialectRegistry(PyDialectRegistry &)=delete
static PyDialectRegistry createFromCapsule(nanobind::object capsule)
MlirDialectRegistry get() const
PyDialectRegistry(MlirDialectRegistry registry)
User-level dialect object.
PyDialect(nanobind::object descriptor)
nanobind::object getDescriptor()
User-level object for accessing dialects with dotted syntax such as: ctx.dialect.std.
PyDialects(PyMlirContextRef contextRef)
MlirDialect getDialectForKey(const std::string &key, bool attrError)
void registerTypeCaster(MlirTypeID mlirTypeID, nanobind::callable typeCaster, bool replace=false)
Adds a user-friendly type caster.
static PyGlobals & get()
Most code should get the globals via this static accessor.
An insertion point maintains a pointer to a Block and a reference operation.
static PyInsertionPoint atBlockTerminator(PyBlock &block)
Shortcut to create an insertion point before the block terminator.
static PyInsertionPoint atBlockBegin(PyBlock &block)
Shortcut to create an insertion point at the beginning of the block.
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
static PyInsertionPoint after(PyOperationBase &op)
Shortcut to create an insertion point to the node after the specified operation.
PyInsertionPoint(const PyBlock &block)
Creates an insertion point positioned after the last operation in the block, but still inside the blo...
void insert(PyOperationBase &operationBase)
Inserts an operation.
std::optional< PyOperationRef > & getRefOperation()
static nanobind::object contextEnter(nanobind::object insertionPoint)
Enter and exit the context manager.
static PyIntegerSet createFromCapsule(const nanobind::object &capsule)
Creates a PyIntegerSet from the MlirAffineMap wrapped by a capsule.
MlirIntegerSet get() const
bool operator==(const PyIntegerSet &other) const
PyIntegerSet(PyMlirContextRef contextRef, MlirIntegerSet integerSet)
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirIntegerSet.
Wrapper around an MlirLocation.
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirLocation.
PyLocation(PyMlirContextRef contextRef, MlirLocation loc)
static PyLocation createFromCapsule(nanobind::object capsule)
Creates a PyLocation from the MlirLocation wrapped by a capsule.
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
static nanobind::object contextEnter(nanobind::object location)
Enter and exit the context manager.
PyMlirContext(const PyMlirContext &)=delete
PyMlirContext(PyMlirContext &&)=delete
MlirContext get()
Accesses the underlying MlirContext.
PyMlirContextRef getRef()
Gets a strong reference to this context, which will ensure it is kept alive for the life of the refer...
static size_t getLiveCount()
Gets the count of live context objects. Used for testing.
size_t getLiveModuleCount()
Gets the count of live modules associated with this context.
nanobind::object attachDiagnosticHandler(nanobind::object callback)
Attaches a Python callback as a diagnostic handler, returning a registration object (internally a PyD...
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirContext.
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
static PyMlirContextRef forContext(MlirContext context)
Returns a context reference for the singleton PyMlirContext wrapper for the given context.
static nanobind::object createFromCapsule(nanobind::object capsule)
Creates a PyMlirContext from the MlirContext wrapped by a capsule.
static nanobind::object contextEnter(nanobind::object context)
Enter and exit the context manager.
void setEmitErrorDiagnostics(bool value)
Controls whether error diagnostics should be propagated to diagnostic handlers, instead of being capt...
bool getEmitErrorDiagnostics()
MlirModule get()
Gets the backing MlirModule.
static PyModuleRef forModule(MlirModule module)
Returns a PyModule reference for the given MlirModule.
static nanobind::object createFromCapsule(nanobind::object capsule)
Creates a PyModule from the MlirModule wrapped by a capsule.
PyModuleRef getRef()
Gets a strong reference to this module.
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirModule.
PyModule(PyModule &)=delete
PyModule(PyMlirContext &&)=delete
Represents a Python MlirNamedAttr, carrying an optional owned name.
PyNamedAttribute(MlirAttribute attr, std::string ownedName)
Constructs a PyNamedAttr that retains an owned name.
MlirNamedAttribute namedAttr
Template for a reference to a concrete type which captures a python reference to its underlying pytho...
nanobind::typed< nanobind::object, T > NBTypedT
nanobind::object getObject()
PyObjectRef(T *referrent, nanobind::object object)
nanobind::object releaseObject()
Releases the object held by this instance, returning it.
PyObjectRef(PyObjectRef &&other) noexcept
PyObjectRef(const PyObjectRef &other)
A PyOpView is equivalent to the C++ "Op" wrappers: these are the basis for providing more instance-sp...
static nanobind::object constructDerived(const nanobind::object &cls, const nanobind::object &operation)
Construct an instance of a class deriving from OpView, bypassing its __init__ method.
nanobind::object getOperationObject()
static nanobind::object buildGeneric(std::string_view name, std::tuple< int, bool > opRegionSpec, nanobind::object operandSegmentSpecObj, nanobind::object resultSegmentSpecObj, std::optional< nanobind::list > resultTypeList, nanobind::list operandList, std::optional< nanobind::dict > attributes, std::optional< std::vector< PyBlock * >> successors, std::optional< int > regions, PyLocation &location, const nanobind::object &maybeIp)
PyOpView(const nanobind::object &operationObject)
PyOperation & getOperation() override
Each must provide access to the raw Operation.
Base class for PyOperation and PyOpView which exposes the primary, user visible methods for manipulat...
void walk(std::function< MlirWalkResult(MlirOperation)> callback, MlirWalkOrder walkOrder)
bool isBeforeInBlock(PyOperationBase &other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
virtual PyOperation & getOperation()=0
Each must provide access to the raw Operation.
nanobind::object getAsm(bool binary, std::optional< int64_t > largeElementsLimit, std::optional< int64_t > largeResourceLimit, bool enableDebugInfo, bool prettyDebugInfo, bool printGenericOpForm, bool useLocalScope, bool useNameLocAsPrefix, bool assumeVerified, bool skipRegions)
void print(PyAsmState &state, nanobind::object fileObject, bool binary)
virtual ~PyOperationBase()=default
void moveAfter(PyOperationBase &other)
Moves the operation before or after the other operation.
void print(std::optional< int64_t > largeElementsLimit, std::optional< int64_t > largeResourceLimit, bool enableDebugInfo, bool prettyDebugInfo, bool printGenericOpForm, bool useLocalScope, bool useNameLocAsPrefix, bool assumeVerified, nanobind::object fileObject, bool binary, bool skipRegions)
Implements the bound 'print' method and helps with others.
void writeBytecode(const nanobind::object &fileObject, std::optional< int64_t > bytecodeVersion)
void moveBefore(PyOperationBase &other)
bool verify()
Verify the operation.
void detachFromParent()
Detaches the operation from its parent block and updates its state accordingly.
PyOperation(PyMlirContextRef contextRef, MlirOperation operation)
void erase()
Erases the underlying MlirOperation, removes its pointer from the parent context's live operations ma...
static nanobind::object createFromCapsule(const nanobind::object &capsule)
Creates a PyOperation from the MlirOperation wrapped by a capsule.
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirOperation.
static PyOperationRef createDetached(PyMlirContextRef contextRef, MlirOperation operation, nanobind::object parentKeepAlive=nanobind::object())
Creates a detached operation.
nanobind::object clone(const nanobind::object &ip)
Clones this operation.
PyOperation & getOperation() override
Each must provide access to the raw Operation.
MlirOperation get() const
static PyOperationRef forOperation(PyMlirContextRef contextRef, MlirOperation operation, nanobind::object parentKeepAlive=nanobind::object())
Returns a PyOperation for the given MlirOperation, optionally associating it with a parentKeepAlive.
void setAttached(const nanobind::object &parent=nanobind::object())
std::optional< PyOperationRef > getParentOperation()
Gets the parent operation or raises an exception if the operation has no parent.
static nanobind::object create(std::string_view name, std::optional< std::vector< PyType * >> results, llvm::ArrayRef< MlirValue > operands, std::optional< nanobind::dict > attributes, std::optional< std::vector< PyBlock * >> successors, int regions, PyLocation &location, const nanobind::object &ip, bool inferType)
Creates an operation. See corresponding python docstring.
nanobind::object createOpView()
Creates an OpView suitable for this operation.
PyBlock getBlock()
Gets the owning block or raises an exception if the operation has no owning block.
static PyOperationRef parse(PyMlirContextRef contextRef, const std::string &sourceStr, const std::string &sourceName)
Parses a source string (either text assembly or bytecode), creating a detached operation.
void setInvalid()
Invalidate the operation.
Wrapper around an MlirRegion.
PyRegion(PyOperationRef parentOperation, MlirRegion region)
PyOperationRef & getParentOperation()
static constexpr GetTypeIDFunctionTy getTypeIdFunction
static constexpr IsAFunctionTy isaFunction
static constexpr const char * pyClassName
static void bindDerived(ClassTy &c)
Bindings for MLIR symbol tables.
void dunderDel(const std::string &name)
Removes the operation with the given name from the symbol table and erases it, throws if there is no ...
static void walkSymbolTables(PyOperationBase &from, bool allSymUsesVisible, nanobind::object callback)
Walks all symbol tables under and including 'from'.
static void replaceAllSymbolUses(const std::string &oldSymbol, const std::string &newSymbol, PyOperationBase &from)
Replaces all symbol uses within an operation.
static void setVisibility(PyOperationBase &symbol, const std::string &visibility)
static void setSymbolName(PyOperationBase &symbol, const std::string &name)
~PySymbolTable()
Destroys the symbol table.
PyStringAttribute insert(PyOperationBase &symbol)
Inserts the given operation into the symbol table.
void erase(PyOperationBase &symbol)
Removes the given operation from the symbol table and erases it.
PySymbolTable(PyOperationBase &operation)
Constructs a symbol table for the given operation.
static PyStringAttribute getSymbolName(PyOperationBase &symbol)
Gets and sets the name of a symbol op.
static PyStringAttribute getVisibility(PyOperationBase &symbol)
Gets and sets the visibility of a symbol op.
nanobind::object dunderGetItem(const std::string &name)
Returns the symbol (opview) with the given name, throws if there is no such symbol in the table.
Tracks an entry in the thread context stack.
static PyThreadContextEntry * getTopOfStack()
Stack management.
static void popLocation(PyLocation &location)
static nanobind::object pushLocation(nanobind::object location)
PyLocation * getLocation()
static nanobind::object pushContext(nanobind::object context)
static PyLocation * getDefaultLocation()
Gets the top of stack location and returns nullptr if not defined.
static void popInsertionPoint(PyInsertionPoint &insertionPoint)
static nanobind::object pushInsertionPoint(nanobind::object insertionPoint)
static void popContext(PyMlirContext &context)
static PyInsertionPoint * getDefaultInsertionPoint()
Gets the top of stack insertion point and return nullptr if not defined.
PyMlirContext * getContext()
static PyMlirContext * getDefaultContext()
Gets the top of stack context and return nullptr if not defined.
static std::vector< PyThreadContextEntry > & getStack()
Gets the thread local stack.
PyThreadContextEntry(FrameKind frameKind, nanobind::object context, nanobind::object insertionPoint, nanobind::object location)
PyInsertionPoint * getInsertionPoint()
Wrapper around MlirLlvmThreadPool Python object owns the C++ thread pool.
std::string _mlir_thread_pool_ptr() const
PyThreadPool(const PyThreadPool &)=delete
int getMaxConcurrency() const
PyThreadPool(PyThreadPool &&)=delete
A TypeID provides an efficient and unique identifier for a specific C++ type.
static PyTypeID createFromCapsule(nanobind::object capsule)
Creates a PyTypeID from the MlirTypeID wrapped by a capsule.
bool operator==(const PyTypeID &other) const
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirTypeID.
PyTypeID(MlirTypeID typeID)
Wrapper around the generic MlirType.
PyType(PyMlirContextRef contextRef, MlirType type)
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirType.
static PyType createFromCapsule(nanobind::object capsule)
Creates a PyType from the MlirType wrapped by a capsule.
nanobind::object maybeDownCast()
bool operator==(const PyType &other) const
Wrapper around the generic MlirValue.
PyValue(PyOperationRef parentOperation, MlirValue value)
static PyValue createFromCapsule(nanobind::object capsule)
Creates a PyValue from the MlirValue wrapped by a capsule.
nanobind::object maybeDownCast()
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirValue.
virtual ~PyValue()=default
PyOperationRef & getParentOperation()
MlirDiagnosticSeverity
Severity of a diagnostic.
MLIR_CAPI_EXPORTED MlirDiagnosticHandlerID mlirContextAttachDiagnosticHandler(MlirContext context, MlirDiagnosticHandler handler, void *userData, void(*deleteUserData)(void *))
Attaches the diagnostic handler to the context.
MLIR_CAPI_EXPORTED void mlirContextDetachDiagnosticHandler(MlirContext context, MlirDiagnosticHandlerID id)
Detaches an attached diagnostic handler from the context given its identifier.
uint64_t MlirDiagnosticHandlerID
Opaque identifier of a diagnostic handler, useful to detach a handler.
MlirDiagnostic wrap(mlir::Diagnostic &diagnostic)
MLIR_CAPI_EXPORTED MlirTypeID mlirStringAttrGetTypeID(void)
Returns the typeID of a String attribute.
MLIR_CAPI_EXPORTED bool mlirAttributeIsAString(MlirAttribute attr)
Checks whether the given attribute is a string attribute.
MlirWalkOrder
Traversal order for operation walk.
MLIR_CAPI_EXPORTED void mlirOpPrintingFlagsUseLocalScope(MlirOpPrintingFlags flags)
Use local scope when printing the operation.
MLIR_CAPI_EXPORTED void mlirDialectRegistryDestroy(MlirDialectRegistry registry)
Takes a dialect registry owned by the caller and destroys it.
MLIR_CAPI_EXPORTED MlirType mlirAttributeGetType(MlirAttribute attribute)
Gets the type of this attribute.
MLIR_CAPI_EXPORTED void mlirTypePrint(MlirType type, MlirStringCallback callback, void *userData)
Prints a location by sending chunks of the string representation and forwarding userData tocallback`.
MLIR_CAPI_EXPORTED void mlirAttributePrint(MlirAttribute attr, MlirStringCallback callback, void *userData)
Prints an attribute by sending chunks of the string representation and forwarding userData tocallback...
MlirWalkResult
Operation walk result.
MLIR_CAPI_EXPORTED MlirAsmState mlirAsmStateCreateForOperation(MlirOperation op, MlirOpPrintingFlags flags)
Creates new AsmState, as with AsmState the IR should not be mutated in-between using this state.
static bool mlirBlockIsNull(MlirBlock block)
Checks whether a block is null.
MLIR_CAPI_EXPORTED void mlirSymbolTableDestroy(MlirSymbolTable symbolTable)
Destroys the symbol table created with mlirSymbolTableCreate.
static bool mlirDialectRegistryIsNull(MlirDialectRegistry registry)
Checks if the dialect registry is null.
static bool mlirRegionIsNull(MlirRegion region)
Checks whether a region is null.
MLIR_CAPI_EXPORTED void mlirOpPrintingFlagsDestroy(MlirOpPrintingFlags flags)
Destroys printing flags created with mlirOpPrintingFlagsCreate.
MLIR_CAPI_EXPORTED MlirDialectRegistry mlirDialectRegistryCreate(void)
Creates a dialect registry and transfers its ownership to the caller.
MLIR_CAPI_EXPORTED void mlirOperationRemoveFromParent(MlirOperation op)
Removes the given operation from its parent block.
MLIR_CAPI_EXPORTED MlirOpPrintingFlags mlirOpPrintingFlagsCreate(void)
Creates new printing flags with defaults, intended for customization.
MLIR_CAPI_EXPORTED MlirAsmState mlirAsmStateCreateForValue(MlirValue value, MlirOpPrintingFlags flags)
Creates new AsmState from value.
PyObjectRef< PyMlirContext > PyMlirContextRef
Wrapper around MlirContext.
void populateIRAttributes(nanobind::module_ &m)
void populateIRInterfaces(nb::module_ &m)
PyObjectRef< PyModule > PyModuleRef
void populateIRAffine(nanobind::module_ &m)
void populateIRTypes(nanobind::module_ &m)
void populateIRCore(nanobind::module_ &m)
PyObjectRef< PyOperation > PyOperationRef
Include the generated interface declarations.
An opaque reference to a diagnostic, always owned by the diagnostics engine (context).
A logical result value, essentially a boolean with named states.
Accumulates into a python string from a method that accepts an MlirStringCallback.
MlirStringCallback getCallback()
Custom exception that allows access to error diagnostic information.
MLIRError(llvm::Twine message, std::vector< PyDiagnostic::DiagnosticInfo > &&errorDiagnostics={})
std::vector< PyDiagnostic::DiagnosticInfo > errorDiagnostics
Materialized diagnostic information.
MlirDiagnosticSeverity severity
std::vector< DiagnosticInfo > notes
RAII object that captures any error diagnostics emitted to the provided context.
std::vector< PyDiagnostic::DiagnosticInfo > take()
ErrorCapture(PyMlirContextRef ctx)