10#ifndef MLIR_BINDINGS_PYTHON_IRCORE_H
11#define MLIR_BINDINGS_PYTHON_IRCORE_H
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/Support/FormatVariadic.h"
34#include "llvm/Support/ThreadPool.h"
57 static void set(nanobind::object &o,
bool enable);
58 static bool get(
const nanobind::object &);
59 static void bind(nanobind::module_ &m);
62 static nanobind::ft_mutex mutex;
71 : referrent(referrent), object(std::move(object)) {
72 assert(this->referrent &&
73 "cannot construct PyObjectRef with null referrent");
74 assert(this->
object &&
"cannot construct PyObjectRef with null object");
77 : referrent(other.referrent), object(std::move(other.object)) {
78 other.referrent =
nullptr;
79 assert(!other.object);
82 : referrent(other.referrent), object(other.object ) {}
88 return Py_REFCNT(
object.
ptr());
95 assert(referrent &&
object);
97 auto stolen = std::move(
object);
101 T *
get() {
return referrent; }
103 assert(referrent &&
object);
107 assert(referrent &&
object);
110 operator bool()
const {
return referrent && object; }
112 using NBTypedT = nanobind::typed<nanobind::object, T>;
116 nanobind::object object;
136 nanobind::object insertionPoint,
137 nanobind::object location)
138 : context(std::move(context)), insertionPoint(std::move(insertionPoint)),
139 location(std::move(location)), frameKind(frameKind) {}
157 static nanobind::object pushContext(nanobind::object context);
159 static nanobind::object pushInsertionPoint(nanobind::object insertionPoint);
161 static nanobind::object pushLocation(nanobind::object location);
162 static void popLocation(
PyLocation &location);
165 static std::vector<PyThreadContextEntry> &getStack();
168 static void push(FrameKind frameKind, nanobind::object context,
169 nanobind::object insertionPoint, nanobind::object location);
172 nanobind::object context;
174 nanobind::object insertionPoint;
176 nanobind::object location;
190 MlirLlvmThreadPool
get() {
return wrap(ownedThreadPool.get()); }
192 std::string _mlir_thread_pool_ptr()
const;
195 std::unique_ptr<llvm::ThreadPoolInterface> ownedThreadPool;
213 MlirContext
get() {
return context; }
220 nanobind::object getCapsule();
226 static nanobind::object createFromCapsule(nanobind::object capsule);
229 static size_t getLiveCount();
233 size_t getLiveModuleCount();
236 static nanobind::object contextEnter(nanobind::object context);
237 void contextExit(
const nanobind::object &excType,
238 const nanobind::object &excVal,
239 const nanobind::object &excTb);
243 nanobind::object attachDiagnosticHandler(nanobind::object callback);
259 static nanobind::ft_mutex live_contexts_mutex;
260 static LiveContextMap &getLiveContexts();
266 using LiveModuleMap =
268 LiveModuleMap liveModules;
270 bool emitErrorDiagnostics =
false;
280 :
public Defaulting<DefaultingPyMlirContext, PyMlirContext> {
294 assert(this->contextRef &&
295 "context object constructed with null context ref");
311 operator MlirLocation()
const {
return loc; }
312 MlirLocation
get()
const {
return loc; }
315 static nanobind::object contextEnter(nanobind::object location);
316 void contextExit(
const nanobind::object &excType,
317 const nanobind::object &excVal,
318 const nanobind::object &excTb);
321 nanobind::object getCapsule();
327 static PyLocation createFromCapsule(nanobind::object capsule);
364 nanobind::str getMessage();
365 nanobind::tuple getNotes();
384 std::optional<nanobind::tuple> materializedNotes;
420 const nanobind::object &excVal,
421 const nanobind::object &excTb) {
427 nanobind::object callback;
428 std::optional<MlirDiagnosticHandlerID> registeredID;
429 bool hadError =
false;
438 ctx->
get(), handler, this,
442 assert(errors.empty() &&
"unhandled captured errors");
445 std::vector<PyDiagnostic::DiagnosticInfo>
take() {
446 return std::move(errors);
452 std::vector<PyDiagnostic::DiagnosticInfo> errors;
467 MlirDialect
get() {
return dialect; }
480 MlirDialect getDialectForKey(
const std::string &key,
bool attrError);
488 PyDialect(nanobind::object descriptor) : descriptor(std::move(descriptor)) {}
493 nanobind::object descriptor;
509 : registry(other.registry) {
510 other.registry = {
nullptr};
513 operator MlirDialectRegistry()
const {
return registry; }
514 MlirDialectRegistry
get()
const {
return registry; }
516 nanobind::object getCapsule();
520 MlirDialectRegistry registry;
526 :
public Defaulting<DefaultingPyLocation, PyLocation> {
532 operator MlirLocation()
const {
return *
get(); }
549 MlirModule
get() {
return module; }
553 return PyModuleRef(
this, nanobind::borrow<nanobind::object>(handle));
560 nanobind::object getCapsule();
565 static nanobind::object createFromCapsule(nanobind::object capsule);
572 nanobind::handle handle;
583 void print(std::optional<int64_t> largeElementsLimit,
584 std::optional<int64_t> largeResourceLimit,
bool enableDebugInfo,
585 bool prettyDebugInfo,
bool printGenericOpForm,
bool useLocalScope,
586 bool useNameLocAsPrefix,
bool assumeVerified,
587 nanobind::object fileObject,
bool binary,
bool skipRegions);
588 void print(
PyAsmState &state, nanobind::object fileObject,
bool binary);
591 getAsm(
bool binary, std::optional<int64_t> largeElementsLimit,
592 std::optional<int64_t> largeResourceLimit,
bool enableDebugInfo,
593 bool prettyDebugInfo,
bool printGenericOpForm,
bool useLocalScope,
594 bool useNameLocAsPrefix,
bool assumeVerified,
bool skipRegions);
598 std::optional<int64_t> bytecodeVersion);
642 nanobind::object parentKeepAlive = nanobind::object());
648 nanobind::object parentKeepAlive = nanobind::object());
653 const std::string &sourceStr,
654 const std::string &sourceName);
658 void detachFromParent();
661 operator MlirOperation()
const {
return get(); }
662 MlirOperation
get()
const;
667 void setAttached(
const nanobind::object &parent = nanobind::object());
669 void checkValid()
const;
677 std::optional<PyOperationRef> getParentOperation();
680 nanobind::object getCapsule();
685 static nanobind::object createFromCapsule(
const nanobind::object &capsule);
688 static nanobind::object
689 create(std::string_view name, std::optional<std::vector<PyType *>> results,
691 std::optional<nanobind::dict> attributes,
692 std::optional<std::vector<PyBlock *>> successors,
int regions,
693 PyLocation &location,
const nanobind::object &ip,
bool inferType);
696 nanobind::object createOpView();
706 nanobind::object
clone(
const nanobind::object &ip);
712 MlirOperation operation,
713 nanobind::object parentKeepAlive);
715 MlirOperation operation;
716 nanobind::handle handle;
723 nanobind::object parentKeepAlive;
724 bool attached =
true;
738 PyOpView(
const nanobind::object &operationObject);
743 static nanobind::object
744 buildGeneric(std::string_view name, std::tuple<int, bool> opRegionSpec,
745 nanobind::object operandSegmentSpecObj,
746 nanobind::object resultSegmentSpecObj,
747 std::optional<nanobind::list> resultTypeList,
748 nanobind::list operandList,
749 std::optional<nanobind::dict> attributes,
750 std::optional<std::vector<PyBlock *>> successors,
751 std::optional<int> regions,
PyLocation &location,
752 const nanobind::object &maybeIp);
761 static nanobind::object constructDerived(
const nanobind::object &cls,
762 const nanobind::object &operation);
766 nanobind::object operationObject;
775 : parentOperation(std::move(parentOperation)), region(region) {
778 operator MlirRegion()
const {
return region; }
780 MlirRegion
get() {
return region; }
793 PyAsmState(MlirValue value,
bool useLocalScope);
800 MlirAsmState
get() {
return state; }
804 MlirOpPrintingFlags flags;
813 : parentOperation(std::move(parentOperation)), block(block) {
817 MlirBlock
get() {
return block; }
823 nanobind::object getCapsule();
856 static nanobind::object
contextEnter(nanobind::object insertionPoint);
858 const nanobind::object &excVal,
859 const nanobind::object &excTb);
868 : refOperation(std::move(refOperation)), block(std::move(block)) {}
870 std::optional<PyOperationRef> refOperation;
881 operator MlirType()
const {
return type; }
882 MlirType
get()
const {
return type; }
885 nanobind::object getCapsule();
891 static PyType createFromCapsule(nanobind::object capsule);
893 nanobind::typed<nanobind::object, PyType> maybeDownCast();
909 operator MlirTypeID()
const {
return typeID; }
910 MlirTypeID
get() {
return typeID; }
913 nanobind::object getCapsule();
916 static PyTypeID createFromCapsule(nanobind::object capsule);
927template <
typename DerivedTy,
typename BaseTy = PyType>
933 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, nanobind::is_generic());
961 cls.def(nanobind::init<PyType &>(), nanobind::keep_alive<0, 1>(),
962 nanobind::arg(
"cast_from_type"));
963 cls.def_prop_ro_static(
965 [](nanobind::object & ) {
966 if (DerivedTy::getTypeIdFunction)
967 return PyTypeID(DerivedTy::getTypeIdFunction());
968 throw nanobind::attribute_error(
969 (DerivedTy::pyClassName + ::llvm::Twine(
" has no typeid."))
973 nanobind::sig(
"def static_typeid(/) -> TypeID"));
974 cls.def_prop_ro(
"typeid", [](
PyType &self) {
975 return nanobind::cast<PyTypeID>(nanobind::cast(self).attr(
"typeid"));
977 cls.def(
"__repr__", [](
DerivedTy &self) {
979 printAccum.
parts.append(DerivedTy::pyClassName);
980 printAccum.
parts.append(
"(");
982 printAccum.
parts.append(
")");
983 return printAccum.
join();
986 if (DerivedTy::getTypeIdFunction) {
988 DerivedTy::getTypeIdFunction(),
989 nanobind::cast<nanobind::callable>(nanobind::cpp_function(
994 if (DerivedTy::name.length != 0) {
995 cls.def_prop_ro_static(
"type_name", [](nanobind::object & ) {
996 return nanobind::str(DerivedTy::name.data, DerivedTy::name.length);
1000 DerivedTy::bindDerived(cls);
1014 operator MlirAttribute()
const {
return attr; }
1015 MlirAttribute
get()
const {
return attr; }
1018 nanobind::object getCapsule();
1024 static PyAttribute createFromCapsule(
const nanobind::object &capsule);
1026 nanobind::typed<nanobind::object, PyAttribute> maybeDownCast();
1052 std::unique_ptr<std::string> ownedName;
1060template <
typename DerivedTy,
typename BaseTy = PyAttribute>
1066 using ClassTy = nanobind::class_<DerivedTy, BaseTy>;
1075 : BaseTy(std::move(contextRef), attr) {}
1080 if (!DerivedTy::isaFunction(orig)) {
1082 nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
1083 throw nanobind::value_error((::llvm::Twine(
"Cannot cast attribute to ") +
1084 DerivedTy::pyClassName +
" (from " +
1092 static void bind(nanobind::module_ &m, PyType_Slot *slots =
nullptr) {
1095 cls =
ClassTy(m, DerivedTy::pyClassName, nanobind::type_slots(slots),
1096 nanobind::is_generic());
1098 cls =
ClassTy(m, DerivedTy::pyClassName, nanobind::is_generic());
1100 cls.def(nanobind::init<PyAttribute &>(), nanobind::keep_alive<0, 1>(),
1101 nanobind::arg(
"cast_from_attr"));
1104 [](
PyAttribute &attr) -> nanobind::typed<nanobind::object, PyType> {
1108 cls.def_prop_ro_static(
1110 [](nanobind::object & ) ->
PyTypeID {
1111 if (DerivedTy::getTypeIdFunction)
1112 return PyTypeID(DerivedTy::getTypeIdFunction());
1113 throw nanobind::attribute_error(
1114 (DerivedTy::pyClassName + ::llvm::Twine(
" has no typeid."))
1118 nanobind::sig(
"def static_typeid(/) -> TypeID"));
1120 return nanobind::cast<PyTypeID>(nanobind::cast(self).attr(
"typeid"));
1122 cls.def(
"__repr__", [](
DerivedTy &self) {
1124 printAccum.
parts.append(DerivedTy::pyClassName);
1125 printAccum.
parts.append(
"(");
1128 printAccum.
parts.append(
")");
1129 return printAccum.
join();
1132 if (DerivedTy::getTypeIdFunction) {
1134 DerivedTy::getTypeIdFunction(),
1135 nanobind::cast<nanobind::callable>(
1142 if (DerivedTy::name.length != 0) {
1143 cls.def_prop_ro_static(
"attr_name", [](nanobind::object & ) {
1144 return nanobind::str(DerivedTy::name.data, DerivedTy::name.length);
1148 DerivedTy::bindDerived(cls);
1183 : parentOperation(std::move(parentOperation)), value(value) {}
1184 operator MlirValue()
const {
return value; }
1186 MlirValue
get() {
return value; }
1192 nanobind::object getCapsule();
1194 nanobind::typed<nanobind::object,
1195 std::variant<PyBlockArgument, PyOpResult, PyValue>>
1200 static PyValue createFromCapsule(nanobind::object capsule);
1213 operator MlirAffineExpr()
const {
return affineExpr; }
1214 MlirAffineExpr
get()
const {
return affineExpr; }
1217 nanobind::object getCapsule();
1223 static PyAffineExpr createFromCapsule(
const nanobind::object &capsule);
1231 nanobind::typed<nanobind::object, PyAffineExpr>
maybeDownCast();
1234 MlirAffineExpr affineExpr;
1242 operator MlirAffineMap()
const {
return affineMap; }
1243 MlirAffineMap
get()
const {
return affineMap; }
1246 nanobind::object getCapsule();
1252 static PyAffineMap createFromCapsule(
const nanobind::object &capsule);
1255 MlirAffineMap affineMap;
1263 operator MlirIntegerSet()
const {
return integerSet; }
1264 MlirIntegerSet
get()
const {
return integerSet; }
1267 nanobind::object getCapsule();
1272 static PyIntegerSet createFromCapsule(
const nanobind::object &capsule);
1275 MlirIntegerSet integerSet;
1289 nanobind::object dunderGetItem(
const std::string &name);
1296 void dunderDel(
const std::string &name);
1304 static void setSymbolName(
PyOperationBase &symbol,
const std::string &name);
1309 const std::string &visibility);
1313 static void replaceAllSymbolUses(
const std::string &oldSymbol,
1314 const std::string &newSymbol,
1318 static void walkSymbolTables(
PyOperationBase &from,
bool allSymUsesVisible,
1319 nanobind::object callback);
1322 operator MlirSymbolTable() {
return symbolTable; }
1326 MlirSymbolTable symbolTable;
1334 : message(message.str()), errorDiagnostics(std::move(errorDiagnostics)) {}
1359 const std::optional<nanobind::sequence> &pyArgLocs);
1363 static nanobind::callable
1366 nanobind::callable
func,
bool replace);
1368 static void bind(nanobind::module_ &m);
1378 : operation(std::move(operation)), nextIndex(nextIndex) {}
1382 nanobind::typed<nanobind::object, PyRegion> dunderNext();
1384 static void bind(nanobind::module_ &m);
1394 :
public Sliceable<PyRegionList, PyRegion> {
1421 : operation(std::move(operation)), next(next) {}
1425 nanobind::typed<nanobind::object, PyBlock> dunderNext();
1427 static void bind(nanobind::module_ &m);
1440 : operation(std::move(operation)), region(region) {}
1448 PyBlock appendBlock(
const nanobind::args &pyArgTypes,
1449 const std::optional<nanobind::sequence> &pyArgLocs);
1451 static void bind(nanobind::module_ &m);
1461 : parentOperation(std::move(parentOperation)), next(next) {}
1465 nanobind::typed<nanobind::object, PyOpView> dunderNext();
1467 static void bind(nanobind::module_ &m);
1481 : parentOperation(std::move(parentOperation)), block(block) {}
1487 nanobind::typed<nanobind::object, PyOpView> dunderGetItem(
intptr_t index);
1489 static void bind(nanobind::module_ &m);
1500 nanobind::typed<nanobind::object, PyOpView> getOwner()
const;
1502 size_t getOperandNumber()
const;
1504 static void bind(nanobind::module_ &m);
1507 MlirOpOperand opOperand;
1516 nanobind::typed<nanobind::object, PyOpOperand> dunderNext();
1518 static void bind(nanobind::module_ &m);
1521 MlirOpOperand opOperand;
1527template <
typename DerivedTy>
1534 using ClassTy = nanobind::class_<DerivedTy, PyValue>;
1542 :
PyValue(operationRef, value) {}
1549 if (!DerivedTy::isaFunction(orig.
get())) {
1551 nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
1552 throw nanobind::value_error((::llvm::Twine(
"Cannot cast value to ") +
1553 DerivedTy::pyClassName +
" (from " +
1562 static void bind(nanobind::module_ &m) {
1563 auto cls =
ClassTy(m, DerivedTy::pyClassName, nanobind::is_generic(),
1564 nanobind::sig((::llvm::Twine(
"class ") +
1565 DerivedTy::pyClassName +
"(Value[_T])")
1568 cls.def(nanobind::init<PyValue &>(), nanobind::keep_alive<0, 1>(),
1569 nanobind::arg(
"value"));
1572 [](
DerivedTy &self) -> nanobind::typed<nanobind::object, DerivedTy> {
1573 return self.maybeDownCast();
1575 cls.def(
"__str__", [](
PyValue &self) {
1577 printAccum.
parts.append(std::string(DerivedTy::pyClassName) +
"(");
1580 printAccum.
parts.append(
")");
1581 return printAccum.
join();
1584 if (DerivedTy::getTypeIdFunction) {
1586 DerivedTy::getTypeIdFunction(),
1587 nanobind::cast<nanobind::callable>(nanobind::cpp_function(
1592 DerivedTy::bindDerived(cls);
1614 :
public Sliceable<PyOpResultList, PyOpResult> {
1656 :
public Sliceable<PyBlockArgumentList, PyBlockArgument> {
1690 :
public Sliceable<PyOpOperandList, PyValue> {
1721 :
public Sliceable<PyOpSuccessors, PyBlock> {
1751 :
public Sliceable<PyBlockSuccessors, PyBlock> {
1782 :
public Sliceable<PyBlockPredecessors, PyBlock> {
1810 : operation(std::move(operation)) {}
1812 nanobind::typed<nanobind::object, PyAttribute>
1813 dunderGetItemNamed(
const std::string &name);
1817 nanobind::typed<nanobind::object, std::optional<PyAttribute>>
1818 get(
const std::string &key, nanobind::object defaultValue);
1820 void dunderSetItem(
const std::string &name,
const PyAttribute &attr);
1822 void dunderDelItem(
const std::string &name);
1826 bool dunderContains(
const std::string &name);
1829 forEachAttr(MlirOperation op,
1832 static void bind(nanobind::module_ &m);
1850 mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN::DefaultingPyMlirContext>
1852 mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN::DefaultingPyMlirContext> {
1856 mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN::DefaultingPyLocation>
1858 mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN::DefaultingPyLocation> {};
MLIR_FLOAT16_EXPORT bool operator==(const f16 &f1, const f16 &f2)
bool mlirValueIsABlockArgument(MlirValue value)
MlirType mlirAttributeGetType(MlirAttribute attribute)
bool mlirValueIsAOpResult(MlirValue value)
void mlirOpPrintingFlagsDestroy(MlirOpPrintingFlags flags)
void mlirTypePrint(MlirType type, MlirStringCallback callback, void *userData)
#define MLIR_PYTHON_MAYBE_DOWNCAST_ATTR
Attribute on MLIR Python objects that expose a function for downcasting the corresponding Python obje...
static LogicalResult nextIndex(ArrayRef< int64_t > shape, MutableArrayRef< int64_t > index)
Walks over the indices of the elements of a tensor of a given shape by updating index in place to the...
static std::string diag(const llvm::Value &value)
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
static sycl::context getDefaultContext()
A CRTP base class for pseudo-containers willing to support Python-type slicing access on top of index...
nanobind::class_< PyRegionList > ClassTy
Sliceable(intptr_t startIndex, intptr_t length, intptr_t step)
ReferrentTy * get() const
Defaulting()=default
Type casters require the type to be default constructible, but using such an instance is illegal.
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 constexpr const char kTypeDescription[]
static PyLocation & resolve()
Defaulting()=default
Type casters require the type to be default constructible, but using such an instance is illegal.
Used in function arguments when None should resolve to the current context manager set instance.
static constexpr const char kTypeDescription[]
static PyMlirContext & resolve()
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.
PyAffineExpr ceilDiv(const PyAffineExpr &other) const
PyAffineExpr floorDiv(const PyAffineExpr &other) const
PyAffineExpr add(const PyAffineExpr &other) const
MlirAffineExpr get() const
PyAffineExpr mod(const PyAffineExpr &other) const
PyAffineExpr(PyMlirContextRef contextRef, MlirAffineExpr affineExpr)
nanobind::typed< nanobind::object, PyAffineExpr > maybeDownCast()
PyAffineExpr mul(const PyAffineExpr &other) const
PyAffineMap(PyMlirContextRef contextRef, MlirAffineMap affineMap)
MlirAffineMap get() const
Wrapper around an MlirAsmState.
PyAsmState(MlirValue value, bool useLocalScope)
PyAsmState(const PyAsmState &other)=delete
PyAsmState(PyAsmState &other)=delete
Wrapper around the generic MlirAttribute.
PyAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
MlirAttribute get() const
Sliceable< PyBlockArgumentList, PyBlockArgument > SliceableT
PyBlockArgumentList(PyOperationRef operation, MlirBlock block, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
static constexpr const char * pyClassName
static void bindDerived(ClassTy &c)
Python wrapper for MlirBlockArgument.
static void bindDerived(ClassTy &c)
PyConcreteValue()=default
static constexpr IsAFunctionTy isaFunction
static constexpr const char * pyClassName
PyBlockIterator & dunderIter()
PyBlockIterator(PyOperationRef operation, MlirBlock next)
PyBlockList(PyOperationRef operation, MlirRegion region)
PyBlockPredecessors(PyBlock block, PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
static constexpr const char * pyClassName
PyBlockSuccessors(PyBlock block, PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
static constexpr const char * pyClassName
Wrapper around an MlirBlock.
PyOperationRef & getParentOperation()
PyBlock(PyOperationRef parentOperation, MlirBlock block)
static constexpr GetTypeIDFunctionTy getTypeIdFunction
static void bindDerived(ClassTy &m)
Implemented by derived classes to add methods to the Python subclass.
PyConcreteAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
static void bind(nanobind::module_ &m, PyType_Slot *slots=nullptr)
nanobind::class_< DerivedTy, BaseTy > ClassTy
PyConcreteAttribute(PyAttribute &orig)
PyConcreteAttribute()=default
static MlirAttribute castFrom(PyAttribute &orig)
bool(*)(MlirAttribute) IsAFunctionTy
MlirTypeID(*)() GetTypeIDFunctionTy
static const MlirStringRef name
nanobind::class_< DerivedTy, BaseTy > ClassTy
static constexpr GetTypeIDFunctionTy getTypeIdFunction
static void bind(nanobind::module_ &m)
MlirTypeID(*)() GetTypeIDFunctionTy
PyConcreteType(PyMlirContextRef contextRef, MlirType t)
PyConcreteType(PyType &orig)
static const MlirStringRef name
static MlirType castFrom(PyType &orig)
bool(*)(MlirType) IsAFunctionTy
static void bindDerived(ClassTy &m)
Implemented by derived classes to add methods to the Python subclass.
PyConcreteValue(PyOperationRef operationRef, MlirValue value)
static constexpr GetTypeIDFunctionTy getTypeIdFunction
MlirTypeID(*)() GetTypeIDFunctionTy
PyConcreteValue(PyValue &orig)
PyConcreteValue()=default
static void bind(nanobind::module_ &m)
Binds the Python module objects to functions of this class.
nanobind::class_< DerivedTy, PyValue > ClassTy
bool(*)(MlirValue) IsAFunctionTy
static MlirValue castFrom(PyValue &orig)
Attempts to cast the original value to the derived type and throws on type mismatches.
static void bindDerived(ClassTy &m)
Implemented by derived classes to add methods to the Python subclass.
Represents a diagnostic handler attached to the context.
void detach()
Detaches the handler. Does nothing if not attached.
nanobind::object contextEnter()
PyDiagnosticHandler(MlirContext context, nanobind::object callback)
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
friend class PyMlirContext
Python class mirroring the C MlirDiagnostic struct.
PyDiagnostic(MlirDiagnostic diagnostic)
PyDialectDescriptor(PyMlirContextRef contextRef, MlirDialect dialect)
Wrapper around an MlirDialectRegistry.
PyDialectRegistry(PyDialectRegistry &&other) noexcept
MlirDialectRegistry get() const
PyDialectRegistry(MlirDialectRegistry registry)
PyDialectRegistry(PyDialectRegistry &)=delete
nanobind::object getDescriptor()
PyDialect(nanobind::object descriptor)
PyDialects(PyMlirContextRef contextRef)
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.
void insert(PyOperationBase &operationBase)
Inserts an operation.
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
static PyInsertionPoint atBlockTerminator(PyBlock &block)
Shortcut to create an insertion point before the block terminator.
static PyInsertionPoint after(PyOperationBase &op)
Shortcut to create an insertion point to the node after the specified operation.
std::optional< PyOperationRef > & getRefOperation()
static PyInsertionPoint atBlockBegin(PyBlock &block)
Shortcut to create an insertion point at the beginning of the block.
PyInsertionPoint(const PyBlock &block)
Creates an insertion point positioned after the last operation in the block, but still inside the blo...
static nanobind::object contextEnter(nanobind::object insertionPoint)
Enter and exit the context manager.
MlirIntegerSet get() const
PyIntegerSet(PyMlirContextRef contextRef, MlirIntegerSet integerSet)
Wrapper around an MlirLocation.
PyLocation(PyMlirContextRef contextRef, MlirLocation loc)
static PyMlirContextRef forContext(MlirContext context)
Returns a context reference for the singleton PyMlirContext wrapper for the given context.
PyMlirContext(PyMlirContext &&)=delete
MlirContext get()
Accesses the underlying MlirContext.
PyMlirContext(const PyMlirContext &)=delete
bool getEmitErrorDiagnostics()
void setEmitErrorDiagnostics(bool value)
Controls whether error diagnostics should be propagated to diagnostic handlers, instead of being capt...
PyModule(PyModule &)=delete
PyModuleRef getRef()
Gets a strong reference to this module.
MlirModule get()
Gets the backing MlirModule.
static PyModuleRef forModule(MlirModule module)
Returns a PyModule reference for the given MlirModule.
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
PyObjectRef(PyObjectRef &&other) noexcept
nanobind::object releaseObject()
Releases the object held by this instance, returning it.
PyObjectRef(T *referrent, nanobind::object object)
nanobind::object getObject()
PyObjectRef(const PyObjectRef &other)
PyOpAttributeMap(PyOperationRef operation)
PyOpOperandIterator(MlirOpOperand opOperand)
PyOpOperandIterator & dunderIter()
static constexpr const char * pyClassName
Sliceable< PyOpOperandList, PyValue > SliceableT
static void bindDerived(ClassTy &c)
PyOpOperandList(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
void dunderSetItem(intptr_t index, PyValue value)
PyOpOperand(MlirOpOperand opOperand)
A list of operation results.
static void bindDerived(ClassTy &c)
Sliceable< PyOpResultList, PyOpResult > SliceableT
PyOpResultList(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
PyOperationRef & getOperation()
static constexpr const char * pyClassName
Python wrapper for MlirOpResult.
static constexpr const char * pyClassName
static void bindDerived(ClassTy &c)
PyConcreteValue()=default
static constexpr IsAFunctionTy isaFunction
static void bindDerived(ClassTy &c)
static constexpr const char * pyClassName
PyOpSuccessors(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
void dunderSetItem(intptr_t index, PyBlock block)
A PyOpView is equivalent to the C++ "Op" wrappers: these are the basis for providing more instance-sp...
PyOpView(const nanobind::object &operationObject)
PyOperation & getOperation() override
Each must provide access to the raw Operation.
nanobind::object getOperationObject()
Base class for PyOperation and PyOpView which exposes the primary, user visible methods for manipulat...
bool isBeforeInBlock(PyOperationBase &other)
Given an operation 'other' that is within the same parent block, return whether the current 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)
virtual ~PyOperationBase()=default
void writeBytecode(const nanobind::object &fileObject, std::optional< int64_t > bytecodeVersion)
bool verify()
Verify the operation.
virtual PyOperation & getOperation()=0
Each must provide access to the raw Operation.
void moveAfter(PyOperationBase &other)
Moves the operation before or after the other operation.
void moveBefore(PyOperationBase &other)
void walk(std::function< PyWalkResult(MlirOperation)> callback, PyWalkOrder walkOrder)
PyOperationIterator(PyOperationRef parentOperation, MlirOperation next)
PyOperationIterator & dunderIter()
PyOperationList(PyOperationRef parentOperation, MlirBlock block)
MlirOperation get() const
void setInvalid()
Invalidate the operation.
friend class PyOperationBase
PyOperation & getOperation() override
Each must provide access to the raw Operation.
friend class PySymbolTable
PyOperation(PyMlirContextRef contextRef, MlirOperation operation)
PyRegionIterator & dunderIter()
PyRegionIterator(PyOperationRef operation, int nextIndex)
PyRegionIterator dunderIter()
static constexpr const char * pyClassName
PyRegionList(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
static void bindDerived(ClassTy &c)
Wrapper around an MlirRegion.
PyOperationRef & getParentOperation()
PyRegion(PyOperationRef parentOperation, MlirRegion region)
static constexpr const char * pyClassName
static void bindDerived(ClassTy &c)
static constexpr IsAFunctionTy isaFunction
static constexpr GetTypeIDFunctionTy getTypeIdFunction
PyConcreteAttribute()=default
static const MlirStringRef name
Bindings for MLIR symbol tables.
PySymbolTable(PyOperationBase &operation)
Constructs a symbol table for the given operation.
~PySymbolTable()
Destroys the symbol table.
Tracks an entry in the thread context stack.
PyThreadContextEntry(FrameKind frameKind, nanobind::object context, nanobind::object insertionPoint, nanobind::object location)
int getMaxConcurrency() const
PyThreadPool(PyThreadPool &&)=delete
PyThreadPool(const PyThreadPool &)=delete
A TypeID provides an efficient and unique identifier for a specific C++ type.
PyTypeID(MlirTypeID typeID)
Wrapper around the generic MlirType.
PyType(PyMlirContextRef contextRef, MlirType type)
nanobind::typed< nanobind::object, PyType > maybeDownCast()
virtual ~PyValue()=default
PyOperationRef & getParentOperation()
PyValue(PyOperationRef parentOperation, MlirValue value)
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.
MLIR_CAPI_EXPORTED MlirStringRef mlirStringAttrGetName(void)
MLIR_CAPI_EXPORTED void mlirDialectRegistryDestroy(MlirDialectRegistry registry)
Takes a dialect registry owned by the caller and destroys it.
MLIR_CAPI_EXPORTED void mlirAttributePrint(MlirAttribute attr, MlirStringCallback callback, void *userData)
Prints a location by sending chunks of the string representation and forwarding userData to callback`...
@ MlirWalkResultInterrupt
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 MlirDialectRegistry mlirDialectRegistryCreate(void)
Creates a dialect registry and transfers its ownership to the caller.
MLIR_CAPI_EXPORTED void mlirValuePrint(MlirValue value, MlirStringCallback callback, void *userData)
Prints a block by sending chunks of the string representation and forwarding userData to callback`.
static MlirStringRef mlirStringRefCreate(const char *str, size_t length)
Constructs a string reference from the pointer and length.
#define MLIR_PYTHON_API_EXPORTED
MLIR_PYTHON_API_EXPORTED MlirValue getUniqueResult(MlirOperation operation)
MLIR_PYTHON_API_EXPORTED void populateRoot(nanobind::module_ &m)
PyObjectRef< PyMlirContext > PyMlirContextRef
Wrapper around MlirContext.
PyObjectRef< PyOperation > PyOperationRef
MlirStringRef toMlirStringRef(const std::string &s)
PyObjectRef< PyModule > PyModuleRef
MlirBlock MLIR_PYTHON_API_EXPORTED createBlock(const nanobind::sequence &pyArgTypes, const std::optional< nanobind::sequence > &pyArgLocs)
Create a block, using the current location context if no locations are specified.
PyWalkOrder
Traversal order for operation walk.
MLIR_PYTHON_API_EXPORTED void populateIRCore(nanobind::module_ &m)
Include the generated interface declarations.
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
An opaque reference to a diagnostic, always owned by the diagnostics engine (context).
A logical result value, essentially a boolean with named states.
A pointer to a sized fragment of a string, not necessarily null-terminated.
Accumulates into a python string from a method that accepts an MlirStringCallback.
MlirStringCallback getCallback()
MLIRError(::llvm::Twine message, std::vector< PyDiagnostic::DiagnosticInfo > &&errorDiagnostics={})
std::vector< PyDiagnostic::DiagnosticInfo > errorDiagnostics
static bool dunderContains(const std::string &attributeKind)
static nanobind::callable dunderGetItemNamed(const std::string &attributeKind)
static void bind(nanobind::module_ &m)
static void dunderSetItemNamed(const std::string &attributeKind, nanobind::callable func, bool replace)
Materialized diagnostic information.
std::vector< DiagnosticInfo > notes
PyDiagnosticSeverity severity
Wrapper for the global LLVM debugging flag.
static void set(nanobind::object &o, bool enable)
static bool get(const nanobind::object &)
static void bind(nanobind::module_ &m)
std::vector< PyDiagnostic::DiagnosticInfo > take()
ErrorCapture(PyMlirContextRef ctx)