9#ifndef MLIR_BINDINGS_PYTHON_IRCORE_H
10#define MLIR_BINDINGS_PYTHON_IRCORE_H
56 static void set(nanobind::object &o,
bool enable);
57 static bool get(
const nanobind::object &);
58 static void bind(nanobind::module_ &m);
61 static nanobind::ft_mutex mutex;
70 : referrent(referrent), object(std::move(object)) {
71 assert(this->referrent &&
72 "cannot construct PyObjectRef with null referrent");
73 assert(this->
object &&
"cannot construct PyObjectRef with null object");
76 : referrent(other.referrent), object(std::move(other.object)) {
77 other.referrent =
nullptr;
78 assert(!other.object);
81 : referrent(other.referrent), object(other.object ) {}
83 referrent = other.referrent;
84 object = other.object;
88 referrent = other.referrent;
89 object = std::move(other.object);
90 other.referrent =
nullptr;
91 assert(!other.object);
99 return Py_REFCNT(
object.
ptr());
106 assert(referrent &&
object);
108 auto stolen = std::move(
object);
112 T *
get() {
return referrent; }
114 assert(referrent &&
object);
118 assert(referrent &&
object);
121 operator bool()
const {
return referrent && object; }
123 using NBTypedT = nanobind::typed<nanobind::object, T>;
127 nanobind::object object;
147 nanobind::object insertionPoint,
148 nanobind::object location)
149 : context(std::move(context)), insertionPoint(std::move(insertionPoint)),
150 location(std::move(location)), frameKind(frameKind) {}
168 static nanobind::object pushContext(nanobind::object context);
170 static nanobind::object pushInsertionPoint(nanobind::object insertionPoint);
172 static nanobind::object pushLocation(nanobind::object location);
173 static void popLocation(
PyLocation &location);
176 static std::vector<PyThreadContextEntry> &getStack();
179 static void push(FrameKind frameKind, nanobind::object context,
180 nanobind::object insertionPoint, nanobind::object location);
183 nanobind::object context;
185 nanobind::object insertionPoint;
187 nanobind::object location;
202 MlirLlvmThreadPool
get() {
return threadPool; }
204 std::string _mlir_thread_pool_ptr()
const;
207 MlirLlvmThreadPool threadPool;
245 MlirContext
get() {
return context; }
252 nanobind::object getCapsule();
258 static nanobind::object createFromCapsule(nanobind::object capsule);
261 static size_t getLiveCount();
265 size_t getLiveModuleCount();
268 static nanobind::object contextEnter(nanobind::object context);
269 void contextExit(
const nanobind::object &excType,
270 const nanobind::object &excVal,
271 const nanobind::object &excTb);
275 nanobind::object attachDiagnosticHandler(nanobind::object callback);
282 const std::optional<std::string> &outputFile,
284 const std::string &passedFilter,
285 const std::string &missedFilter,
286 const std::string &analysisFilter,
287 const std::string &failedFilter, nanobind::object callback,
288 std::optional<bool> printAsEmitRemarks);
290 void finalizeRemarks();
292 bool getRemarksEnabled();
295 static bool isLiveContext(MlirContext context);
310 using LiveContextMap = std::unordered_map<void *, PyMlirContext *>;
311 static nanobind::ft_mutex live_contexts_mutex;
312 static LiveContextMap &getLiveContexts();
318 using LiveModuleMap =
319 std::unordered_map<const void *, std::pair<nanobind::handle, PyModule *>>;
320 LiveModuleMap liveModules;
322 bool emitErrorDiagnostics =
false;
332 :
public Defaulting<DefaultingPyMlirContext, PyMlirContext> {
346 assert(this->contextRef &&
347 "context object constructed with null context ref");
363 operator MlirLocation()
const {
return loc; }
364 MlirLocation
get()
const {
return loc; }
367 static nanobind::object contextEnter(nanobind::object location);
368 void contextExit(
const nanobind::object &excType,
369 const nanobind::object &excVal,
370 const nanobind::object &excTb);
373 nanobind::object getCapsule();
379 static PyLocation createFromCapsule(nanobind::object capsule);
383 nanobind::typed<nanobind::object, PyLocation> maybeDownCast();
411 MlirOperationEquivalenceFlags> {
412 None = MLIR_OPERATION_EQUIVALENCE_NONE,
429 nanobind::typed<nanobind::object, PyLocation> getLocation();
430 nanobind::str getMessage();
431 nanobind::typed<nanobind::tuple, PyDiagnostic> getNotes();
450 std::optional<nanobind::tuple> materializedNotes;
463 nanobind::str getRemarkName()
const;
464 nanobind::str getCategoryName()
const;
465 nanobind::str getFullCategoryName()
const;
466 nanobind::str getFunctionName()
const;
467 nanobind::typed<nanobind::object, PyLocation> getLocation()
const;
468 uint64_t getId()
const;
470 nanobind::list getArgs()
const;
472 nanobind::str getMessage()
const;
475 void checkValid()
const;
512 const nanobind::object &excVal,
513 const nanobind::object &excTb) {
519 nanobind::object callback;
520 std::optional<MlirDiagnosticHandlerID> registeredID;
521 bool hadError =
false;
530 ctx->
get(), handler, this,
534 assert(errors.empty() &&
"unhandled captured errors");
537 std::vector<PyDiagnostic::DiagnosticInfo>
take() {
538 return std::move(errors);
544 std::vector<PyDiagnostic::DiagnosticInfo> errors;
559 MlirDialect
get() {
return dialect; }
572 MlirDialect getDialectForKey(
const std::string &key,
bool attrError);
580 PyDialect(nanobind::object descriptor) : descriptor(std::move(descriptor)) {}
585 nanobind::object descriptor;
601 : registry(other.registry) {
602 other.registry = {
nullptr};
605 operator MlirDialectRegistry()
const {
return registry; }
606 MlirDialectRegistry
get()
const {
return registry; }
608 nanobind::object getCapsule();
612 MlirDialectRegistry registry;
618 :
public Defaulting<DefaultingPyLocation, PyLocation> {
624 operator MlirLocation()
const {
return *
get(); }
641 MlirModule
get() {
return module; }
645 return PyModuleRef(
this, nanobind::borrow<nanobind::object>(handle));
652 nanobind::object getCapsule();
657 static nanobind::object createFromCapsule(nanobind::object capsule);
664 nanobind::handle handle;
675 void print(std::optional<int64_t> largeElementsLimit,
676 std::optional<int64_t> largeResourceLimit,
bool enableDebugInfo,
677 bool prettyDebugInfo,
bool printGenericOpForm,
bool useLocalScope,
678 bool useNameLocAsPrefix,
bool assumeVerified,
679 nanobind::object fileObject,
bool binary,
bool skipRegions);
680 void print(
PyAsmState &state, nanobind::object fileObject,
bool binary);
683 getAsm(
bool binary, std::optional<int64_t> largeElementsLimit,
684 std::optional<int64_t> largeResourceLimit,
bool enableDebugInfo,
685 bool prettyDebugInfo,
bool printGenericOpForm,
bool useLocalScope,
686 bool useNameLocAsPrefix,
bool assumeVerified,
bool skipRegions);
690 std::optional<int64_t> bytecodeVersion);
734 nanobind::object parentKeepAlive = nanobind::object());
740 nanobind::object parentKeepAlive = nanobind::object());
745 const std::string &sourceStr,
746 const std::string &sourceName);
750 void detachFromParent();
753 operator MlirOperation()
const {
return get(); }
754 MlirOperation
get()
const;
759 void setAttached(
const nanobind::object &parent = nanobind::object());
761 void checkValid()
const;
769 std::optional<PyOperationRef> getParentOperation();
772 nanobind::object getCapsule();
777 static nanobind::object createFromCapsule(
const nanobind::object &capsule);
780 static nanobind::object
781 create(std::string_view name, std::optional<std::vector<PyType *>> results,
782 const MlirValue *operands,
size_t numOperands,
783 std::optional<nanobind::dict> attributes,
784 std::optional<std::vector<PyBlock *>> successors,
int regions,
785 PyLocation &location,
const nanobind::object &ip,
bool inferType);
788 nanobind::object createOpView();
798 nanobind::object
clone(
const nanobind::object &ip);
804 MlirOperation operation,
805 nanobind::object parentKeepAlive);
807 MlirOperation operation;
808 nanobind::handle handle;
815 nanobind::object parentKeepAlive;
816 bool attached =
true;
830 PyOpView(
const nanobind::object &operationObject);
835 static nanobind::typed<nanobind::object, PyOperation>
836 buildGeneric(std::string_view name, std::tuple<int, bool> opRegionSpec,
837 nanobind::object operandSegmentSpecObj,
838 nanobind::object resultSegmentSpecObj,
839 std::optional<nanobind::sequence> resultTypeList,
840 nanobind::sequence operandList,
841 std::optional<nanobind::dict> attributes,
842 std::optional<std::vector<PyBlock *>> successors,
843 std::optional<int> regions,
PyLocation &location,
844 const nanobind::object &maybeIp);
853 static nanobind::object constructDerived(
const nanobind::object &cls,
854 const nanobind::object &operation);
858 nanobind::object operationObject;
867 : parentOperation(std::move(parentOperation)), region(region) {
870 operator MlirRegion()
const {
return region; }
872 MlirRegion
get() {
return region; }
885 PyAsmState(MlirValue value,
bool useLocalScope);
892 MlirAsmState
get() {
return state; }
896 MlirOpPrintingFlags flags;
905 : parentOperation(std::move(parentOperation)), block(block) {
909 MlirBlock
get() {
return block; }
915 nanobind::object getCapsule();
948 static nanobind::object
contextEnter(nanobind::object insertionPoint);
950 const nanobind::object &excVal,
951 const nanobind::object &excTb);
960 : refOperation(std::move(refOperation)), block(std::move(block)) {}
962 std::optional<PyOperationRef> refOperation;
973 operator MlirType()
const {
return type; }
974 MlirType
get()
const {
return type; }
977 nanobind::object getCapsule();
983 static PyType createFromCapsule(nanobind::object capsule);
985 nanobind::typed<nanobind::object, PyType> maybeDownCast();
1001 operator MlirTypeID()
const {
return typeID; }
1002 MlirTypeID
get() {
return typeID; }
1005 nanobind::object getCapsule();
1008 static PyTypeID createFromCapsule(nanobind::object capsule);
1019template <
typename DerivedTy,
typename BaseTy = PyType>
1025 using ClassTy = nanobind::class_<DerivedTy, BaseTy>;
1034 : BaseTy(std::move(contextRef), t) {}
1039 if (!DerivedTy::isaFunction(orig)) {
1041 nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
1042 throw nanobind::value_error((std::string(
"Cannot cast type to ") +
1043 DerivedTy::pyClassName +
" (from " +
1050 static void bind(nanobind::module_ &m) {
1051 auto cls =
ClassTy(m, DerivedTy::pyClassName, nanobind::is_generic());
1052 cls.def(nanobind::init<PyType &>(), nanobind::keep_alive<0, 1>(),
1053 nanobind::arg(
"cast_from_type"));
1054 cls.def_prop_ro_static(
"static_typeid", [](nanobind::object & ) {
1055 if (DerivedTy::getTypeIdFunction)
1056 return PyTypeID(DerivedTy::getTypeIdFunction());
1057 throw nanobind::attribute_error(
1058 (DerivedTy::pyClassName + std::string(
" has no typeid.")).c_str());
1060 cls.def_prop_ro(
"typeid", [](
PyType &self) {
1061 return nanobind::cast<PyTypeID>(nanobind::cast(self).attr(
"typeid"));
1063 cls.def(
"__repr__", [](
DerivedTy &self) {
1065 printAccum.
parts.append(DerivedTy::pyClassName);
1066 printAccum.
parts.append(
"(");
1068 printAccum.
parts.append(
")");
1069 return printAccum.
join();
1072 if (DerivedTy::getTypeIdFunction) {
1074 DerivedTy::getTypeIdFunction(),
1075 nanobind::cast<nanobind::callable>(nanobind::cpp_function(
1080 if (DerivedTy::name.length != 0) {
1081 cls.def_prop_ro_static(
"type_name", [](nanobind::object & ) {
1082 return nanobind::str(DerivedTy::name.data, DerivedTy::name.length);
1086 DerivedTy::bindDerived(cls);
1100 operator MlirAttribute()
const {
return attr; }
1101 MlirAttribute
get()
const {
return attr; }
1104 nanobind::object getCapsule();
1110 static PyAttribute createFromCapsule(
const nanobind::object &capsule);
1112 nanobind::typed<nanobind::object, PyAttribute> maybeDownCast();
1138 std::unique_ptr<std::string> ownedName;
1146template <
typename DerivedTy,
typename BaseTy = PyAttribute>
1152 using ClassTy = nanobind::class_<DerivedTy, BaseTy>;
1161 : BaseTy(std::move(contextRef), attr) {}
1166 if (!DerivedTy::isaFunction(orig)) {
1168 nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
1169 throw nanobind::value_error((std::string(
"Cannot cast attribute to ") +
1170 DerivedTy::pyClassName +
" (from " +
1177 static void bind(nanobind::module_ &m, PyType_Slot *slots =
nullptr) {
1180 cls =
ClassTy(m, DerivedTy::pyClassName, nanobind::type_slots(slots),
1181 nanobind::is_generic());
1183 cls =
ClassTy(m, DerivedTy::pyClassName, nanobind::is_generic());
1185 cls.def(nanobind::init<PyAttribute &>(), nanobind::keep_alive<0, 1>(),
1186 nanobind::arg(
"cast_from_attr"));
1189 [](
PyAttribute &attr) -> nanobind::typed<nanobind::object, PyType> {
1193 cls.def_prop_ro_static(
"static_typeid", [](nanobind::object & ) {
1194 if (DerivedTy::getTypeIdFunction)
1195 return PyTypeID(DerivedTy::getTypeIdFunction());
1196 throw nanobind::attribute_error(
1197 (DerivedTy::pyClassName + std::string(
" has no typeid.")).c_str());
1200 return nanobind::cast<PyTypeID>(nanobind::cast(self).attr(
"typeid"));
1202 cls.def(
"__repr__", [](
DerivedTy &self) {
1204 printAccum.
parts.append(DerivedTy::pyClassName);
1205 printAccum.
parts.append(
"(");
1208 printAccum.
parts.append(
")");
1209 return printAccum.
join();
1212 if (DerivedTy::getTypeIdFunction) {
1214 DerivedTy::getTypeIdFunction(),
1215 nanobind::cast<nanobind::callable>(
1222 if (DerivedTy::name.length != 0) {
1223 cls.def_prop_ro_static(
"attr_name", [](nanobind::object & ) {
1224 return nanobind::str(DerivedTy::name.data, DerivedTy::name.length);
1228 DerivedTy::bindDerived(cls);
1250template <
typename DerivedTy,
typename BaseTy = PyLocation>
1256 using ClassTy = nanobind::class_<DerivedTy, BaseTy>;
1264 : BaseTy(std::move(contextRef), loc) {}
1269 if (!DerivedTy::isaFunction(orig.
get())) {
1271 nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
1272 throw nanobind::value_error((std::string(
"Cannot cast location to ") +
1273 DerivedTy::pyClassName +
" (from " +
1280 static void bind(nanobind::module_ &m) {
1281 ClassTy cls(m, DerivedTy::pyClassName, nanobind::is_generic());
1282 cls.def(nanobind::init<PyLocation &>(), nanobind::keep_alive<0, 1>(),
1283 nanobind::arg(
"cast_from_loc"));
1284 cls.def_prop_ro_static(
"static_typeid", [](nanobind::object & ) {
1285 if (DerivedTy::getTypeIdFunction)
1286 return PyTypeID(DerivedTy::getTypeIdFunction());
1287 throw nanobind::attribute_error(
1288 (DerivedTy::pyClassName + std::string(
" has no typeid.")).c_str());
1290 cls.def(
"__repr__", [](
DerivedTy &self) {
1292 printAccum.
parts.append(DerivedTy::pyClassName);
1293 printAccum.
parts.append(
"(");
1296 printAccum.
parts.append(
")");
1297 return printAccum.
join();
1299 if (DerivedTy::getTypeIdFunction) {
1301 DerivedTy::getTypeIdFunction(),
1302 nanobind::cast<nanobind::callable>(nanobind::cpp_function(
1306 DerivedTy::bindDerived(cls);
1388 : parentOperation(std::move(parentOperation)), value(value) {}
1389 operator MlirValue()
const {
return value; }
1391 MlirValue
get() {
return value; }
1397 nanobind::object getCapsule();
1399 nanobind::typed<nanobind::object,
1400 std::variant<PyBlockArgument, PyOpResult, PyValue>>
1405 static PyValue createFromCapsule(nanobind::object capsule);
1418 operator MlirAffineExpr()
const {
return affineExpr; }
1419 MlirAffineExpr
get()
const {
return affineExpr; }
1422 nanobind::object getCapsule();
1428 static PyAffineExpr createFromCapsule(
const nanobind::object &capsule);
1436 nanobind::typed<nanobind::object, PyAffineExpr>
maybeDownCast();
1439 MlirAffineExpr affineExpr;
1447 operator MlirAffineMap()
const {
return affineMap; }
1448 MlirAffineMap
get()
const {
return affineMap; }
1451 nanobind::object getCapsule();
1457 static PyAffineMap createFromCapsule(
const nanobind::object &capsule);
1460 MlirAffineMap affineMap;
1468 operator MlirIntegerSet()
const {
return integerSet; }
1469 MlirIntegerSet
get()
const {
return integerSet; }
1472 nanobind::object getCapsule();
1477 static PyIntegerSet createFromCapsule(
const nanobind::object &capsule);
1480 MlirIntegerSet integerSet;
1494 nanobind::object dunderGetItem(
const std::string &name);
1501 void dunderDel(
const std::string &name);
1509 static void setSymbolName(
PyOperationBase &symbol,
const std::string &name);
1514 const std::string &visibility);
1518 static void replaceAllSymbolUses(
const std::string &oldSymbol,
1519 const std::string &newSymbol,
1523 static void walkSymbolTables(
PyOperationBase &from,
bool allSymUsesVisible,
1524 nanobind::object callback);
1527 operator MlirSymbolTable() {
return symbolTable; }
1531 MlirSymbolTable symbolTable;
1539 : message(std::move(message)),
1540 errorDiagnostics(std::move(errorDiagnostics)) {}
1541 const char *
what() const noexcept
override {
return message.c_str(); }
1544 static void bind(nanobind::module_ &m);
1569createBlock(
const nanobind::typed<nanobind::sequence, PyType> &pyArgTypes,
1570 const std::optional<nanobind::typed<nanobind::sequence, PyLocation>>
1575 static nanobind::callable
1578 nanobind::callable
func,
bool replace,
1579 bool allow_existing);
1581 static void bind(nanobind::module_ &m);
1591 :
public Sliceable<PyRegionList, PyRegion> {
1614 : operation(std::move(operation)), next(next) {}
1618 nanobind::typed<nanobind::object, PyBlock> dunderNext();
1620 static void bind(nanobind::module_ &m);
1633 : operation(std::move(operation)), region(region) {}
1641 PyBlock appendBlock(
const nanobind::args &pyArgTypes,
1642 const std::optional<nanobind::sequence> &pyArgLocs);
1644 static void bind(nanobind::module_ &m);
1654 : parentOperation(std::move(parentOperation)), next(next) {}
1658 nanobind::typed<nanobind::object, PyOpView> dunderNext();
1660 static void bind(nanobind::module_ &m);
1674 : parentOperation(std::move(parentOperation)), block(block) {}
1680 nanobind::typed<nanobind::object, PyOpView> dunderGetItem(
intptr_t index);
1682 static void bind(nanobind::module_ &m);
1692 operator MlirOpOperand()
const {
return opOperand; }
1694 nanobind::typed<nanobind::object, PyOpView> getOwner()
const;
1696 size_t getOperandNumber()
const;
1698 static void bind(nanobind::module_ &m);
1701 MlirOpOperand opOperand;
1710 nanobind::typed<nanobind::object, PyOpOperand> dunderNext();
1712 static void bind(nanobind::module_ &m);
1715 MlirOpOperand opOperand;
1721template <
typename DerivedTy>
1728 using ClassTy = nanobind::class_<DerivedTy, PyValue>;
1736 :
PyValue(operationRef, value) {}
1743 if (!DerivedTy::isaFunction(orig.
get())) {
1745 nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
1746 throw nanobind::value_error((std::string(
"Cannot cast value to ") +
1747 DerivedTy::pyClassName +
" (from " +
1755 static void bind(nanobind::module_ &m) {
1756 auto cls =
ClassTy(m, DerivedTy::pyClassName, nanobind::is_generic(),
1757 nanobind::sig((std::string(
"class ") +
1758 DerivedTy::pyClassName +
"(Value[_T])")
1760 cls.def(nanobind::init<PyValue &>(), nanobind::keep_alive<0, 1>(),
1761 nanobind::arg(
"value"));
1764 [](
DerivedTy &self) -> nanobind::typed<nanobind::object, DerivedTy> {
1765 return self.maybeDownCast();
1767 cls.def(
"__str__", [](
PyValue &self) {
1769 printAccum.
parts.append(std::string(DerivedTy::pyClassName) +
"(");
1772 printAccum.
parts.append(
")");
1773 return printAccum.
join();
1776 if (DerivedTy::getTypeIdFunction) {
1778 DerivedTy::getTypeIdFunction(),
1779 nanobind::cast<nanobind::callable>(nanobind::cpp_function(
1784 DerivedTy::bindDerived(cls);
1806 :
public Sliceable<PyOpResultList, PyOpResult> {
1809 static constexpr std::array<const char *, 1>
typeParams = {
"_T"};
1849 :
public Sliceable<PyBlockArgumentList, PyBlockArgument> {
1883 :
public Sliceable<PyOpOperandList, PyValue> {
1886 static constexpr std::array<const char *, 1>
typeParams = {
"_T"};
1915 :
public Sliceable<PyOpSuccessors, PyBlock> {
1945 :
public Sliceable<PyBlockSuccessors, PyBlock> {
1976 :
public Sliceable<PyBlockPredecessors, PyBlock> {
2004 : operation(std::move(operation)) {}
2006 nanobind::typed<nanobind::object, PyAttribute>
2007 dunderGetItemNamed(
const std::string &name);
2011 nanobind::typed<nanobind::object, std::optional<PyAttribute>>
2012 get(
const std::string &key, nanobind::object defaultValue);
2014 void dunderSetItem(
const std::string &name,
const PyAttribute &attr);
2016 void dunderDelItem(
const std::string &name);
2020 bool dunderContains(
const std::string &name);
2022 static void forEachAttr(MlirOperation op,
2025 static void bind(nanobind::module_ &m);
2035 : operands(std::move(operands)), attributes(std::move(attributes)) {}
2037 : operands(std::move(operands)),
2038 attributes(opView.getOperation().getRef()) {}
2040 static void bind(nanobind::module_ &m);
2043 nanobind::list operands;
2049 static bool attach(
const nanobind::object &opName,
2052 static void bind(nanobind::module_ &m);
2062 static void bind(nanobind::module_ &m);
2068 static void bind(nanobind::module_ &m);
2074 static void bind(nanobind::module_ &m);
2081 static void bind(nanobind::module_ &m);
2092template <
class Func,
typename... Args>
2094 nanobind::object
cf = nanobind::cpp_function(f, args...);
2096 return std::make_unique<nanobind::object>(
2097 nanobind::module_::import_(
"builtins").attr(
"classmethod"));
2099 return classmethodFn.
get()(
cf);
2110 mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN::DefaultingPyMlirContext>
2112 mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN::DefaultingPyMlirContext> {
2116 mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN::DefaultingPyLocation>
2118 mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN::DefaultingPyLocation> {};
MLIR_FLOAT16_EXPORT bool operator==(const f16 &f1, const f16 &f2)
bool mlirValueIsABlockArgument(MlirValue value)
void mlirLocationPrint(MlirLocation location, MlirStringCallback callback, void *userData)
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 void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
static sycl::context getDefaultContext()
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
A CRTP base class for pseudo-containers willing to support Python-type slicing access on top of index...
nanobind::class_< PyOpResultList > 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 IsAFunctionTy isaFunction
static constexpr const char * pyClassName
PyConcreteLocation()=default
static constexpr GetTypeIDFunctionTy getTypeIdFunction
static void bindDerived(ClassTy &c)
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
static constexpr GetTypeIDFunctionTy getTypeIdFunction
static void bind(nanobind::module_ &m)
static void bindDerived(ClassTy &m)
Implemented by derived classes to add methods to the Python subclass.
PyConcreteLocation()=default
static MlirLocation castFrom(PyLocation &orig)
MlirTypeID(*)() GetTypeIDFunctionTy
PyConcreteLocation(PyLocation &orig)
PyConcreteLocation(PyMlirContextRef contextRef, MlirLocation loc)
nanobind::class_< DerivedTy, BaseTy > ClassTy
bool(*)(MlirLocation) IsAFunctionTy
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 void bind(nanobind::module_ &m)
static const char * typeIDAttr
static bool attach(const nanobind::object &opName, const nanobind::object &target, PyMlirContext &context)
static bool attach(const nanobind::object &opName, PyMlirContext &context)
static void bind(nanobind::module_ &m)
static bool attach(const nanobind::object &opName, PyMlirContext &context)
static void bind(nanobind::module_ &m)
static void bind(nanobind::module_ &m)
static bool attach(const nanobind::object &opName, PyMlirContext &context)
static bool attach(const nanobind::object &opName, PyMlirContext &context)
static void bind(nanobind::module_ &m)
static constexpr IsAFunctionTy isaFunction
static void bindDerived(ClassTy &c)
static constexpr GetTypeIDFunctionTy getTypeIdFunction
PyConcreteLocation()=default
static constexpr const char * pyClassName
static void bindDerived(ClassTy &c)
static constexpr GetTypeIDFunctionTy getTypeIdFunction
static constexpr IsAFunctionTy isaFunction
PyConcreteLocation()=default
static constexpr const char * pyClassName
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
static constexpr GetTypeIDFunctionTy getTypeIdFunction
static constexpr IsAFunctionTy isaFunction
static constexpr const char * pyClassName
PyConcreteLocation()=default
static void bindDerived(ClassTy &c)
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 & operator=(const PyObjectRef &other)
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 & operator=(PyObjectRef &&other) noexcept
PyObjectRef(const PyObjectRef &other)
PyOpAdaptor(nanobind::list operands, PyOpAttributeMap attributes)
PyOpAdaptor(nanobind::list operands, PyOpView &opView)
A list of operation attributes.
PyOpAttributeMap(PyOperationRef operation)
PyOpOperandIterator(MlirOpOperand opOperand)
PyOpOperandIterator & dunderIter()
static constexpr const char * pyClassName
Sliceable< PyOpOperandList, PyValue > SliceableT
static constexpr std::array< const char *, 1 > typeParams
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
static constexpr std::array< const char *, 1 > typeParams
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)
static constexpr const char * pyClassName
PyRegionList(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Wrapper around an MlirRegion.
PyOperationRef & getParentOperation()
PyRegion(PyOperationRef parentOperation, MlirRegion region)
PyRemark(MlirRemark remark)
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()
static constexpr GetTypeIDFunctionTy getTypeIdFunction
static constexpr const char * pyClassName
PyConcreteLocation()=default
static constexpr IsAFunctionTy isaFunction
static void bindDerived(ClassTy &c)
virtual ~PyValue()=default
PyOperationRef & getParentOperation()
PyValue(PyOperationRef parentOperation, MlirValue value)
Safely calls Python initialization code on first use, avoiding deadlocks.
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.
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 bool mlirLocationIsAUnknown(MlirLocation location)
Checks whether the given location is an Unknown.
MLIR_CAPI_EXPORTED MlirTypeID mlirLocationUnknownGetTypeID(void)
TypeID Getter for Unknown.
MLIR_CAPI_EXPORTED void mlirDialectRegistryDestroy(MlirDialectRegistry registry)
Takes a dialect registry owned by the caller and destroys it.
MLIR_CAPI_EXPORTED bool mlirLocationIsAFileLineColRange(MlirLocation location)
Checks whether the given location is an FileLineColRange.
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
MLIR_CAPI_EXPORTED bool mlirLocationIsACallSite(MlirLocation location)
Checks whether the given location is an CallSite.
static bool mlirBlockIsNull(MlirBlock block)
Checks whether a block is null.
MLIR_CAPI_EXPORTED bool mlirLocationIsAFused(MlirLocation location)
Checks whether the given location is an Fused.
MLIR_CAPI_EXPORTED void mlirSymbolTableDestroy(MlirSymbolTable symbolTable)
Destroys the symbol table created with mlirSymbolTableCreate.
MLIR_CAPI_EXPORTED bool mlirLocationIsAName(MlirLocation location)
Checks whether the given location is an Name.
static bool mlirDialectRegistryIsNull(MlirDialectRegistry registry)
Checks if the dialect registry is null.
MLIR_CAPI_EXPORTED MlirTypeID mlirLocationFileLineColRangeGetTypeID(void)
TypeID Getter for FileLineColRange.
static bool mlirRegionIsNull(MlirRegion region)
Checks whether a region is null.
MLIR_CAPI_EXPORTED MlirTypeID mlirLocationCallSiteGetTypeID(void)
TypeID Getter for CallSite.
MLIR_CAPI_EXPORTED MlirDialectRegistry mlirDialectRegistryCreate(void)
Creates a dialect registry and transfers its ownership to the caller.
MLIR_CAPI_EXPORTED MlirTypeID mlirLocationNameGetTypeID(void)
TypeID Getter for Name.
MLIR_CAPI_EXPORTED MlirTypeID mlirLocationFusedGetTypeID(void)
TypeID Getter for Fused.
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)
PyOperationEquivalenceFlags
Flags controlling structural operation equivalence and hashing.
MLIR_PYTHON_API_EXPORTED void populateRoot(nanobind::module_ &m)
MLIR_PYTHON_API_EXPORTED void populateIRRemarks(nanobind::module_ &m)
PyObjectRef< PyMlirContext > PyMlirContextRef
Wrapper around MlirContext.
PyObjectRef< PyOperation > PyOperationRef
MlirStringRef toMlirStringRef(const std::string &s)
PyRemarkKind
The kinds, emitting policies and file formats of the remark engine (mlir-c/Remarks....
PyObjectRef< PyModule > PyModuleRef
MlirBlock MLIR_PYTHON_API_EXPORTED createBlock(const nanobind::typed< nanobind::sequence, PyType > &pyArgTypes, const std::optional< nanobind::typed< nanobind::sequence, PyLocation > > &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)
nanobind::object classmethod(Func f, Args... args)
Helper for creating an @classmethod.
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(std::string message, std::vector< PyDiagnostic::DiagnosticInfo > &&errorDiagnostics={})
std::vector< PyDiagnostic::DiagnosticInfo > errorDiagnostics
const char * what() const noexcept override
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, bool allow_existing)
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)