28using namespace nb::literals;
33 R
"(Parses a module's assembly format from a string.
35Returns a new MlirModule or raises an MLIRError if the parsing fails.
37See also: https://mlir.llvm.org/docs/LangRef/
41 "Dumps a debug representation of the object to stderr.";
44 R
"(Replace all uses of this value with the `with` value, except for those
45in `exceptions`. `exceptions` can be either a single operation or a list of
55static size_t hash(
const T &value) {
56 return std::hash<T>{}(value);
61 nb::object dialectDescriptor) {
68 std::move(dialectDescriptor)));
72 return (*dialectClass)(std::move(dialectDescriptor));
80 const nb::typed<nb::sequence, PyType> &pyArgTypes,
81 const std::optional<nb::typed<nb::sequence, PyLocation>> &pyArgLocs) {
82 std::vector<MlirType> argTypes;
83 argTypes.reserve(nb::len(pyArgTypes));
84 for (nb::handle pyType : pyArgTypes)
86 nb::cast<python::MLIR_BINDINGS_PYTHON_DOMAIN::PyType &>(pyType));
88 std::vector<MlirLocation> argLocs;
90 argLocs.reserve(nb::len(*pyArgLocs));
91 for (nb::handle pyLoc : *pyArgLocs)
93 nb::cast<python::MLIR_BINDINGS_PYTHON_DOMAIN::PyLocation &>(pyLoc));
94 }
else if (!argTypes.empty()) {
100 if (argTypes.size() != argLocs.size())
101 throw nb::value_error(
102 join(
"Expected ", argTypes.size(),
" locations, got: ", argLocs.size())
104 return mlirBlockCreate(argTypes.size(), argTypes.data(), argLocs.data());
108 nb::ft_lock_guard lock(mutex);
113 nb::ft_lock_guard lock(mutex);
119 nb::class_<PyGlobalDebugFlag>(m,
"_GlobalDebug")
124 [](
const std::string &type) {
125 nb::ft_lock_guard lock(mutex);
128 "types"_a,
"Sets specific debug types to be produced by LLVM.")
131 [](
const std::vector<std::string> &types) {
132 std::vector<const char *> pointers;
133 pointers.reserve(types.size());
134 for (
const std::string &str : types)
135 pointers.push_back(str.c_str());
136 nb::ft_lock_guard lock(mutex);
140 "Sets multiple specific debug types to be produced by LLVM.");
143nb::ft_mutex PyGlobalDebugFlag::mutex;
153 throw nb::key_error(attributeKind.c_str());
158 nb::callable
func,
bool replace,
159 bool allow_existing) {
161 replace, allow_existing);
165 nb::class_<PyAttrBuilderMap>(m,
"AttrBuilder")
168 "Checks whether an attribute builder is registered for the "
169 "given attribute kind.")
172 "Gets the registered attribute builder for the given "
175 "attribute_kind"_a,
"attr_builder"_a,
"replace"_a =
false,
176 "allow_existing"_a =
false,
177 "Register an attribute builder for building MLIR "
178 "attributes from Python values.");
199 operation(std::move(operation)) {}
201intptr_t PyRegionList::getRawNumElements() {
217 operation->checkValid();
219 PyErr_SetNone(PyExc_StopIteration);
224 PyBlock returnBlock(operation, next);
226 return nb::cast(returnBlock);
230 nb::class_<PyBlockIterator>(m,
"BlockIterator")
232 "Returns an iterator over the blocks in the operation's region.")
234 "Returns the next block in the iteration.");
238 operation->checkValid();
243 operation->checkValid();
259 throw nb::index_error(
"attempt to access out of bounds block");
264 return PyBlock(operation, block);
269 throw nb::index_error(
"attempt to access out of bounds block");
273 const std::optional<nb::sequence> &pyArgLocs) {
275 MlirBlock block =
createBlock(nb::cast<nb::sequence>(pyArgTypes), pyArgLocs);
277 return PyBlock(operation, block);
281 nb::class_<PyBlockList>(m,
"BlockList")
283 "Returns the block at the specified index.")
285 "Returns an iterator over blocks in the operation's region.")
287 "Returns the number of blocks in the operation's region.")
290 Appends a new block, with argument types as positional args.
295 "args"_a, nb::kw_only(),
"arg_locs"_a = std::nullopt);
300 if (mlirOperationIsNull(next)) {
301 PyErr_SetNone(PyExc_StopIteration);
313 nb::class_<PyOperationIterator>(m,
"OperationIterator")
315 "Returns an iterator over the operations in an operation's block.")
317 "Returns the next operation in the iteration.");
321 parentOperation->checkValid();
330 while (!mlirOperationIsNull(childOp)) {
343 throw nb::index_error(
"attempt to access out of bounds operation");
346 while (!mlirOperationIsNull(childOp)) {
354 throw nb::index_error(
"attempt to access out of bounds operation");
358 nb::class_<PyOperationList>(m,
"OperationList")
360 "Returns the operation at the specified index.")
362 "Returns an iterator over operations in the list.")
364 "Returns the number of operations in the list.");
379 nb::class_<PyOpOperand>(m,
"OpOperand")
381 "Returns the operation that owns this operand.")
383 "Returns the operand number in the owning operation.");
388 PyErr_SetNone(PyExc_StopIteration);
395 return nb::cast(returnOpOperand);
399 nb::class_<PyOpOperandIterator>(m,
"OpOperandIterator")
401 "Returns an iterator over operands.")
403 "Returns the next operand in the iteration.");
422 std::stringstream ss;
423 ss << threadPool.ptr;
432 nb::gil_scoped_acquire acquire;
433 nb::ft_lock_guard lock(live_contexts_mutex);
434 auto &liveContexts = getLiveContexts();
435 liveContexts[context.ptr] =
this;
442 nb::gil_scoped_acquire acquire;
444 nb::ft_lock_guard lock(live_contexts_mutex);
445 getLiveContexts().erase(context.ptr);
461 throw nb::python_error();
466 nb::gil_scoped_acquire acquire;
467 nb::ft_lock_guard lock(live_contexts_mutex);
468 auto &liveContexts = getLiveContexts();
469 auto it = liveContexts.find(context.ptr);
470 if (it == liveContexts.end()) {
473 nb::object pyRef = nb::cast(unownedContextWrapper);
474 assert(pyRef &&
"cast to nb::object failed");
475 liveContexts[context.ptr] = unownedContextWrapper;
479 nb::object pyRef = nb::cast(it->second);
483nb::ft_mutex PyMlirContext::live_contexts_mutex;
485PyMlirContext::LiveContextMap &PyMlirContext::getLiveContexts() {
486 static LiveContextMap liveContexts;
491 nb::ft_lock_guard lock(live_contexts_mutex);
492 return getLiveContexts().size();
500 const nb::object &excVal,
501 const nb::object &excTb) {
510 nb::object pyHandlerObject =
511 nb::cast(pyHandler, nb::rv_policy::take_ownership);
512 (
void)pyHandlerObject.inc_ref();
516 auto handlerCallback =
519 nb::object pyDiagnosticObject =
520 nb::cast(pyDiagnostic, nb::rv_policy::take_ownership);
527 nb::gil_scoped_acquire gil;
529 result = nb::cast<bool>(pyHandler->callback(pyDiagnostic));
530 }
catch (std::exception &e) {
531 fprintf(stderr,
"MLIR Python Diagnostic handler raised exception: %s\n",
533 pyHandler->hadError =
true;
540 auto deleteCallback = +[](
void *userData) {
541 auto *pyHandler =
static_cast<PyDiagnosticHandler *
>(userData);
542 assert(pyHandler->registeredID &&
"handler is not registered");
543 pyHandler->registeredID.reset();
546 nb::object pyHandlerObject = nb::cast(pyHandler, nb::rv_policy::reference);
547 pyHandlerObject.dec_ref();
551 get(), handlerCallback,
static_cast<void *
>(pyHandler), deleteCallback);
552 return pyHandlerObject;
559 if (self->ctx->emitErrorDiagnostics)
563 MlirDiagnosticSeverity::MlirDiagnosticError)
573 throw std::runtime_error(
574 "An MLIR function requires a Context but none was provided in the call "
575 "or from the surrounding environment. Either pass to the function with "
576 "a 'context=' argument or establish a default using 'with Context():'");
586 static thread_local std::vector<PyThreadContextEntry> stack;
591 auto &stack = getStack();
594 return &stack.back();
597void PyThreadContextEntry::push(FrameKind frameKind, nb::object context,
598 nb::object insertionPoint,
599 nb::object location) {
600 auto &stack = getStack();
601 stack.emplace_back(frameKind, std::move(context), std::move(insertionPoint),
602 std::move(location));
606 if (stack.size() > 1) {
607 auto &prev = *(stack.rbegin() + 1);
608 auto ¤t = stack.back();
609 if (current.context.is(prev.context)) {
611 if (!current.insertionPoint)
612 current.insertionPoint = prev.insertionPoint;
613 if (!current.location)
614 current.location = prev.location;
622 return nb::cast<PyMlirContext *>(context);
628 return nb::cast<PyInsertionPoint *>(insertionPoint);
634 return nb::cast<PyLocation *>(location);
639 return tos ? tos->getContext() :
nullptr;
644 return tos ? tos->getInsertionPoint() :
nullptr;
649 return tos ? tos->getLocation() :
nullptr;
653 push(FrameKind::Context, context,
660 auto &stack = getStack();
662 throw std::runtime_error(
"Unbalanced Context enter/exit");
663 auto &tos = stack.back();
664 if (tos.frameKind != FrameKind::Context && tos.getContext() != &context)
665 throw std::runtime_error(
"Unbalanced Context enter/exit");
672 nb::cast<PyInsertionPoint &>(insertionPointObj);
673 nb::object contextObj =
675 push(FrameKind::InsertionPoint,
679 return insertionPointObj;
683 auto &stack = getStack();
685 throw std::runtime_error(
"Unbalanced InsertionPoint enter/exit");
686 auto &tos = stack.back();
687 if (tos.frameKind != FrameKind::InsertionPoint &&
688 tos.getInsertionPoint() != &insertionPoint)
689 throw std::runtime_error(
"Unbalanced InsertionPoint enter/exit");
694 PyLocation &location = nb::cast<PyLocation &>(locationObj);
696 push(FrameKind::Location, contextObj,
703 auto &stack = getStack();
705 throw std::runtime_error(
"Unbalanced Location enter/exit");
706 auto &tos = stack.back();
707 if (tos.frameKind != FrameKind::Location && tos.getLocation() != &location)
708 throw std::runtime_error(
"Unbalanced Location enter/exit");
718 if (materializedNotes) {
719 for (nb::handle noteObject : *materializedNotes) {
720 PyDiagnostic *note = nb::cast<PyDiagnostic *>(noteObject);
728 : context(context), callback(std::move(callback)) {}
737 assert(!registeredID &&
"should have unregistered");
743void PyDiagnostic::checkValid() {
745 throw std::invalid_argument(
746 "Diagnostic is invalid (used outside of callback)");
765 nb::object fileObject = nb::module_::import_(
"io").attr(
"StringIO")();
768 return nb::cast<nb::str>(fileObject.attr(
"getvalue")());
773 if (materializedNotes)
774 return *materializedNotes;
776 nb::tuple notes = nb::steal<nb::tuple>(PyTuple_New(numNotes));
777 for (
intptr_t i = 0; i < numNotes; ++i) {
779 nb::object diagnostic = nb::cast(
PyDiagnostic(noteDiag));
780 PyTuple_SetItem(notes.ptr(), i, diagnostic.release().ptr());
782 materializedNotes = std::move(notes);
784 return *materializedNotes;
788 std::vector<DiagnosticInfo> notes;
790 notes.emplace_back(nb::cast<PyDiagnostic>(n).
getInfo());
802 {key.data(), key.size()});
804 std::string msg =
join(
"Dialect '", key,
"' not found");
806 throw nb::attribute_error(msg.c_str());
807 throw nb::index_error(msg.c_str());
817 MlirDialectRegistry rawRegistry =
820 throw nb::python_error();
835 throw nb::python_error();
845 const nb::object &excVal,
846 const nb::object &excTb) {
853 throw std::runtime_error(
854 "An MLIR function requires a Location but none was provided in the "
855 "call or from the surrounding environment. Either pass to the function "
856 "with a 'loc=' argument or establish a default using 'with loc:'");
869 nb::gil_scoped_acquire acquire;
870 auto &liveModules =
getContext()->liveModules;
871 assert(liveModules.count(module.ptr) == 1 &&
872 "destroying module not in live map");
873 liveModules.erase(module.ptr);
881 nb::gil_scoped_acquire acquire;
882 auto &liveModules = contextRef->liveModules;
883 auto it = liveModules.find(module.ptr);
884 if (it == liveModules.end()) {
890 nb::object pyRef = nb::cast(unownedModule, nb::rv_policy::take_ownership);
891 unownedModule->handle = pyRef;
892 liveModules[module.ptr] =
893 std::make_pair(unownedModule->handle, unownedModule);
894 return PyModuleRef(unownedModule, std::move(pyRef));
898 nb::object pyRef = nb::borrow<nb::object>(it->second.first);
904 if (mlirModuleIsNull(rawModule))
905 throw nb::python_error();
937template <
typename T,
class... Args>
939 nb::handle type = nb::type<T>();
940 nb::object instance = nb::inst_alloc(type);
941 T *
ptr = nb::inst_ptr<T>(instance);
942 new (
ptr) T(std::forward<Args>(args)...);
943 nb::inst_mark_ready(instance);
950 MlirOperation operation,
951 nb::object parentKeepAlive) {
954 makeObjectRef<PyOperation>(std::move(contextRef), operation);
955 unownedOperation->handle = unownedOperation.
getObject();
956 if (parentKeepAlive) {
957 unownedOperation->parentKeepAlive = std::move(parentKeepAlive);
959 return unownedOperation;
963 MlirOperation operation,
964 nb::object parentKeepAlive) {
965 return createInstance(std::move(contextRef), operation,
966 std::move(parentKeepAlive));
970 MlirOperation operation,
971 nb::object parentKeepAlive) {
972 PyOperationRef created = createInstance(std::move(contextRef), operation,
973 std::move(parentKeepAlive));
974 created->attached =
false;
979 const std::string &sourceStr,
980 const std::string &sourceName) {
985 if (mlirOperationIsNull(op))
986 throw MLIRError(
"Unable to parse operation assembly", errors.take());
993 parentKeepAlive = nb::object();
1006 assert(!attached &&
"operation already attached");
1011 assert(attached &&
"operation already detached");
1017 throw std::runtime_error(
"the operation has been invalidated");
1022 std::optional<int64_t> largeResourceLimit,
1023 bool enableDebugInfo,
bool prettyDebugInfo,
1024 bool printGenericOpForm,
bool useLocalScope,
1025 bool useNameLocAsPrefix,
bool assumeVerified,
1026 nb::object fileObject,
bool binary,
1030 if (fileObject.is_none())
1031 fileObject = nb::module_::import_(
"sys").attr(
"stdout");
1034 if (largeElementsLimit)
1036 if (largeResourceLimit)
1038 if (enableDebugInfo)
1041 if (printGenericOpForm)
1049 if (useNameLocAsPrefix)
1054 accum.getUserData());
1062 if (fileObject.is_none())
1063 fileObject = nb::module_::import_(
"sys").attr(
"stdout");
1066 accum.getUserData());
1070 std::optional<int64_t> bytecodeVersion) {
1075 if (!bytecodeVersion.has_value())
1077 accum.getUserData());
1082 operation, config, accum.getCallback(), accum.getUserData());
1085 throw nb::value_error(
1086 join(
"Unable to honor desired bytecode version ", *bytecodeVersion)
1097 std::string exceptionWhat;
1098 nb::object exceptionType;
1100 UserData userData{callback,
false, {}, {}};
1103 UserData *calleeUserData =
static_cast<UserData *
>(userData);
1105 return static_cast<MlirWalkResult>((calleeUserData->callback)(op));
1106 }
catch (nb::python_error &e) {
1107 calleeUserData->gotException =
true;
1108 calleeUserData->exceptionWhat = std::string(e.what());
1109 calleeUserData->exceptionType = nb::borrow(e.type());
1110 return MlirWalkResult::MlirWalkResultInterrupt;
1115 if (userData.gotException) {
1116 std::string message(
"Exception raised in callback: ");
1117 message.append(userData.exceptionWhat);
1118 throw std::runtime_error(message);
1123 std::optional<int64_t> largeElementsLimit,
1124 std::optional<int64_t> largeResourceLimit,
1125 bool enableDebugInfo,
bool prettyDebugInfo,
1126 bool printGenericOpForm,
bool useLocalScope,
1127 bool useNameLocAsPrefix,
bool assumeVerified,
1129 nb::object fileObject;
1131 fileObject = nb::module_::import_(
"io").attr(
"BytesIO")();
1133 fileObject = nb::module_::import_(
"io").attr(
"StringIO")();
1135 print(largeElementsLimit,
1147 return fileObject.attr(
"getvalue")();
1156 operation.parentKeepAlive = otherOp.parentKeepAlive;
1165 operation.parentKeepAlive = otherOp.parentKeepAlive;
1180 throw MLIRError(
"Verification failed", errors.take());
1187 throw nb::value_error(
"Detached operations have no parent");
1189 if (mlirOperationIsNull(operation))
1199 assert(parentOperation &&
"Operation has no parent");
1200 return PyBlock{std::move(*parentOperation), block};
1210 if (mlirOperationIsNull(rawOperation))
1211 throw nb::python_error();
1218 const nb::object &maybeIp) {
1220 if (!maybeIp.is(nb::cast(
false))) {
1222 if (maybeIp.is_none()) {
1225 ip = nb::cast<PyInsertionPoint *>(maybeIp);
1233 std::optional<std::vector<PyType *>> results,
1234 const MlirValue *operands,
size_t numOperands,
1235 std::optional<nb::dict> attributes,
1236 std::optional<std::vector<PyBlock *>> successors,
1238 const nb::object &maybeIp,
bool inferType) {
1239 std::vector<MlirType> mlirResults;
1240 std::vector<MlirBlock> mlirSuccessors;
1241 std::vector<std::pair<std::string, MlirAttribute>> mlirAttributes;
1245 throw nb::value_error(
"number of regions must be >= 0");
1249 mlirResults.reserve(results->size());
1253 throw nb::value_error(
"result type cannot be None");
1254 mlirResults.push_back(*
result);
1259 mlirAttributes.reserve(attributes->size());
1260 for (std::pair<nb::handle, nb::handle> it : *attributes) {
1263 key = nb::cast<std::string>(it.first);
1264 }
catch (nb::cast_error &err) {
1265 std::string msg =
join(
"Invalid attribute key (not a string) when "
1266 "attempting to create the operation \"",
1267 name,
"\" (", err.what(),
")");
1268 throw nb::type_error(msg.c_str());
1271 auto &attribute = nb::cast<PyAttribute &>(it.second);
1273 mlirAttributes.emplace_back(std::move(key), attribute);
1274 }
catch (nb::cast_error &err) {
1275 std::string msg =
join(
"Invalid attribute value for the key \"", key,
1276 "\" when attempting to create the operation \"",
1277 name,
"\" (", err.what(),
")");
1278 throw nb::type_error(msg.c_str());
1279 }
catch (std::runtime_error &) {
1281 std::string msg =
join(
1282 "Found an invalid (`None`?) attribute value for the key \"", key,
1283 "\" when attempting to create the operation \"", name,
"\"");
1284 throw std::runtime_error(msg);
1290 mlirSuccessors.reserve(successors->size());
1291 for (PyBlock *successor : *successors) {
1294 throw nb::value_error(
"successor block cannot be None");
1295 mlirSuccessors.push_back(successor->get());
1301 MlirOperationState state =
1303 if (numOperands > 0)
1305 state.enableResultTypeInference = inferType;
1306 if (!mlirResults.empty())
1308 mlirResults.data());
1309 if (!mlirAttributes.empty()) {
1313 std::vector<MlirNamedAttribute> mlirNamedAttributes;
1314 mlirNamedAttributes.reserve(mlirAttributes.size());
1315 for (
const std::pair<std::string, MlirAttribute> &it : mlirAttributes)
1321 mlirNamedAttributes.data());
1323 if (!mlirSuccessors.empty())
1325 mlirSuccessors.data());
1327 std::vector<MlirRegion> mlirRegions;
1328 mlirRegions.resize(regions);
1329 for (
int i = 0; i < regions; ++i)
1332 mlirRegions.data());
1336 PyMlirContext::ErrorCapture errors(location.
getContext());
1339 throw MLIRError(
"Operation creation failed", errors.take());
1361 std::string_view(identStr.
data, identStr.
length));
1376 [](
PyOpResult &self) -> nb::typed<nb::object, PyOpView> {
1379 "expected the owner of the value in Python to match that in "
1383 "Returns the operation that produces this result.");
1387 "Returns the position of this result in the operation's result list.");
1391template <
typename Container>
1392static std::vector<nb::typed<nb::object, PyType>>
1394 std::vector<nb::typed<nb::object, PyType>>
result;
1395 result.reserve(container.size());
1396 for (
int i = 0, e = container.size(); i < e; ++i) {
1410 operation(std::move(operation)) {}
1418 "Returns a list of types for all results in this result list.");
1424 "Returns the operation that owns this result list.");
1427intptr_t PyOpResultList::getRawNumElements() {
1428 operation->checkValid();
1432PyOpResult PyOpResultList::getRawElement(intptr_t index) {
1434 return PyOpResult(value);
1437PyOpResultList PyOpResultList::slice(intptr_t startIndex, intptr_t length,
1438 intptr_t step)
const {
1447 nb::sequence resultTypeList,
1448 const nb::object &resultSegmentSpecObj,
1449 std::vector<int32_t> &resultSegmentLengths,
1450 std::vector<PyType *> &resultTypes) {
1451 resultTypes.reserve(nb::len(resultTypeList));
1452 if (resultSegmentSpecObj.is_none()) {
1455 for (nb::handle resultType : resultTypeList) {
1457 resultTypes.push_back(nb::cast<PyType *>(resultType));
1458 if (!resultTypes.back())
1459 throw nb::cast_error();
1460 }
catch (nb::cast_error &err) {
1461 throw nb::value_error(
join(
"Result ",
index,
" of operation \"", name,
1462 "\" must be a Type (", err.what(),
")")
1469 auto resultSegmentSpec = nb::cast<std::vector<int>>(resultSegmentSpecObj);
1470 if (resultSegmentSpec.size() != nb::len(resultTypeList)) {
1471 throw nb::value_error(
1472 join(
"Operation \"", name,
"\" requires ", resultSegmentSpec.size(),
1473 " result segments but was provided ", nb::len(resultTypeList))
1476 resultSegmentLengths.reserve(nb::len(resultTypeList));
1477 for (
size_t i = 0, e = resultSegmentSpec.size(); i < e; ++i) {
1478 int segmentSpec = resultSegmentSpec[i];
1479 if (segmentSpec == 1 || segmentSpec == 0) {
1482 auto *resultType = nb::cast<PyType *>(resultTypeList[i]);
1484 resultTypes.push_back(resultType);
1485 resultSegmentLengths.push_back(1);
1486 }
else if (segmentSpec == 0) {
1488 resultSegmentLengths.push_back(0);
1490 throw nb::value_error(
1491 join(
"Result ", i,
" of operation \"", name,
1492 "\" must be a Type (was None and result is not optional)")
1495 }
catch (nb::cast_error &err) {
1496 throw nb::value_error(
join(
"Result ", i,
" of operation \"", name,
1497 "\" must be a Type (", err.what(),
")")
1500 }
else if (segmentSpec == -1) {
1503 if (resultTypeList[i].is_none()) {
1505 resultSegmentLengths.push_back(0);
1508 auto segment = nb::cast<nb::sequence>(resultTypeList[i]);
1509 for (nb::handle segmentItem : segment) {
1510 resultTypes.push_back(nb::cast<PyType *>(segmentItem));
1511 if (!resultTypes.back()) {
1512 throw nb::type_error(
"contained a None item");
1515 resultSegmentLengths.push_back(nb::len(segment));
1517 }
catch (std::exception &err) {
1521 throw nb::value_error(
join(
"Result ", i,
" of operation \"", name,
1522 "\" must be a Sequence of Types (",
1527 throw nb::value_error(
"Unexpected segment spec");
1535 if (numResults != 1) {
1537 throw nb::value_error(
1538 join(
"Cannot call .result on operation ",
1539 std::string_view(name.data, name.length),
" which has ",
1541 " results (it is only valid for operations with a "
1549 if (operand.is_none()) {
1550 throw nb::value_error(
"contained a None item");
1553 if (nb::try_cast<PyOperationBase *>(operand, op)) {
1557 if (nb::try_cast<PyOpResultList *>(operand, opResultList)) {
1561 if (nb::try_cast<PyValue *>(operand, value)) {
1564 throw nb::value_error(
"is not a Value");
1568 std::string_view name, std::tuple<int, bool> opRegionSpec,
1569 nb::object operandSegmentSpecObj, nb::object resultSegmentSpecObj,
1570 std::optional<nb::sequence> resultTypeList, nb::sequence operandList,
1571 std::optional<nb::dict> attributes,
1572 std::optional<std::vector<PyBlock *>> successors,
1573 std::optional<int> regions,
PyLocation &location,
1574 const nb::object &maybeIp) {
1583 std::vector<int32_t> operandSegmentLengths;
1584 std::vector<int32_t> resultSegmentLengths;
1587 int opMinRegionCount = std::get<0>(opRegionSpec);
1588 bool opHasNoVariadicRegions = std::get<1>(opRegionSpec);
1590 regions = opMinRegionCount;
1592 if (*regions < opMinRegionCount) {
1593 throw nb::value_error(
join(
"Operation \"", name,
1594 "\" requires a minimum of ", opMinRegionCount,
1595 " regions but was built with regions=", *regions)
1598 if (opHasNoVariadicRegions && *regions > opMinRegionCount) {
1599 throw nb::value_error(
join(
"Operation \"", name,
1600 "\" requires a maximum of ", opMinRegionCount,
1601 " regions but was built with regions=", *regions)
1606 std::vector<PyType *> resultTypes;
1607 if (resultTypeList.has_value()) {
1609 resultSegmentLengths, resultTypes);
1613 std::vector<MlirValue> operands;
1614 operands.reserve(operands.size());
1616 if (operandSegmentSpecObj.is_none()) {
1618 for (nb::handle operand : operandList) {
1621 }
catch (nb::builtin_exception &err) {
1622 throw nb::value_error(
join(
"Operand ", index,
" of operation \"", name,
1623 "\" must be a Value (", err.what(),
")")
1630 auto operandSegmentSpec = nb::cast<std::vector<int>>(operandSegmentSpecObj);
1631 if (operandSegmentSpec.size() != nb::len(operandList)) {
1632 throw nb::value_error(
1633 join(
"Operation \"", name,
"\" requires ", operandSegmentSpec.size(),
1634 "operand segments but was provided ", nb::len(operandList))
1637 operandSegmentLengths.reserve(nb::len(operandList));
1638 for (
size_t i = 0, e = operandSegmentSpec.size(); i < e; ++i) {
1639 int segmentSpec = operandSegmentSpec[i];
1640 if (segmentSpec == 1 || segmentSpec == 0) {
1642 const nanobind::handle operand = operandList[i];
1643 if (!operand.is_none()) {
1646 }
catch (nb::builtin_exception &err) {
1647 throw nb::value_error(
join(
"Operand ", i,
" of operation \"", name,
1648 "\" must be a Value (", err.what(),
")")
1652 operandSegmentLengths.push_back(1);
1653 }
else if (segmentSpec == 0) {
1655 operandSegmentLengths.push_back(0);
1657 throw nb::value_error(
1658 join(
"Operand ", i,
" of operation \"", name,
1659 "\" must be a Value (was None and operand is not optional)")
1662 }
else if (segmentSpec == -1) {
1665 if (operandList[i].is_none()) {
1667 operandSegmentLengths.push_back(0);
1670 auto segment = nb::cast<nb::sequence>(operandList[i]);
1671 for (nb::handle segmentItem : segment) {
1674 operandSegmentLengths.push_back(nb::len(segment));
1676 }
catch (std::exception &err) {
1680 throw nb::value_error(
join(
"Operand ", i,
" of operation \"", name,
1681 "\" must be a Sequence of Values (",
1686 throw nb::value_error(
"Unexpected segment spec");
1692 if (!operandSegmentLengths.empty() || !resultSegmentLengths.empty()) {
1695 attributes = nb::dict(*attributes);
1697 attributes = nb::dict();
1699 if (attributes->contains(
"resultSegmentSizes") ||
1700 attributes->contains(
"operandSegmentSizes")) {
1701 throw nb::value_error(
"Manually setting a 'resultSegmentSizes' or "
1702 "'operandSegmentSizes' attribute is unsupported. "
1703 "Use Operation.create for such low-level access.");
1707 if (!resultSegmentLengths.empty()) {
1708 MlirAttribute segmentLengthAttr =
1710 resultSegmentLengths.data());
1711 (*attributes)[
"resultSegmentSizes"] =
1712 PyAttribute(context, segmentLengthAttr);
1716 if (!operandSegmentLengths.empty()) {
1717 MlirAttribute segmentLengthAttr =
1719 operandSegmentLengths.data());
1720 (*attributes)[
"operandSegmentSizes"] =
1721 PyAttribute(context, segmentLengthAttr);
1727 std::move(resultTypes),
1730 std::move(attributes),
1731 std::move(successors),
1732 *regions, location, maybeIp,
1737 const nb::object &operation) {
1738 nb::handle opViewType = nb::type<PyOpView>();
1739 nb::object instance = cls.attr(
"__new__")(cls);
1740 opViewType.attr(
"__init__")(instance, operation);
1748 operationObject(operation.getRef().getObject()) {}
1779 : refOperation(beforeOperationBase.getOperation().getRef()),
1783 : refOperation(beforeOperationRef), block((*refOperation)->getBlock()) {}
1788 throw nb::value_error(
1789 "Attempt to insert operation that is already attached");
1790 block.getParentOperation()->checkValid();
1791 MlirOperation beforeOp = {
nullptr};
1794 (*refOperation)->checkValid();
1795 beforeOp = (*refOperation)->get();
1801 throw nb::index_error(
"Cannot insert operation at the end of a block "
1802 "that already has a terminator. Did you mean to "
1803 "use 'InsertionPoint.at_block_terminator(block)' "
1804 "versus 'InsertionPoint(block)'?");
1813 if (mlirOperationIsNull(firstOp)) {
1820 block.getParentOperation()->getContext(), firstOp);
1826 if (mlirOperationIsNull(terminator))
1827 throw nb::value_error(
"Block has no terminator");
1829 block.getParentOperation()->getContext(), terminator);
1837 if (mlirOperationIsNull(nextOperation))
1851 const nb::object &excVal,
1852 const nb::object &excTb) {
1870 if (mlirAttributeIsNull(rawAttr))
1871 throw nb::python_error();
1879 "mlirTypeID was expected to be non-null.");
1884 nb::object thisObj = nb::cast(
this, nb::rv_policy::move);
1887 return typeCaster.value()(thisObj);
1895 : ownedName(new std::string(std::move(ownedName))) {
1917 throw nb::python_error();
1925 "mlirTypeID was expected to be non-null.");
1930 nb::object thisObj = nb::cast(
this, nb::rv_policy::move);
1933 return typeCaster.value()(thisObj);
1947 throw nb::python_error();
1963 MlirOperation owner;
1969 assert(
false &&
"Value must be an block arg or op result.");
1970 if (mlirOperationIsNull(owner))
1971 throw nb::python_error();
1976nb::typed<nb::object, std::variant<PyBlockArgument, PyOpResult, PyValue>>
1981 "mlirTypeID was expected to be non-null.");
1982 std::optional<nb::callable> valueCaster =
1988 thisObj = nb::cast<PyOpResult>(*
this, nb::rv_policy::move);
1990 thisObj = nb::cast<PyBlockArgument>(*
this, nb::rv_policy::move);
1992 assert(
false &&
"Value must be an block arg or op result.");
1994 return valueCaster.value()(thisObj);
2000 if (mlirValueIsNull(value))
2001 throw nb::python_error();
2003 return PyValue(ownerRef, value);
2011 : operation(operation.getOperation().getRef()) {
2014 throw nb::type_error(
"Operation is not a Symbol Table.");
2019 operation->checkValid();
2022 if (mlirOperationIsNull(symbol))
2023 throw nb::key_error(
2024 join(
"Symbol '", name,
"' not in the symbol table.").c_str());
2027 operation.getObject())
2032 operation->checkValid();
2043 erase(nb::cast<PyOperationBase &>(operation));
2047 operation->checkValid();
2051 if (mlirAttributeIsNull(symbolAttr))
2052 throw nb::value_error(
"Expected operation to have a symbol name.");
2063 MlirAttribute existingNameAttr =
2065 if (mlirAttributeIsNull(existingNameAttr))
2066 throw nb::value_error(
"Expected operation to have a symbol name.");
2072 const std::string &name) {
2077 MlirAttribute existingNameAttr =
2079 if (mlirAttributeIsNull(existingNameAttr))
2080 throw nb::value_error(
"Expected operation to have a symbol name.");
2081 MlirAttribute newNameAttr =
2090 MlirAttribute existingVisAttr =
2092 if (mlirAttributeIsNull(existingVisAttr))
2093 throw nb::value_error(
"Expected operation to have a symbol visibility.");
2098 const std::string &visibility) {
2099 if (visibility !=
"public" && visibility !=
"private" &&
2100 visibility !=
"nested")
2101 throw nb::value_error(
2102 "Expected visibility to be 'public', 'private' or 'nested'");
2106 MlirAttribute existingVisAttr =
2108 if (mlirAttributeIsNull(existingVisAttr))
2109 throw nb::value_error(
"Expected operation to have a symbol visibility.");
2116 const std::string &newSymbol,
2124 throw nb::value_error(
"Symbol rename failed");
2128 bool allSymUsesVisible,
2129 nb::object callback) {
2134 nb::object callback;
2136 std::string exceptionWhat;
2137 nb::object exceptionType;
2140 fromOperation.
getContext(), std::move(callback),
false, {}, {}};
2142 fromOperation.
get(), allSymUsesVisible,
2143 [](MlirOperation foundOp,
bool isVisible,
void *calleeUserDataVoid) {
2144 UserData *calleeUserData = static_cast<UserData *>(calleeUserDataVoid);
2146 PyOperation::forOperation(calleeUserData->context, foundOp);
2147 if (calleeUserData->gotException)
2150 calleeUserData->callback(pyFoundOp.getObject(), isVisible);
2151 } catch (nb::python_error &e) {
2152 calleeUserData->gotException =
true;
2153 calleeUserData->exceptionWhat = e.what();
2154 calleeUserData->exceptionType = nb::borrow(e.type());
2157 static_cast<void *
>(&userData));
2158 if (userData.gotException) {
2159 std::string message(
"Exception raised in callback: ");
2160 message.append(userData.exceptionWhat);
2161 throw std::runtime_error(message);
2172 "Returns the block that owns this argument.");
2178 "Returns the position of this argument in the block's argument list.");
2184 "type"_a,
"Sets the type of this block argument.");
2187 [](PyBlockArgument &self, PyLocation loc) {
2190 "loc"_a,
"Sets the location of this block argument.");
2194 MlirBlock block,
intptr_t startIndex,
2198 operation(std::move(operation)), block(block) {}
2206 "Returns a list of types for all arguments in this argument list.");
2209intptr_t PyBlockArgumentList::getRawNumElements() {
2231 operation(operation) {}
2240 "Sets the operand at the specified index to a new value.");
2243intptr_t PyOpOperandList::getRawNumElements() {
2251 return PyValue(pyOwner, operand);
2265 static constexpr const char *
pyClassName =
"OpOperands";
2274 operation(operation) {}
2281 operation->checkValid();
2303 operation(operation) {}
2312 "Sets the successor block at the specified index.");
2315intptr_t PyOpSuccessors::getRawNumElements() {
2322 return PyBlock(operation, block);
2336 operation(operation), block(block) {}
2338intptr_t PyBlockSuccessors::getRawNumElements() {
2345 return PyBlock(operation, block);
2361 operation(operation), block(block) {}
2363intptr_t PyBlockPredecessors::getRawNumElements() {
2370 return PyBlock(operation, block);
2379nb::typed<nb::object, PyAttribute>
2381 MlirAttribute attr =
2383 if (mlirAttributeIsNull(attr)) {
2384 throw nb::key_error(
"attempt to access a non-existent attribute");
2389nb::typed<nb::object, std::optional<PyAttribute>>
2391 MlirAttribute attr =
2393 if (mlirAttributeIsNull(attr))
2394 return defaultValue;
2402 if (index < 0 || index >=
dunderLen()) {
2403 throw nb::index_error(
"attempt to access out of bounds attribute");
2423 throw nb::key_error(
"attempt to delete a non-existent attribute");
2431 return !mlirAttributeIsNull(
2436 MlirOperation op, std::function<
void(
MlirStringRef, MlirAttribute)> fn) {
2446 nb::class_<PyOpAttributeMap>(m,
"OpAttributeMap")
2448 "Checks if an attribute with the given name exists in the map.")
2450 "Returns the number of attributes in the map.")
2452 "Gets an attribute by name.")
2454 "Gets a named attribute by index.")
2456 "Sets an attribute with the given name.")
2458 "Deletes an attribute with the given name.")
2460 nb::arg(
"default") = nb::none(),
2461 "Gets an attribute by name or the default value, if it does not "
2469 keys.append(nb::str(name.data, name.length));
2471 return nb::iter(keys);
2473 "Iterates over attribute names.")
2480 out.append(nb::str(name.data, name.length));
2484 "Returns a list of attribute names.")
2491 out.append(PyAttribute(self.operation->getContext(), attr)
2496 "Returns a list of attribute values.")
2500 -> nb::typed<nb::list,
2501 nb::typed<nb::tuple, nb::str, PyAttribute>> {
2504 self.operation->
get(),
2506 out.append(nb::make_tuple(
2507 nb::str(name.data, name.length),
2508 PyAttribute(self.operation->getContext(), attr)
2513 "Returns a list of `(name, attribute)` tuples.");
2517 nb::class_<PyOpAdaptor>(m,
"OpAdaptor")
2519 "Creates an OpAdaptor with the given operands and attributes.",
2520 "operands"_a,
"attributes"_a)
2521 .def(nb::init<nb::typed<nb::list, PyValue>,
PyOpView &>(),
2522 "Creates an OpAdaptor with the given operands and operation view.",
2523 "operands"_a,
"opview"_a)
2525 "operands", [](
PyOpAdaptor &self) {
return self.operands; },
2526 "Returns the operands of the adaptor.")
2528 "attributes", [](
PyOpAdaptor &self) {
return self.attributes; },
2529 "Returns the attributes of the adaptor.");
2533 const char *methodName) {
2534 nb::handle targetObj(
static_cast<PyObject *
>(userData));
2535 if (!nb::hasattr(targetObj, methodName))
2539 bool success = nb::cast<bool>(targetObj.attr(methodName)(opView));
2543static bool attachOpTrait(
const nb::object &opName, MlirDynamicOpTrait trait,
2545 std::string opNameStr;
2546 if (opName.is_type()) {
2547 opNameStr = nb::cast<std::string>(opName.attr(
"OPERATION_NAME"));
2548 }
else if (nb::isinstance<nb::str>(opName)) {
2549 opNameStr = nb::cast<std::string>(opName);
2551 throw nb::type_error(
"the root argument must be a type or a string");
2559 const nb::object &
target,
2561 if (!nb::hasattr(
target,
"verify_invariants") &&
2562 !nb::hasattr(
target,
"verify_region_invariants"))
2563 throw nb::type_error(
2564 "the target object must have at least one of 'verify_invariants' or "
2565 "'verify_region_invariants' methods");
2568 callbacks.
construct = [](
void *userData) {
2569 nb::handle(
static_cast<PyObject *
>(userData)).inc_ref();
2571 callbacks.
destruct = [](
void *userData) {
2572 nb::handle(
static_cast<PyObject *
>(userData)).dec_ref();
2592 static_cast<void *
>(
target.ptr()));
2597 nb::class_<PyDynamicOpTrait> cls(m,
"DynamicOpTrait");
2599 [](
const nb::object &cls,
const nb::object &opName, nb::object
target,
2605 nb::arg(
"cls"), nb::arg(
"op_name"), nb::arg(
"target").none() = nb::none(),
2606 nb::arg(
"context").none() = nb::none(),
2607 "Attach the dynamic op trait subclass to the given operation name.");
2617 nb::class_<PyDynamicOpTraits::IsTerminator, PyDynamicOpTrait> cls(
2618 m,
"IsTerminatorTrait");
2621 [](
const nb::object &cls,
const nb::object &opName,
2625 "Attach IsTerminator trait to the given operation name.", nb::arg(
"cls"),
2626 nb::arg(
"op_name"), nb::arg(
"context").none() = nb::none());
2636 nb::class_<PyDynamicOpTraits::NoTerminator, PyDynamicOpTrait> cls(
2637 m,
"NoTerminatorTrait");
2640 [](
const nb::object &cls,
const nb::object &opName,
2644 "Attach NoTerminator trait to the given operation name.", nb::arg(
"cls"),
2645 nb::arg(
"op_name"), nb::arg(
"context").none() = nb::none());
2654using namespace mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN;
2656MlirLocation tracebackToLocation(MlirContext ctx) {
2657#if defined(Py_LIMITED_API)
2662 size_t framesLimit =
2665 thread_local std::array<MlirLocation, PyGlobals::TracebackLoc::kMaxFrames>
2669 nb::gil_scoped_acquire acquire;
2671 PyThreadState *tstate = PyThreadState_GET();
2672 PyFrameObject *next;
2673 PyFrameObject *pyFrame = PyThreadState_GetFrame(tstate);
2679 for (; pyFrame !=
nullptr && count < framesLimit;
2680 next = PyFrame_GetBack(pyFrame), Py_XDECREF(pyFrame), pyFrame = next) {
2681 PyCodeObject *code = PyFrame_GetCode(pyFrame);
2683 nb::cast<std::string>(nb::borrow<nb::str>(code->co_filename));
2684 std::string_view fileName(fileNameStr);
2685 if (!
PyGlobals::get().getTracebackLoc().isUserTracebackFilename(fileName))
2689#if PY_VERSION_HEX < 0x030B00F0
2691 nb::cast<std::string>(nb::borrow<nb::str>(code->co_name));
2692 std::string_view funcName(name);
2693 int startLine = PyFrame_GetLineNumber(pyFrame);
2699 nb::cast<std::string>(nb::borrow<nb::str>(code->co_qualname));
2700 std::string_view funcName(name);
2701 int startLine, startCol, endLine, endCol;
2702 int lasti = PyFrame_GetLasti(pyFrame);
2703 if (!PyCode_Addr2Location(code, lasti, &startLine, &startCol, &endLine,
2705 throw nb::python_error();
2709 startCol, endLine, endCol);
2718 Py_XDECREF(pyFrame);
2723 MlirLocation callee = frames[0];
2728 MlirLocation caller = frames[count - 1];
2730 for (
int i = count - 2; i >= 1; i--)
2738maybeGetTracebackLocation(
const std::optional<PyLocation> &location) {
2739 if (location.has_value())
2740 return location.value();
2745 MlirLocation mlirLoc = tracebackToLocation(ctx.
get());
2747 return {ref, mlirLoc};
2759 std::string s = nb::cast<std::string>(nb::str(accum.
join()));
2760 std::string_view sv(s);
2761 if (sv.size() > 5) {
2762 sv.remove_prefix(4);
2763 sv.remove_suffix(1);
2765 return std::string(sv);
2767 auto indent = [](std::string s) {
2769 while ((pos = s.find(
'\n', pos)) != std::string::npos) {
2770 s.replace(pos, 1,
"\n ");
2776 std::ostringstream os;
2781 os <<
"\nerror: " << locStr(
diag.location) <<
": " << indent(
diag.message);
2782 for (
const auto ¬e :
diag.notes) {
2783 os <<
"\n note: " << locStr(note.location) <<
": "
2784 << indent(note.message);
2791 auto cls = nb::exception<MLIRError>(m,
"MLIRError", PyExc_Exception);
2792 nb::register_exception_translator(
2793 [](
const std::exception_ptr &p,
void *payload) {
2796 std::rethrow_exception(p);
2799 nb::object ty = nb::borrow(
static_cast<PyObject *
>(payload));
2800 nb::object obj = ty(formatted);
2801 obj.attr(
"_message") = nb::cast(std::move(e.
message));
2802 obj.attr(
"_error_diagnostics") =
2804 PyErr_SetObject(
static_cast<PyObject *
>(payload), obj.ptr());
2808 auto propertyType = nb::borrow<nb::type_object>(
2809 reinterpret_cast<PyObject *
>(&PyProperty_Type));
2812 propertyType(nb::cpp_function(
2813 [](nb::object self) -> nb::str {
return self.attr(
"_message"); },
2815 nb::setattr(cls,
"error_diagnostics",
2816 propertyType(nb::cpp_function(
2818 -> nb::typed<nb::list, PyDiagnostic::DiagnosticInfo> {
2819 return self.attr(
"_error_diagnostics");
2825 m.attr(
"T") = nb::type_var(
"T");
2826 m.attr(
"U") = nb::type_var(
"U");
2828 nb::class_<PyGlobals>(m,
"_Globals")
2829 .def_prop_rw(
"dialect_search_modules",
2835 "_check_dialect_module_loaded",
2836 [](
PyGlobals &self,
const std::string &dialectNamespace) {
2839 "dialect_namespace"_a)
2841 "dialect_namespace"_a,
"dialect_class"_a, nb::kw_only(),
2842 "replace"_a =
false,
2843 "Testing hook for directly registering a dialect")
2845 "operation_name"_a,
"operation_class"_a, nb::kw_only(),
2846 "replace"_a =
false,
2847 "Testing hook for directly registering an operation")
2848 .def(
"loc_tracebacks_enabled",
2852 .def(
"set_loc_tracebacks_enabled",
2856 .def(
"loc_tracebacks_frame_limit",
2860 .def(
"set_loc_tracebacks_frame_limit",
2861 [](
PyGlobals &self, std::optional<int> n) {
2865 .def(
"register_traceback_file_inclusion",
2866 [](
PyGlobals &self,
const std::string &filename) {
2869 .def(
"register_traceback_file_exclusion",
2870 [](
PyGlobals &self,
const std::string &filename) {
2877 m.attr(
"globals") = nb::cast(
new PyGlobals, nb::rv_policy::take_ownership);
2882 [](nb::type_object pyClass) {
2883 std::string dialectNamespace =
2884 nb::cast<std::string>(pyClass.attr(
"DIALECT_NAMESPACE"));
2889 "Class decorator for registering a custom Dialect wrapper");
2891 "register_operation",
2892 [](
const nb::type_object &dialectClass,
bool replace) -> nb::object {
2893 return nb::cpp_function(
2895 replace](nb::type_object opClass) -> nb::type_object {
2896 std::string operationName =
2897 nb::cast<std::string>(opClass.attr(
"OPERATION_NAME"));
2901 nb::object opClassName = opClass.attr(
"__name__");
2902 dialectClass.attr(opClassName) = opClass;
2907 nb::sig(
"def register_operation(dialect_class: type, *, replace: bool = False) "
2908 "-> typing.Callable[[type[T]], type[T]]"),
2910 "dialect_class"_a, nb::kw_only(),
"replace"_a =
false,
2911 "Produce a class decorator for registering an Operation class as part of "
2914 "register_op_adaptor",
2915 [](
const nb::type_object &opClass,
bool replace) -> nb::object {
2916 return nb::cpp_function(
2918 replace](nb::type_object adaptorClass) -> nb::type_object {
2919 std::string operationName =
2920 nb::cast<std::string>(adaptorClass.attr(
"OPERATION_NAME"));
2922 adaptorClass, replace);
2924 opClass.attr(
"Adaptor") = adaptorClass;
2925 return adaptorClass;
2929 nb::sig(
"def register_op_adaptor(op_class: type, *, replace: bool = False) "
2930 "-> typing.Callable[[type[T]], type[T]]"),
2932 "op_class"_a, nb::kw_only(),
"replace"_a =
false,
2933 "Produce a class decorator for registering an OpAdaptor class for an "
2937 [](
PyTypeID mlirTypeID,
bool replace) -> nb::object {
2938 return nb::cpp_function([mlirTypeID, replace](
2939 nb::callable typeCaster) -> nb::object {
2945 nb::sig(
"def register_type_caster(typeid: _mlir.ir.TypeID, *, replace: bool = False) "
2946 "-> typing.Callable[[typing.Callable[[T], U]], typing.Callable[[T], U]]"),
2948 "typeid"_a, nb::kw_only(),
"replace"_a =
false,
2949 "Register a type caster for casting MLIR types to custom user types.");
2952 [](
PyTypeID mlirTypeID,
bool replace) -> nb::object {
2953 return nb::cpp_function(
2954 [mlirTypeID, replace](nb::callable valueCaster) -> nb::object {
2961 nb::sig(
"def register_value_caster(typeid: _mlir.ir.TypeID, *, replace: bool = False) "
2962 "-> typing.Callable[[typing.Callable[[T], U]], typing.Callable[[T], U]]"),
2964 "typeid"_a, nb::kw_only(),
"replace"_a =
false,
2965 "Register a value caster for casting MLIR values to custom user values.");
2975 nb::enum_<PyDiagnosticSeverity>(m,
"DiagnosticSeverity")
2981 nb::enum_<PyWalkOrder>(m,
"WalkOrder")
2984 nb::enum_<PyWalkResult>(m,
"WalkResult")
2992 nb::class_<PyDiagnostic>(m,
"Diagnostic")
2994 "Returns the severity of the diagnostic.")
2996 "Returns the location associated with the diagnostic.")
2998 "Returns the message text of the diagnostic.")
3000 "Returns a tuple of attached note diagnostics.")
3005 return nb::str(
"<Invalid Diagnostic>");
3008 "Returns the diagnostic message as a string.");
3010 nb::class_<PyDiagnostic::DiagnosticInfo>(m,
"DiagnosticInfo")
3016 "diag"_a,
"Creates a DiagnosticInfo from a Diagnostic.")
3018 "The severity level of the diagnostic.")
3020 "The location associated with the diagnostic.")
3022 "The message text of the diagnostic.")
3024 "List of attached note diagnostics.")
3028 "Returns the diagnostic message as a string.");
3030 nb::class_<PyDiagnosticHandler>(m,
"DiagnosticHandler")
3032 "Detaches the diagnostic handler from the context.")
3034 "Returns True if the handler is attached to a context.")
3036 "Returns True if an error was encountered during diagnostic "
3039 "Enters the diagnostic handler as a context manager.",
3040 nb::sig(
"def __enter__(self, /) -> DiagnosticHandler"))
3042 "exc_value"_a.none(),
"traceback"_a.none(),
3043 "Exits the diagnostic handler context manager.");
3046 nb::class_<PyThreadPool>(m,
"ThreadPool")
3049 "Creates a new thread pool with default concurrency.")
3051 "Returns the maximum number of threads in the pool.")
3053 "Returns the raw pointer to the LLVM thread pool as a string.");
3055 nb::class_<PyMlirContext>(m,
"Context")
3063 Creates a new MLIR context.
3065 The context is the top-level container for all MLIR objects. It owns the storage
3066 for types, attributes, locations, and other core IR objects. A context can be
3067 configured to allow or disallow unregistered dialects and can have dialects
3068 loaded on-demand.)")
3070 "Gets the number of live Context objects.")
3072 "_get_context_again",
3073 [](
PyMlirContext &self) -> nb::typed<nb::object, PyMlirContext> {
3077 "Gets another reference to the same context.")
3079 "Gets the number of live modules owned by this context.")
3081 "Gets a capsule wrapping the MlirContext.")
3084 "Creates a Context from a capsule wrapping MlirContext.")
3086 "Enters the context as a context manager.",
3087 nb::sig(
"def __enter__(self, /) -> Context"))
3089 "exc_value"_a.none(),
"traceback"_a.none(),
3090 "Exits the context manager.")
3091 .def_prop_ro_static(
3094 -> std::optional<nb::typed<nb::object, PyMlirContext>> {
3098 return nb::cast(context);
3100 nb::sig(
"def current(/) -> Context | None"),
3101 "Gets the Context bound to the current thread or returns None if no "
3106 "Gets a container for accessing dialects by name.")
3109 "Alias for `dialects`.")
3111 "get_dialect_descriptor",
3114 self.get(), {name.data(), name.size()});
3116 throw nb::value_error(
3117 join(
"Dialect '", name,
"' not found").c_str());
3122 "Gets or loads a dialect by name, returning its descriptor object.")
3124 "allow_unregistered_dialects",
3131 "Controls whether unregistered dialects are allowed in this context.")
3134 "Attaches a diagnostic handler that will receive callbacks.")
3136 "enable_multithreading",
3142 Enables or disables multi-threading support in the context.
3145 enable: Whether to enable (True) or disable (False) multi-threading.
3157 Sets a custom thread pool for the context to use.
3160 pool: A ThreadPool object to use for parallel operations.
3163 Multi-threading is automatically disabled before setting the thread pool.)")
3169 "Gets the number of threads in the context's thread pool.")
3171 "_mlir_thread_pool_ptr",
3174 std::stringstream ss;
3178 "Gets the raw pointer to the LLVM thread pool as a string.")
3180 "is_registered_operation",
3187 Checks whether an operation with the given name is registered.
3190 operation_name: The fully qualified name of the operation (e.g., `arith.addf`).
3193 True if the operation is registered, False otherwise.)")
3195 "append_dialect_registry",
3201 Appends the contents of a dialect registry to the context.
3204 registry: A DialectRegistry containing dialects to append.)")
3205 .def_prop_rw("emit_error_diagnostics",
3209 Controls whether error diagnostics are emitted to diagnostic handlers.
3211 By default, error diagnostics are captured and reported through MLIRError exceptions.)")
3213 "load_all_available_dialects",
3218 Loads all dialects available in the registry into the context.
3220 This eagerly loads all dialects that have been registered, making them
3221 immediately available for use.)");
3226 nb::class_<PyDialectDescriptor>(m,
"DialectDescriptor")
3233 "Returns the namespace of the dialect.")
3238 std::string repr(
"<DialectDescriptor ");
3243 nb::sig(
"def __repr__(self) -> str"),
3244 "Returns a string representation of the dialect descriptor.");
3249 nb::class_<PyDialects>(m,
"Dialects")
3253 MlirDialect dialect =
3254 self.getDialectForKey(keyName,
false);
3255 nb::object descriptor =
3259 "Gets a dialect by name using subscript notation.")
3262 [=](
PyDialects &self, std::string attrName) {
3263 MlirDialect dialect =
3264 self.getDialectForKey(attrName,
true);
3265 nb::object descriptor =
3269 "Gets a dialect by name using attribute notation.");
3274 nb::class_<PyDialect>(m,
"Dialect")
3275 .def(nb::init<nb::object>(),
"descriptor"_a,
3276 "Creates a Dialect from a DialectDescriptor.")
3278 "descriptor", [](
PyDialect &self) {
return self.getDescriptor(); },
3279 "Returns the DialectDescriptor for this dialect.")
3282 [](
const nb::object &self) {
3283 auto clazz = self.attr(
"__class__");
3284 return nb::str(
"<Dialect ") +
3285 self.attr(
"descriptor").attr(
"namespace") +
3286 nb::str(
" (class ") + clazz.attr(
"__module__") +
3287 nb::str(
".") + clazz.attr(
"__name__") + nb::str(
")>");
3289 nb::sig(
"def __repr__(self) -> str"),
3290 "Returns a string representation of the dialect.");
3295 nb::class_<PyDialectRegistry>(m,
"DialectRegistry")
3297 "Gets a capsule wrapping the MlirDialectRegistry.")
3300 "Creates a DialectRegistry from a capsule wrapping "
3301 "`MlirDialectRegistry`.")
3302 .def(nb::init<>(),
"Creates a new empty dialect registry.");
3307 nb::class_<PyLocation>(m,
"Location")
3309 "Gets a capsule wrapping the MlirLocation.")
3311 "Creates a Location from a capsule wrapping MlirLocation.")
3313 "Enters the location as a context manager.",
3314 nb::sig(
"def __enter__(self, /) -> Location"))
3316 "exc_value"_a.none(),
"traceback"_a.none(),
3317 "Exits the location context manager.")
3323 "Compares two locations for equality.")
3325 "__eq__", [](
PyLocation &self, nb::object other) {
return false; },
3326 "Compares location with non-location object (always returns False).")
3327 .def_prop_ro_static(
3329 [](nb::object & ) -> std::optional<PyLocation *> {
3332 return std::nullopt;
3336 nb::sig(
"def current(/) -> Location | None"),
3338 "Gets the Location bound to the current thread or raises ValueError.")
3345 "context"_a = nb::none(),
3346 "Gets a Location representing an unknown location.")
3349 [](
PyLocation callee,
const std::vector<PyLocation> &frames,
3352 throw nb::value_error(
"No caller frames provided.");
3353 MlirLocation caller = frames.back().get();
3354 for (
size_t index = frames.size() - 1;
index-- > 0;) {
3360 "callee"_a,
"frames"_a,
"context"_a = nb::none(),
3361 "Gets a Location representing a caller and callsite.")
3363 "Returns True if this location is a CallSiteLoc.")
3370 "Gets the callee location from a CallSiteLoc.")
3377 "Gets the caller location from a CallSiteLoc.")
3380 [](std::string filename,
int line,
int col,
3387 "filename"_a,
"line"_a,
"col"_a,
"context"_a = nb::none(),
3388 "Gets a Location representing a file, line and column.")
3391 [](std::string filename,
int startLine,
int startCol,
int endLine,
3396 startLine, startCol, endLine, endCol));
3398 "filename"_a,
"start_line"_a,
"start_col"_a,
"end_line"_a,
3399 "end_col"_a,
"context"_a = nb::none(),
3400 "Gets a Location representing a file, line and column range.")
3402 "Returns True if this location is a FileLineColLoc.")
3409 "Gets the filename from a FileLineColLoc.")
3411 "Gets the start line number from a `FileLineColLoc`.")
3413 "Gets the start column number from a `FileLineColLoc`.")
3415 "Gets the end line number from a `FileLineColLoc`.")
3417 "Gets the end column number from a `FileLineColLoc`.")
3420 [](
const std::vector<PyLocation> &pyLocations,
3421 std::optional<PyAttribute> metadata,
3423 std::vector<MlirLocation> locations;
3424 locations.reserve(pyLocations.size());
3425 for (
const PyLocation &pyLocation : pyLocations)
3426 locations.push_back(pyLocation.get());
3428 context->
get(), locations.size(), locations.data(),
3429 metadata ? metadata->
get() : MlirAttribute{0});
3430 return PyLocation(context->getRef(), location);
3432 "locations"_a,
"metadata"_a = nb::none(),
"context"_a = nb::none(),
3433 "Gets a Location representing a fused location with optional "
3436 "Returns True if this location is a `FusedLoc`.")
3441 std::vector<MlirLocation> locations(numLocations);
3444 std::vector<PyLocation> pyLocations{};
3445 pyLocations.reserve(numLocations);
3446 for (
unsigned i = 0; i < numLocations; ++i)
3447 pyLocations.emplace_back(self.getContext(), locations[i]);
3450 "Gets the list of locations from a `FusedLoc`.")
3453 [](std::string name, std::optional<PyLocation> childLoc,
3459 childLoc ? childLoc->get()
3462 "name"_a,
"childLoc"_a = nb::none(),
"context"_a = nb::none(),
3463 "Gets a Location representing a named location with optional child "
3466 "Returns True if this location is a `NameLoc`.")
3472 "Gets the name string from a `NameLoc`.")
3479 "Gets the child location from a `NameLoc`.")
3486 "attribute"_a,
"context"_a = nb::none(),
3487 "Gets a Location from a `LocationAttr`.")
3490 [](
PyLocation &self) -> nb::typed<nb::object, PyMlirContext> {
3491 return self.getContext().getObject();
3493 "Context that owns the `Location`.")
3500 "Get the underlying `LocationAttr`.")
3508 Emits an error diagnostic at this location.
3511 message: The error message to emit.)")
3518 return printAccum.
join();
3520 "Returns the assembly representation of the location.");
3525 nb::class_<PyModule>(m,
"Module", nb::is_weak_referenceable())
3527 "Gets a capsule wrapping the MlirModule.")
3530 Creates a Module from a `MlirModule` wrapped by a capsule (i.e. `module._CAPIPtr`).
3532 This returns a new object **BUT** `_clear_mlir_module(module)` must be called to
3533 prevent double-frees (of the underlying `mlir::Module`).)")
3536 Clears the internal MLIR module reference.
3538 This is used internally to prevent double-free when ownership is transferred
3539 via the C API capsule mechanism. Not intended for normal use.)")
3543 -> nb::typed<nb::object, PyModule> {
3547 if (mlirModuleIsNull(module))
3548 throw MLIRError(
"Unable to parse module assembly", errors.
take());
3555 -> nb::typed<nb::object, PyModule> {
3559 if (mlirModuleIsNull(module))
3560 throw MLIRError(
"Unable to parse module assembly", errors.
take());
3567 -> nb::typed<nb::object, PyModule> {
3571 if (mlirModuleIsNull(module))
3572 throw MLIRError(
"Unable to parse module assembly", errors.
take());
3578 [](
const std::optional<PyLocation> &loc)
3579 -> nb::typed<nb::object, PyModule> {
3580 PyLocation pyLoc = maybeGetTracebackLocation(loc);
3584 "loc"_a = nb::none(),
"Creates an empty module.")
3587 [](
PyModule &self) -> nb::typed<nb::object, PyMlirContext> {
3588 return self.getContext().getObject();
3590 "Context that created the `Module`.")
3593 [](
PyModule &self) -> nb::typed<nb::object, PyOperation> {
3596 self.getRef().releaseObject())
3599 "Accesses the module as an operation.")
3605 self.getRef().releaseObject());
3609 "Return the block for this module.")
3618 [](
const nb::object &self) {
3620 return self.attr(
"operation").attr(
"__str__")();
3622 nb::sig(
"def __str__(self) -> str"),
3624 Gets the assembly form of the operation with default options.
3626 If more advanced control over the assembly formatting or I/O options is needed,
3627 use the dedicated print or get_asm method, which supports keyword arguments to
3635 "other"_a,
"Compares two modules for equality.")
3639 "Returns the hash value of the module.");
3644 nb::class_<PyOperationBase>(m,
"_OperationBase")
3648 return self.getOperation().getCapsule();
3650 "Gets a capsule wrapping the `MlirOperation`.")
3655 other.getOperation().
get());
3657 "Compares two operations for equality.")
3661 "Compares operation with non-operation object (always returns "
3668 "Returns the hash value of the operation.")
3674 "Returns a dictionary-like map of operation attributes.")
3678 PyOperation &concreteOperation = self.getOperation();
3682 "Context that owns the operation.")
3686 auto &concreteOperation = self.getOperation();
3687 concreteOperation.checkValid();
3688 MlirOperation operation = concreteOperation.
get();
3691 "Returns the fully qualified name of the operation.")
3697 "Returns the list of operation operands.")
3703 "Returns the list of op operands.")
3709 "Returns the list of operation regions.")
3715 "Returns the list of Operation results.")
3719 auto &operation = self.getOperation();
3723 "Shortcut to get an op result if it has only one (throws an error "
3736 nb::for_getter(
"Returns the source location the operation was "
3737 "defined or derived from."),
3738 nb::for_setter(
"Sets the source location the operation was defined "
3739 "or derived from."))
3743 -> std::optional<nb::typed<nb::object, PyOperation>> {
3744 auto parent = self.getOperation().getParentOperation();
3746 return parent->getObject();
3749 "Returns the parent operation, or `None` if at top level.")
3753 return self.getAsm(
false,
3764 nb::sig(
"def __str__(self) -> str"),
3765 "Returns the assembly form of the operation.")
3767 nb::overload_cast<PyAsmState &, nb::object, bool>(
3769 "state"_a,
"file"_a = nb::none(),
"binary"_a =
false,
3771 Prints the assembly form of the operation to a file like object.
3774 state: `AsmState` capturing the operation numbering and flags.
3775 file: Optional file like object to write to. Defaults to sys.stdout.
3776 binary: Whether to write `bytes` (True) or `str` (False). Defaults to False.)")
3778 nb::overload_cast<std::optional<int64_t>, std::optional<int64_t>,
3779 bool,
bool,
bool,
bool,
bool,
bool, nb::object,
3782 "large_elements_limit"_a = nb::none(),
3783 "large_resource_limit"_a = nb::none(),
"enable_debug_info"_a =
false,
3784 "pretty_debug_info"_a =
false,
"print_generic_op_form"_a =
false,
3785 "use_local_scope"_a =
false,
"use_name_loc_as_prefix"_a =
false,
3786 "assume_verified"_a =
false,
"file"_a = nb::none(),
3787 "binary"_a =
false,
"skip_regions"_a =
false,
3789 Prints the assembly form of the operation to a file like object.
3792 large_elements_limit: Whether to elide elements attributes above this
3793 number of elements. Defaults to None (no limit).
3794 large_resource_limit: Whether to elide resource attributes above this
3795 number of characters. Defaults to None (no limit). If large_elements_limit
3796 is set and this is None, the behavior will be to use large_elements_limit
3797 as large_resource_limit.
3798 enable_debug_info: Whether to print debug/location information. Defaults
3800 pretty_debug_info: Whether to format debug information for easier reading
3801 by a human (warning: the result is unparseable). Defaults to False.
3802 print_generic_op_form: Whether to print the generic assembly forms of all
3803 ops. Defaults to False.
3804 use_local_scope: Whether to print in a way that is more optimized for
3805 multi-threaded access but may not be consistent with how the overall
3807 use_name_loc_as_prefix: Whether to use location attributes (NameLoc) as
3808 prefixes for the SSA identifiers. Defaults to False.
3809 assume_verified: By default, if not printing generic form, the verifier
3810 will be run and if it fails, generic form will be printed with a comment
3811 about failed verification. While a reasonable default for interactive use,
3812 for systematic use, it is often better for the caller to verify explicitly
3813 and report failures in a more robust fashion. Set this to True if doing this
3814 in order to avoid running a redundant verification. If the IR is actually
3815 invalid, behavior is undefined.
3816 file: The file like object to write to. Defaults to sys.stdout.
3817 binary: Whether to write bytes (True) or str (False). Defaults to False.
3818 skip_regions: Whether to skip printing regions. Defaults to False.)")
3820 "desired_version"_a = nb::none(),
3822 Write the bytecode form of the operation to a file like object.
3825 file: The file like object to write to.
3826 desired_version: Optional version of bytecode to emit.
3828 The bytecode writer status.)")
3831 "binary"_a =
false,
"large_elements_limit"_a = nb::none(),
3832 "large_resource_limit"_a = nb::none(),
"enable_debug_info"_a =
false,
3833 "pretty_debug_info"_a =
false,
"print_generic_op_form"_a =
false,
3834 "use_local_scope"_a =
false,
"use_name_loc_as_prefix"_a =
false,
3835 "assume_verified"_a =
false,
"skip_regions"_a =
false,
3837 Gets the assembly form of the operation with all options available.
3840 binary: Whether to return a bytes (True) or str (False) object. Defaults to
3842 ... others ...: See the print() method for common keyword arguments for
3843 configuring the printout.
3845 Either a bytes or str object, depending on the setting of the `binary`
3848 "Verify the operation. Raises MLIRError if verification fails, and "
3849 "returns true otherwise.")
3851 "Puts self immediately after the other operation in its parent "
3854 "Puts self immediately before the other operation in its parent "
3858 Checks if this operation is before another in the same block.
3861 other: Another operation in the same parent block.
3864 True if this operation is before `other` in the operation list of the parent block.)")
3868 const nb::object &ip) -> nb::typed<nb::object, PyOperation> {
3869 return self.getOperation().clone(ip);
3871 "ip"_a = nb::none(),
3873 Creates a deep copy of the operation.
3876 ip: Optional insertion point where the cloned operation should be inserted.
3877 If None, the current insertion point is used. If False, the operation
3881 A new Operation that is a clone of this operation.)")
3883 "detach_from_parent",
3888 throw nb::value_error(
"Detached operation has no parent.");
3893 "Detaches the operation from its parent block.")
3901 "Reports if the operation is attached to its parent block.")
3905 Erases the operation and frees its memory.
3908 After erasing, any Python references to the operation become invalid.)")
3913 PyWalkOrder walkOrder, std::optional<nb::object> opClass) {
3915 return self.walk(callback, walkOrder);
3920 self.getOperation().getContext(), mlirOp)
3922 if (nb::isinstance(opview, *opClass))
3923 return callback(mlirOp);
3929 "op_class"_a = nb::none(),
3931 nb::sig(
"def walk(self, callback: Callable[[Operation], WalkResult], walk_order: WalkOrder = ..., op_class: type[OpView] | None = None) -> None"),
3934 Walks the operation tree with a callback function.
3936 If op_class is provided, the callback is only invoked on operations
3937 of that type; all other operations are skipped silently.
3940 callback: A callable that takes an Operation and returns a WalkResult.
3941 walk_order: The order of traversal (PRE_ORDER or POST_ORDER).
3942 op_class: If provided, only operations of this type are passed to the callback.)")
3948 MlirIdentifier opName =
3952 self.getOperation().getContext()->get());
3954 "trait_cls"_a,
"Checks if the operation has a given trait.");
3956 nb::class_<PyOperation, PyOperationBase>(m,
"Operation")
3959 [](std::string_view name,
3960 std::optional<std::vector<PyType *>> results,
3961 std::optional<std::vector<PyValue *>> operands,
3962 std::optional<nb::typed<nb::dict, nb::str, PyAttribute>>
3964 std::optional<std::vector<PyBlock *>> successors,
int regions,
3965 const std::optional<PyLocation> &location,
3966 const nb::object &maybeIp,
3967 bool inferType) -> nb::typed<nb::object, PyOperation> {
3969 std::vector<MlirValue> mlirOperands;
3971 mlirOperands.reserve(operands->size());
3972 for (
PyValue *operand : *operands) {
3974 throw nb::value_error(
"operand value cannot be None");
3975 mlirOperands.push_back(operand->get());
3979 PyLocation pyLoc = maybeGetTracebackLocation(location);
3981 name, results, mlirOperands.data(), mlirOperands.size(),
3982 attributes, successors, regions, pyLoc, maybeIp, inferType);
3984 "name"_a,
"results"_a = nb::none(),
"operands"_a = nb::none(),
3985 "attributes"_a = nb::none(),
"successors"_a = nb::none(),
3986 "regions"_a = 0,
"loc"_a = nb::none(),
"ip"_a = nb::none(),
3987 "infer_type"_a =
false,
3989 Creates a new operation.
3992 name: Operation name (e.g. `dialect.operation`).
3993 results: Optional sequence of Type representing op result types.
3994 operands: Optional operands of the operation.
3995 attributes: Optional Dict of {str: Attribute}.
3996 successors: Optional List of Block for the operation's successors.
3997 regions: Number of regions to create (default = 0).
3998 location: Optional Location object (defaults to resolve from context manager).
3999 ip: Optional InsertionPoint (defaults to resolve from context manager or set to False to disable insertion, even with an insertion point set in the context manager).
4000 infer_type: Whether to infer result types (default = False).
4002 A new detached Operation object. Detached operations can be added to blocks, which causes them to become attached.)")
4005 [](
const std::string &sourceStr,
const std::string &sourceName,
4007 -> nb::typed<nb::object, PyOpView> {
4011 "source"_a, nb::kw_only(),
"source_name"_a =
"",
4012 "context"_a = nb::none(),
4013 "Parses an operation. Supports both text assembly format and binary "
4016 "Gets a capsule wrapping the MlirOperation.")
4019 "Creates an Operation from a capsule wrapping MlirOperation.")
4022 [](nb::object self) -> nb::typed<nb::object, PyOperation> {
4025 "Returns self (the operation).")
4028 [](
PyOperation &self) -> nb::typed<nb::object, PyOpView> {
4029 return self.createOpView();
4032 Returns an OpView of this operation.
4035 If the operation has a registered and loaded dialect then this OpView will
4036 be concrete wrapper class.)")
4038 "Returns the block containing this operation.")
4044 "Returns the list of Operation successors.")
4046 "replace_uses_of_with",
4051 "Replaces uses of the 'of' value with the 'with' value inside the "
4054 "Invalidate the operation.");
4057 nb::class_<PyOpView, PyOperationBase>(m,
"OpView")
4058 .def(nb::init<nb::typed<nb::object, PyOperation>>(),
"operation"_a)
4061 [](
PyOpView *self, std::string_view name,
4062 std::tuple<int, bool> opRegionSpec,
4063 nb::object operandSegmentSpecObj,
4064 nb::object resultSegmentSpecObj,
4065 std::optional<nb::sequence> resultTypeList,
4066 nb::sequence operandList,
4067 std::optional<nb::typed<nb::dict, nb::str, PyAttribute>>
4069 std::optional<std::vector<PyBlock *>> successors,
4070 std::optional<int> regions,
4071 const std::optional<PyLocation> &location,
4072 const nb::object &maybeIp) {
4073 PyLocation pyLoc = maybeGetTracebackLocation(location);
4075 name, opRegionSpec, operandSegmentSpecObj,
4076 resultSegmentSpecObj, resultTypeList, operandList,
4077 attributes, successors, regions, pyLoc, maybeIp));
4079 "name"_a,
"opRegionSpec"_a,
4080 "operandSegmentSpecObj"_a = nb::none(),
4081 "resultSegmentSpecObj"_a = nb::none(),
"results"_a = nb::none(),
4082 "operands"_a = nb::none(),
"attributes"_a = nb::none(),
4083 "successors"_a = nb::none(),
"regions"_a = nb::none(),
4084 "loc"_a = nb::none(),
"ip"_a = nb::none())
4087 [](
PyOpView &self) -> nb::typed<nb::object, PyOperation> {
4088 return self.getOperationObject();
4090 .def_prop_ro(
"opview",
4091 [](nb::object self) -> nb::typed<nb::object, PyOpView> {
4096 [](
PyOpView &self) {
return nb::str(self.getOperationObject()); })
4102 "Returns the list of Operation successors.")
4105 [](
PyOpView &self) { self.getOperation().setInvalid(); },
4106 "Invalidate the operation.");
4107 opViewClass.attr(
"_ODS_REGIONS") = nb::make_tuple(0,
true);
4108 opViewClass.attr(
"_ODS_OPERAND_SEGMENTS") = nb::none();
4109 opViewClass.attr(
"_ODS_RESULT_SEGMENTS") = nb::none();
4114 [](nb::handle cls, std::optional<nb::sequence> resultTypeList,
4115 nb::sequence operandList,
4116 std::optional<nb::typed<nb::dict, nb::str, PyAttribute>> attributes,
4117 std::optional<std::vector<PyBlock *>> successors,
4118 std::optional<int> regions, std::optional<PyLocation> location,
4119 const nb::object &maybeIp) {
4120 std::string name = nb::cast<std::string>(cls.attr(
"OPERATION_NAME"));
4121 std::tuple<int, bool> opRegionSpec =
4122 nb::cast<std::tuple<int, bool>>(cls.attr(
"_ODS_REGIONS"));
4123 nb::object operandSegmentSpec = cls.attr(
"_ODS_OPERAND_SEGMENTS");
4124 nb::object resultSegmentSpec = cls.attr(
"_ODS_RESULT_SEGMENTS");
4125 PyLocation pyLoc = maybeGetTracebackLocation(location);
4127 resultSegmentSpec, resultTypeList,
4128 operandList, attributes, successors,
4129 regions, pyLoc, maybeIp);
4131 "cls"_a,
"results"_a = nb::none(),
"operands"_a = nb::none(),
4132 "attributes"_a = nb::none(),
"successors"_a = nb::none(),
4133 "regions"_a = nb::none(),
"loc"_a = nb::none(),
"ip"_a = nb::none(),
4135 nb::sig(
"def build_generic(cls, results: Sequence[Type] | None = None, operands: Sequence[Value] | None = None, attributes: dict[str, Attribute] | None = None, successors: Sequence[Block] | None = None, regions: int | None = None, loc: Location | None = None, ip: InsertionPoint | None = None) -> typing.Self"),
4137 "Builds a specific, generated OpView based on class level attributes.");
4139 [](
const nb::object &cls,
const std::string &sourceStr,
4140 const std::string &sourceName,
4150 std::string clsOpName =
4151 nb::cast<std::string>(cls.attr(
"OPERATION_NAME"));
4154 std::string_view parsedOpName(identifier.
data, identifier.
length);
4155 if (clsOpName != parsedOpName)
4156 throw MLIRError(
join(
"Expected a '", clsOpName,
"' op, got: '",
4157 parsedOpName,
"'"));
4160 "cls"_a,
"source"_a, nb::kw_only(),
"source_name"_a =
"",
4161 "context"_a = nb::none(),
4163 nb::sig(
"def parse(cls, source: str, *, source_name: str = '', context: Context | None = None) -> typing.Self"),
4165 "Parses a specific, generated OpView based on class level attributes.");
4167 [](nb::object &self, nb::type_object &traitCls,
4171 std::string opName = nb::cast<std::string>(self.attr(
"OPERATION_NAME"));
4174 traitTypeID.
get(), context->
get());
4176 "cls"_a,
"trait_cls"_a,
"context"_a = nb::none(),
4177 "Checks if the operation has a given trait.");
4184 nb::class_<PyRegion>(m,
"Region")
4188 return PyBlockList(self.getParentOperation(), self.get());
4190 "Returns a forward-optimized sequence of blocks.")
4193 [](
PyRegion &self) -> nb::typed<nb::object, PyOpView> {
4194 return self.getParentOperation()->createOpView();
4196 "Returns the operation owning this region.")
4204 "Iterates over blocks in the region.")
4208 return self.get().ptr == other.
get().ptr;
4210 "Compares two regions for pointer equality.")
4212 "__eq__", [](
PyRegion &self, nb::object &other) {
return false; },
4213 "Compares region with non-region object (always returns False).");
4218 nb::class_<PyBlock>(m,
"Block")
4220 "Gets a capsule wrapping the MlirBlock.")
4223 [](
PyBlock &self) -> nb::typed<nb::object, PyOpView> {
4224 return self.getParentOperation()->createOpView();
4226 "Returns the owning operation of this block.")
4231 return PyRegion(self.getParentOperation(), region);
4233 "Returns the owning region of this block.")
4239 "Returns a list of block arguments.")
4248 Appends an argument of the specified type to the block.
4251 type: The type of the argument to add.
4252 loc: The source location for the argument.
4255 The newly added block argument.)")
4263 Erases the argument at the specified index.
4266 index: The index of the argument to erase.)")
4272 "Returns a forward-optimized sequence of operations.")
4275 [](
PyRegion &parent, nb::typed<nb::sequence, PyType> pyArgTypes,
4276 const std::optional<nb::typed<nb::sequence, PyLocation>>
4279 MlirBlock block =
createBlock(pyArgTypes, pyArgLocs);
4283 "parent"_a,
"arg_types"_a = nb::list(),
"arg_locs"_a = std::nullopt,
4284 "Creates and returns a new Block at the beginning of the given "
4285 "region (with given argument types and locations).")
4289 MlirBlock
b = self.get();
4296 Appends this block to a region.
4298 Transfers ownership if the block is currently owned by another region.
4301 region: The region to append the block to.)")
4304 [](
PyBlock &self,
const nb::args &pyArgTypes,
4305 const std::optional<nb::typed<nb::sequence, PyLocation>>
4309 createBlock(nb::cast<nb::sequence>(pyArgTypes), pyArgLocs);
4312 return PyBlock(self.getParentOperation(), block);
4314 "arg_types"_a, nb::kw_only(),
"arg_locs"_a = std::nullopt,
4315 "Creates and returns a new Block before this block "
4316 "(with given argument types and locations).")
4319 [](
PyBlock &self,
const nb::args &pyArgTypes,
4320 const std::optional<nb::typed<nb::sequence, PyLocation>>
4324 createBlock(nb::cast<nb::sequence>(pyArgTypes), pyArgLocs);
4327 return PyBlock(self.getParentOperation(), block);
4329 "arg_types"_a, nb::kw_only(),
"arg_locs"_a = std::nullopt,
4330 "Creates and returns a new Block after this block "
4331 "(with given argument types and locations).")
4336 MlirOperation firstOperation =
4341 "Iterates over operations in the block.")
4345 return self.get().ptr == other.
get().ptr;
4347 "Compares two blocks for pointer equality.")
4349 "__eq__", [](
PyBlock &self, nb::object &other) {
return false; },
4350 "Compares block with non-block object (always returns False).")
4352 "__hash__", [](
PyBlock &self) {
return hash(self.get().ptr); },
4353 "Returns the hash value of the block.")
4361 return printAccum.
join();
4363 "Returns the assembly form of the block.")
4373 self.getParentOperation().getObject());
4377 Appends an operation to this block.
4379 If the operation is currently in another block, it will be moved.
4382 operation: The operation to append to the block.)")
4388 "Returns the list of Block successors.")
4394 "Returns the list of Block predecessors.");
4400 nb::class_<PyInsertionPoint>(m,
"InsertionPoint")
4401 .def(nb::init<PyBlock &>(),
"block"_a,
4402 "Inserts after the last operation but still inside the block.")
4404 "Enters the insertion point as a context manager.",
4405 nb::sig(
"def __enter__(self, /) -> InsertionPoint"))
4407 "exc_value"_a.none(),
"traceback"_a.none(),
4408 "Exits the insertion point context manager.")
4409 .def_prop_ro_static(
4414 throw nb::value_error(
"No current InsertionPoint");
4417 nb::sig(
"def current(/) -> InsertionPoint"),
4418 "Gets the InsertionPoint bound to the current thread or raises "
4419 "ValueError if none has been set.")
4420 .def(nb::init<PyOperationBase &>(),
"beforeOperation"_a,
4421 "Inserts before a referenced operation.")
4424 Creates an insertion point at the beginning of a block.
4427 block: The block at whose beginning operations should be inserted.
4430 An InsertionPoint at the block's beginning.)")
4434 Creates an insertion point before a block's terminator.
4437 block: The block whose terminator to insert before.
4440 An InsertionPoint before the terminator.
4443 ValueError: If the block has no terminator.)")
4446 Creates an insertion point immediately after an operation.
4449 operation: The operation after which to insert.
4452 An InsertionPoint after the operation.)")
4455 Inserts an operation at this insertion point.
4458 operation: The operation to insert.)")
4461 "Returns the block that this `InsertionPoint` points to.")
4465 -> std::optional<nb::typed<nb::object, PyOperation>> {
4466 auto refOperation = self.getRefOperation();
4468 return refOperation->getObject();
4471 "The reference operation before which new operations are "
4472 "inserted, or None if the insertion point is at the end of "
4478 nb::class_<PyAttribute>(m,
"Attribute")
4481 .def(nb::init<PyAttribute &>(),
"cast_from_type"_a,
4482 "Casts the passed attribute to the generic `Attribute`.")
4484 "Gets a capsule wrapping the MlirAttribute.")
4487 "Creates an Attribute from a capsule wrapping `MlirAttribute`.")
4491 -> nb::typed<nb::object, PyAttribute> {
4495 if (mlirAttributeIsNull(attr))
4496 throw MLIRError(
"Unable to parse attribute", errors.
take());
4499 "asm"_a,
"context"_a = nb::none(),
4500 "Parses an attribute from an assembly form. Raises an `MLIRError` on "
4504 [](
PyAttribute &self) -> nb::typed<nb::object, PyMlirContext> {
4505 return self.getContext().getObject();
4507 "Context that owns the `Attribute`.")
4510 [](
PyAttribute &self) -> nb::typed<nb::object, PyType> {
4514 "Returns the type of the `Attribute`.")
4520 nb::keep_alive<0, 1>(),
4522 Binds a name to the attribute, creating a `NamedAttribute`.
4525 name: The name to bind to the `Attribute`.
4528 A `NamedAttribute` with the given name and this attribute.)")
4532 "Compares two attributes for equality.")
4534 "__eq__", [](
PyAttribute &self, nb::object &other) {
return false; },
4535 "Compares attribute with non-attribute object (always returns "
4539 "Returns the hash value of the attribute.")
4549 return printAccum.
join();
4551 "Returns the assembly form of the Attribute.")
4561 printAccum.
parts.append(
"Attribute(");
4564 printAccum.
parts.append(
")");
4565 return printAccum.
join();
4567 "Returns a string representation of the attribute.")
4573 "mlirTypeID was expected to be non-null.");
4576 "Returns the `TypeID` of the attribute.")
4579 [](
PyAttribute &self) -> nb::typed<nb::object, PyAttribute> {
4580 return self.maybeDownCast();
4582 "Downcasts the attribute to a more specific attribute if possible.");
4587 nb::class_<PyNamedAttribute>(m,
"NamedAttribute")
4592 printAccum.
parts.append(
"NamedAttribute(");
4593 printAccum.
parts.append(
4596 printAccum.
parts.append(
"=");
4600 printAccum.
parts.append(
")");
4601 return printAccum.
join();
4603 "Returns a string representation of the named attribute.")
4609 "The name of the `NamedAttribute` binding.")
4613 nb::keep_alive<0, 1>(), nb::sig(
"def attr(self) -> Attribute"),
4614 "The underlying generic attribute of the `NamedAttribute` binding.");
4619 nb::class_<PyType>(m,
"Type")
4622 .def(nb::init<PyType &>(),
"cast_from_type"_a,
4623 "Casts the passed type to the generic `Type`.")
4625 "Gets a capsule wrapping the `MlirType`.")
4627 "Creates a Type from a capsule wrapping `MlirType`.")
4630 [](std::string typeSpec,
4639 "asm"_a,
"context"_a = nb::none(),
4641 Parses the assembly form of a type.
4643 Returns a Type object or raises an `MLIRError` if the type cannot be parsed.
4645 See also: https://mlir.llvm.org/docs/LangRef/#type-system)")
4648 [](
PyType &self) -> nb::typed<nb::object, PyMlirContext> {
4649 return self.getContext().getObject();
4651 "Context that owns the `Type`.")
4653 "__eq__", [](
PyType &self,
PyType &other) {
return self == other; },
4654 "Compares two types for equality.")
4656 "__eq__", [](
PyType &self, nb::object &other) {
return false; },
4658 "Compares type with non-type object (always returns False).")
4660 "__hash__", [](
PyType &self) {
return hash(self.get().ptr); },
4661 "Returns the hash value of the `Type`.")
4670 return printAccum.
join();
4672 "Returns the assembly form of the `Type`.")
4681 printAccum.
parts.append(
"Type(");
4684 printAccum.
parts.append(
")");
4685 return printAccum.
join();
4687 "Returns a string representation of the `Type`.")
4690 [](
PyType &self) -> nb::typed<nb::object, PyType> {
4691 return self.maybeDownCast();
4693 "Downcasts the Type to a more specific `Type` if possible.")
4700 auto origRepr = nb::cast<std::string>(nb::repr(nb::cast(self)));
4701 throw nb::value_error(
join(origRepr,
" has no typeid.").c_str());
4703 "Returns the `TypeID` of the `Type`, or raises `ValueError` if "
4710 nb::class_<PyTypeID>(m,
"TypeID")
4712 "Gets a capsule wrapping the `MlirTypeID`.")
4714 "Creates a `TypeID` from a capsule wrapping `MlirTypeID`.")
4721 "Compares two `TypeID`s for equality.")
4724 [](
PyTypeID &self,
const nb::object &other) {
return false; },
4725 "Compares TypeID with non-TypeID object (always returns False).")
4734 "Returns the hash value of the `TypeID`.");
4739 m.attr(
"_T") = nb::type_var(
"_T",
"bound"_a = m.attr(
"Type"));
4741 nb::class_<PyValue>(m,
"Value", nb::is_generic(),
4742 nb::sig(
"class Value(typing.Generic[_T])"))
4743 .def(nb::init<PyValue &>(), nb::keep_alive<0, 1>(),
"value"_a,
4744 "Creates a Value reference from another `Value`.")
4746 "Gets a capsule wrapping the `MlirValue`.")
4748 "Creates a `Value` from a capsule wrapping `MlirValue`.")
4751 [](
PyValue &self) -> nb::typed<nb::object, PyMlirContext> {
4752 return self.getParentOperation()->getContext().getObject();
4754 "Context in which the value lives.")
4761 -> nb::typed<nb::object, std::variant<PyOpView, PyBlock>> {
4762 MlirValue v = self.get();
4766 "expected the owner of the value in Python to match "
4769 return self.getParentOperation()->createOpView();
4774 return nb::cast(
PyBlock(self.getParentOperation(), block));
4777 assert(
false &&
"Value must be a block argument or an op result");
4780 "Returns the owner of the value (`Operation` for results, `Block` "
4788 "Returns an iterator over uses of this value.")
4792 return self.get().ptr == other.
get().ptr;
4794 "Compares two values for pointer equality.")
4796 "__eq__", [](
PyValue &self, nb::object other) {
return false; },
4797 "Compares value with non-value object (always returns False).")
4799 "__hash__", [](
PyValue &self) {
return hash(self.get().ptr); },
4800 "Returns the hash value of the value.")
4805 printAccum.
parts.append(
"Value(");
4808 printAccum.
parts.append(
")");
4809 return printAccum.
join();
4812 Returns the string form of the value.
4814 If the value is a block argument, this is the assembly form of its type and the
4815 position in the argument list. If the value is an operation result, this is
4816 equivalent to printing the operation that produced it.
4820 [](
PyValue &self,
bool useLocalScope,
bool useNameLocAsPrefix) {
4825 if (useNameLocAsPrefix)
4827 MlirAsmState valueState =
4834 return printAccum.
join();
4836 "use_local_scope"_a =
false,
"use_name_loc_as_prefix"_a =
false,
4838 Returns the string form of value as an operand.
4841 use_local_scope: Whether to use local scope for naming.
4842 use_name_loc_as_prefix: Whether to use the location attribute (NameLoc) as prefix.
4845 The value's name as it appears in IR (e.g., `%0`, `%arg0`).)")
4850 MlirAsmState valueState = state.
get();
4854 return printAccum.
join();
4857 "Returns the string form of value as an operand (i.e., the ValueID).")
4861 return PyType(self.getParentOperation()->getContext(),
4865 "Returns the type of the value.", nb::sig(
"def type(self) -> _T"))
4871 "type"_a,
"Sets the type of the value.",
4872 nb::sig(
"def set_type(self, type: _T)"))
4874 "replace_all_uses_with",
4878 "Replace all uses of value with the new value, updating anything in "
4879 "the IR that uses `self` to use the other value instead.")
4881 "replace_all_uses_except",
4883 MlirOperation exceptedUser = exception.
get();
4888 "replace_all_uses_except",
4890 std::vector<PyOperation> &exceptions) {
4892 std::vector<MlirOperation> exceptionOps;
4894 exceptionOps.push_back(exception);
4896 self, with,
static_cast<intptr_t>(exceptionOps.size()),
4897 exceptionOps.data());
4902 [](
PyValue &self) {
return self.maybeDownCast(); },
4903 "Downcasts the `Value` to a more specific kind if possible.")
4911 "Returns the source location of the value.");
4917 nb::class_<PyAsmState>(m,
"AsmState")
4918 .def(nb::init<PyValue &, bool>(),
"value"_a,
"use_local_scope"_a =
false,
4920 Creates an `AsmState` for consistent SSA value naming.
4923 value: The value to create state for.
4924 use_local_scope: Whether to use local scope for naming.)")
4925 .def(nb::init<PyOperationBase &, bool>(), "op"_a,
4926 "use_local_scope"_a =
false,
4928 Creates an AsmState for consistent SSA value naming.
4931 op: The operation to create state for.
4932 use_local_scope: Whether to use local scope for naming.)");
4937 nb::class_<PySymbolTable>(m,
"SymbolTable")
4938 .def(nb::init<PyOperationBase &>(),
4940 Creates a symbol table for an operation.
4943 operation: The `Operation` that defines a symbol table (e.g., a `ModuleOp`).
4946 TypeError: If the operation is not a symbol table.)")
4950 const std::string &name) -> nb::typed<nb::object, PyOpView> {
4951 return self.dunderGetItem(name);
4954 Looks up a symbol by name in the symbol table.
4957 name: The name of the symbol to look up.
4960 The operation defining the symbol.
4963 KeyError: If the symbol is not found.)")
4966 Inserts a symbol operation into the symbol table.
4969 operation: An operation with a symbol name to insert.
4972 The symbol name attribute of the inserted operation.
4975 ValueError: If the operation does not have a symbol name.)")
4978 Erases a symbol operation from the symbol table.
4981 operation: The symbol operation to erase.
4984 The operation is also erased from the IR and invalidated.)")
4986 "Deletes a symbol by name from the symbol table.")
4993 "Checks if a symbol with the given name exists in the table.")
4996 "name"_a,
"Sets the symbol name for a symbol operation.")
4998 "Gets the symbol name from a symbol operation.")
5000 "Gets the visibility attribute of a symbol operation.")
5003 "Sets the visibility attribute of a symbol operation.")
5004 .def_static(
"replace_all_symbol_uses",
5006 "new_symbol"_a,
"from_op"_a,
5007 "Replaces all uses of a symbol with a new symbol name within "
5008 "the given operation.")
5010 "from_op"_a,
"all_sym_uses_visible"_a,
"callback"_a,
5011 "Walks symbol tables starting from an operation with a "
5012 "callback function.");
void mlirSetGlobalDebugTypes(const char **types, intptr_t n)
MLIR_CAPI_EXPORTED void mlirSetGlobalDebugType(const char *type)
Sets the current debug type, similarly to -debug-only=type in the command-line tools.
MLIR_CAPI_EXPORTED bool mlirIsGlobalDebugEnabled()
Retuns true if the global debugging flag is set, false otherwise.
MLIR_CAPI_EXPORTED void mlirEnableGlobalDebug(bool enable)
Sets the global debugging flag.
static const char kDumpDocstring[]
static const char kModuleParseDocstring[]
static size_t hash(const T &value)
Local helper to compute std::hash for a value.
static nb::object createCustomDialectWrapper(const std::string &dialectNamespace, nb::object dialectDescriptor)
std::string join(const Ts &...args)
Helper function to concatenate arguments into a std::string.
static const char kValueReplaceAllUsesExceptDocstring[]
MlirContext mlirModuleGetContext(MlirModule module)
size_t mlirModuleHashValue(MlirModule mod)
intptr_t mlirBlockGetNumPredecessors(MlirBlock block)
MlirIdentifier mlirOperationGetName(MlirOperation op)
bool mlirValueIsABlockArgument(MlirValue value)
intptr_t mlirOperationGetNumRegions(MlirOperation op)
MlirBlock mlirOperationGetBlock(MlirOperation op)
void mlirBlockArgumentSetType(MlirValue value, MlirType type)
void mlirOperationStateAddAttributes(MlirOperationState *state, intptr_t n, MlirNamedAttribute const *attributes)
MlirValue mlirOperationGetResult(MlirOperation op, intptr_t pos)
MlirModule mlirModuleCreateParseFromFile(MlirContext context, MlirStringRef fileName)
bool mlirOperationNameHasTrait(MlirStringRef opName, MlirTypeID traitTypeID, MlirContext context)
MlirAsmState mlirAsmStateCreateForValue(MlirValue value, MlirOpPrintingFlags flags)
intptr_t mlirOperationGetNumResults(MlirOperation op)
void mlirOperationDestroy(MlirOperation op)
MlirContext mlirAttributeGetContext(MlirAttribute attribute)
MlirType mlirValueGetType(MlirValue value)
void mlirBlockPrint(MlirBlock block, MlirStringCallback callback, void *userData)
MlirOpPrintingFlags mlirOpPrintingFlagsCreate()
bool mlirModuleEqual(MlirModule lhs, MlirModule rhs)
void mlirOpPrintingFlagsElideLargeElementsAttrs(MlirOpPrintingFlags flags, intptr_t largeElementLimit)
void mlirOperationSetSuccessor(MlirOperation op, intptr_t pos, MlirBlock block)
MlirOperation mlirOperationGetNextInBlock(MlirOperation op)
void mlirOpPrintingFlagsEnableDebugInfo(MlirOpPrintingFlags flags, bool enable, bool prettyForm)
MlirOperation mlirModuleGetOperation(MlirModule module)
void mlirOpPrintingFlagsElideLargeResourceString(MlirOpPrintingFlags flags, intptr_t largeResourceLimit)
void mlirOpPrintingFlagsUseLocalScope(MlirOpPrintingFlags flags)
intptr_t mlirBlockArgumentGetArgNumber(MlirValue value)
MlirBlock mlirOperationGetSuccessor(MlirOperation op, intptr_t pos)
bool mlirAttributeEqual(MlirAttribute a1, MlirAttribute a2)
MlirAsmState mlirAsmStateCreateForOperation(MlirOperation op, MlirOpPrintingFlags flags)
bool mlirOperationEqual(MlirOperation op, MlirOperation other)
void mlirOpPrintingFlagsAssumeVerified(MlirOpPrintingFlags flags)
void mlirBytecodeWriterConfigDestroy(MlirBytecodeWriterConfig config)
MlirBlock mlirBlockGetSuccessor(MlirBlock block, intptr_t pos)
void mlirModuleDestroy(MlirModule module)
MlirModule mlirModuleCreateEmpty(MlirLocation location)
void mlirOpPrintingFlagsPrintGenericOpForm(MlirOpPrintingFlags flags)
MlirOperation mlirOperationGetParentOperation(MlirOperation op)
void mlirValueSetType(MlirValue value, MlirType type)
intptr_t mlirOperationGetNumSuccessors(MlirOperation op)
MlirDialect mlirAttributeGetDialect(MlirAttribute attr)
void mlirLocationPrint(MlirLocation location, MlirStringCallback callback, void *userData)
void mlirOperationSetAttributeByName(MlirOperation op, MlirStringRef name, MlirAttribute attr)
void mlirOperationSetOperand(MlirOperation op, intptr_t pos, MlirValue newValue)
MlirOperation mlirOpResultGetOwner(MlirValue value)
MlirModule mlirModuleCreateParse(MlirContext context, MlirStringRef module)
size_t mlirOperationHashValue(MlirOperation op)
void mlirOperationStateAddResults(MlirOperationState *state, intptr_t n, MlirType const *results)
MlirOperation mlirOperationClone(MlirOperation op)
MlirBlock mlirBlockArgumentGetOwner(MlirValue value)
void mlirBlockArgumentSetLocation(MlirValue value, MlirLocation loc)
MlirValue mlirOperationGetOperand(MlirOperation op, intptr_t pos)
MlirOpOperand mlirOperationGetOpOperand(MlirOperation op, intptr_t pos)
MlirLocation mlirOperationGetLocation(MlirOperation op)
MlirAttribute mlirOperationGetAttributeByName(MlirOperation op, MlirStringRef name)
MlirTypeID mlirAttributeGetTypeID(MlirAttribute attr)
void mlirOperationStateAddOwnedRegions(MlirOperationState *state, intptr_t n, MlirRegion const *regions)
void mlirOperationSetLocation(MlirOperation op, MlirLocation loc)
MlirType mlirAttributeGetType(MlirAttribute attribute)
bool mlirOperationRemoveAttributeByName(MlirOperation op, MlirStringRef name)
bool mlirValueIsAOpResult(MlirValue value)
MlirBlock mlirBlockGetPredecessor(MlirBlock block, intptr_t pos)
MlirRegion mlirOperationGetRegion(MlirOperation op, intptr_t pos)
MlirOperation mlirOperationCreate(MlirOperationState *state)
void mlirBytecodeWriterConfigDesiredEmitVersion(MlirBytecodeWriterConfig flags, int64_t version)
MlirAttribute mlirAttributeParseGet(MlirContext context, MlirStringRef attr)
void mlirOperationRemoveFromParent(MlirOperation op)
intptr_t mlirBlockGetNumSuccessors(MlirBlock block)
MlirNamedAttribute mlirOperationGetAttribute(MlirOperation op, intptr_t pos)
void mlirOpPrintingFlagsDestroy(MlirOpPrintingFlags flags)
void mlirValueDump(MlirValue value)
void mlirTypePrint(MlirType type, MlirStringCallback callback, void *userData)
MlirBlock mlirModuleGetBody(MlirModule module)
MlirOperation mlirOperationCreateParse(MlirContext context, MlirStringRef sourceStr, MlirStringRef sourceName)
void mlirAsmStateDestroy(MlirAsmState state)
Destroys printing flags created with mlirAsmStateCreate.
MlirContext mlirOperationGetContext(MlirOperation op)
intptr_t mlirOpResultGetResultNumber(MlirValue value)
void mlirOperationStateAddSuccessors(MlirOperationState *state, intptr_t n, MlirBlock const *successors)
MlirBytecodeWriterConfig mlirBytecodeWriterConfigCreate()
void mlirOpPrintingFlagsPrintNameLocAsPrefix(MlirOpPrintingFlags flags)
void mlirOpPrintingFlagsSkipRegions(MlirOpPrintingFlags flags)
void mlirOperationStateAddOperands(MlirOperationState *state, intptr_t n, MlirValue const *operands)
MlirOperationState mlirOperationStateGet(MlirStringRef name, MlirLocation loc)
intptr_t mlirOperationGetNumOperands(MlirOperation op)
void mlirTypeDump(MlirType type)
intptr_t mlirOperationGetNumAttributes(MlirOperation op)
static PyObject * mlirPythonTypeIDToCapsule(MlirTypeID typeID)
Creates a capsule object encapsulating the raw C-API MlirTypeID.
static PyObject * mlirPythonContextToCapsule(MlirContext context)
Creates a capsule object encapsulating the raw C-API MlirContext.
#define MLIR_PYTHON_MAYBE_DOWNCAST_ATTR
Attribute on MLIR Python objects that expose a function for downcasting the corresponding Python obje...
static MlirOperation mlirPythonCapsuleToOperation(PyObject *capsule)
Extracts an MlirOperations from a capsule as produced from mlirPythonOperationToCapsule.
#define MLIR_PYTHON_CAPI_PTR_ATTR
Attribute on MLIR Python objects that expose their C-API pointer.
static MlirAttribute mlirPythonCapsuleToAttribute(PyObject *capsule)
Extracts an MlirAttribute from a capsule as produced from mlirPythonAttributeToCapsule.
static PyObject * mlirPythonTypeToCapsule(MlirType type)
Creates a capsule object encapsulating the raw C-API MlirType.
static PyObject * mlirPythonOperationToCapsule(MlirOperation operation)
Creates a capsule object encapsulating the raw C-API MlirOperation.
static PyObject * mlirPythonAttributeToCapsule(MlirAttribute attribute)
Creates a capsule object encapsulating the raw C-API MlirAttribute.
#define MLIR_PYTHON_CAPI_FACTORY_ATTR
Attribute on MLIR Python objects that exposes a factory function for constructing the corresponding P...
static MlirModule mlirPythonCapsuleToModule(PyObject *capsule)
Extracts an MlirModule from a capsule as produced from mlirPythonModuleToCapsule.
static MlirContext mlirPythonCapsuleToContext(PyObject *capsule)
Extracts a MlirContext from a capsule as produced from mlirPythonContextToCapsule.
static MlirTypeID mlirPythonCapsuleToTypeID(PyObject *capsule)
Extracts an MlirTypeID from a capsule as produced from mlirPythonTypeIDToCapsule.
#define MLIR_PYTHON_CAPI_VALUE_CASTER_REGISTER_ATTR
Attribute on main C extension module (_mlir) that corresponds to the value caster registration bindin...
static PyObject * mlirPythonBlockToCapsule(MlirBlock block)
Creates a capsule object encapsulating the raw C-API MlirBlock.
static PyObject * mlirPythonLocationToCapsule(MlirLocation loc)
Creates a capsule object encapsulating the raw C-API MlirLocation.
static MlirDialectRegistry mlirPythonCapsuleToDialectRegistry(PyObject *capsule)
Extracts an MlirDialectRegistry from a capsule as produced from mlirPythonDialectRegistryToCapsule.
static MlirType mlirPythonCapsuleToType(PyObject *capsule)
Extracts an MlirType from a capsule as produced from mlirPythonTypeToCapsule.
static MlirValue mlirPythonCapsuleToValue(PyObject *capsule)
Extracts an MlirValue from a capsule as produced from mlirPythonValueToCapsule.
static PyObject * mlirPythonValueToCapsule(MlirValue value)
Creates a capsule object encapsulating the raw C-API MlirValue.
static PyObject * mlirPythonModuleToCapsule(MlirModule module)
Creates a capsule object encapsulating the raw C-API MlirModule.
static MlirLocation mlirPythonCapsuleToLocation(PyObject *capsule)
Extracts an MlirLocation from a capsule as produced from mlirPythonLocationToCapsule.
#define MLIR_PYTHON_CAPI_TYPE_CASTER_REGISTER_ATTR
Attribute on main C extension module (_mlir) that corresponds to the type caster registration binding...
static PyObject * mlirPythonDialectRegistryToCapsule(MlirDialectRegistry registry)
Creates a capsule object encapsulating the raw C-API MlirDialectRegistry.
static std::string diag(const llvm::Value &value)
Accumulates into a file, either writing text (default) or binary.
A CRTP base class for pseudo-containers willing to support Python-type slicing access on top of index...
static void bind(nanobind::module_ &m)
Sliceable(intptr_t startIndex, intptr_t length, intptr_t step)
intptr_t wrapIndex(intptr_t index)
ReferrentTy * get() const
PyMlirContextRef & getContext()
Accesses the context reference.
BaseContextObject(PyMlirContextRef ref)
static PyLocation & resolve()
Used in function arguments when None should resolve to the current context manager set instance.
static PyMlirContext & resolve()
Wrapper around an MlirAsmState.
PyAsmState(MlirValue value, bool useLocalScope)
Wrapper around the generic MlirAttribute.
PyAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirAttribute.
MlirAttribute get() const
bool operator==(const PyAttribute &other) const
static PyAttribute createFromCapsule(const nanobind::object &capsule)
Creates a PyAttribute from the MlirAttribute wrapped by a capsule.
nanobind::typed< nanobind::object, PyAttribute > maybeDownCast()
A list of block arguments.
PyBlockArgumentList(PyOperationRef operation, MlirBlock block, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
static void bindDerived(ClassTy &c)
Python wrapper for MlirBlockArgument.
static void bindDerived(ClassTy &c)
PyBlockIterator & dunderIter()
nanobind::typed< nanobind::object, PyBlock > dunderNext()
static void bind(nanobind::module_ &m)
Blocks are exposed by the C-API as a forward-only linked list.
static void bind(nanobind::module_ &m)
PyBlockIterator dunderIter()
PyBlock appendBlock(const nanobind::args &pyArgTypes, const std::optional< nanobind::sequence > &pyArgLocs)
PyBlock dunderGetItem(intptr_t index)
A list of block predecessors.
PyBlockPredecessors(PyBlock block, PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
A list of block successors.
PyBlockSuccessors(PyBlock block, PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Wrapper around an MlirBlock.
PyOperationRef & getParentOperation()
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirBlock.
static void bind(nanobind::module_ &m)
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)
Python class mirroring the C MlirDiagnostic struct.
PyDiagnostic(MlirDiagnostic diagnostic)
nanobind::str getMessage()
PyDiagnosticSeverity getSeverity()
nanobind::typed< nanobind::tuple, PyDiagnostic > getNotes()
Wrapper around an MlirDialect.
Wrapper around an MlirDialectRegistry.
static PyDialectRegistry createFromCapsule(nanobind::object capsule)
nanobind::object getCapsule()
User-level dialect object.
User-level object for accessing dialects with dotted syntax such as: ctx.dialect.std.
MlirDialect getDialectForKey(const std::string &key, bool attrError)
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 void bind(nanobind::module_ &m)
static bool attach(const nanobind::object &opName, PyMlirContext &context)
size_t locTracebackFramesLimit()
void setLocTracebackFramesLimit(size_t value)
void registerTracebackFileExclusion(const std::string &file)
void registerTracebackFileInclusion(const std::string &file)
static constexpr size_t kMaxFrames
void setLocTracebacksEnabled(bool value)
bool locTracebacksEnabled()
Globals that are always accessible once the extension has been initialized.
void registerOpAdaptorImpl(const std::string &operationName, nanobind::object pyClass, bool replace=false)
Adds an operation adaptor class.
std::optional< nanobind::callable > lookupValueCaster(MlirTypeID mlirTypeID, MlirDialect dialect)
Returns the custom value caster for MlirTypeID mlirTypeID.
bool loadDialectModule(std::string_view dialectNamespace)
Loads a python module corresponding to the given dialect namespace.
void addDialectSearchPrefix(std::string value)
void registerDialectImpl(const std::string &dialectNamespace, nanobind::object pyClass, bool replace=false)
Adds a concrete implementation dialect class.
static PyGlobals & get()
Most code should get the globals via this static accessor.
std::optional< nanobind::object > lookupOperationClass(std::string_view operationName)
Looks up a registered operation class (deriving from OpView) by operation name.
void registerTypeCaster(MlirTypeID mlirTypeID, nanobind::callable typeCaster, bool replace=false)
Adds a user-friendly type caster.
void registerOperationImpl(const std::string &operationName, nanobind::object pyClass, bool replace=false)
Adds a concrete implementation operation class.
void setDialectSearchPrefixes(std::vector< std::string > newValues)
std::optional< nanobind::callable > lookupTypeCaster(MlirTypeID mlirTypeID, MlirDialect dialect)
Returns the custom type caster for MlirTypeID mlirTypeID.
void registerValueCaster(MlirTypeID mlirTypeID, nanobind::callable valueCaster, bool replace=false)
Adds a user-friendly value caster.
std::optional< nanobind::callable > lookupAttributeBuilder(const std::string &attributeKind)
Returns the custom Attribute builder for Attribute kind.
TracebackLoc & getTracebackLoc()
std::optional< nanobind::object > lookupDialectClass(const std::string &dialectNamespace)
Looks up a registered dialect class by namespace.
std::vector< std::string > getDialectSearchPrefixes()
Get and set the list of parent modules to search for dialect implementation classes.
void registerAttributeBuilder(const std::string &attributeKind, nanobind::callable pyFunc, bool replace=false, bool allow_existing=false)
Adds a user-friendly Attribute builder.
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.
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.
Wrapper around an MlirLocation.
static nanobind::object contextEnter(nanobind::object location)
Enter and exit the context manager.
static PyLocation createFromCapsule(nanobind::object capsule)
Creates a PyLocation from the MlirLocation wrapped by a capsule.
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirLocation.
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
PyLocation(PyMlirContextRef contextRef, MlirLocation loc)
static PyMlirContextRef forContext(MlirContext context)
Returns a context reference for the singleton PyMlirContext wrapper for the given context.
static size_t getLiveCount()
Gets the count of live context objects. Used for testing.
static nanobind::object createFromCapsule(nanobind::object capsule)
Creates a PyMlirContext from the MlirContext wrapped by a capsule.
nanobind::object attachDiagnosticHandler(nanobind::object callback)
Attaches a Python callback as a diagnostic handler, returning a registration object (internally a PyD...
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
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...
bool getEmitErrorDiagnostics()
void setEmitErrorDiagnostics(bool value)
Controls whether error diagnostics should be propagated to diagnostic handlers, instead of being capt...
static nanobind::object contextEnter(nanobind::object context)
Enter and exit the context manager.
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirContext.
size_t getLiveModuleCount()
Gets the count of live modules associated with this context.
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirModule.
PyModule(PyModule &)=delete
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.
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::object releaseObject()
Releases the object held by this instance, returning it.
nanobind::object getObject()
Base class of operation adaptors.
static void bind(nanobind::module_ &m)
A list of operation attributes.
PyOpAttributeMap(PyOperationRef operation)
void dunderDelItem(const std::string &name)
static void bind(nanobind::module_ &m)
void dunderSetItem(const std::string &name, const PyAttribute &attr)
bool dunderContains(const std::string &name)
nanobind::typed< nanobind::object, PyAttribute > dunderGetItemNamed(const std::string &name)
nanobind::typed< nanobind::object, std::optional< PyAttribute > > get(const std::string &key, nanobind::object defaultValue)
static void forEachAttr(MlirOperation op, std::function< void(MlirStringRef, MlirAttribute)> fn)
PyNamedAttribute dunderGetItemIndexed(intptr_t index)
nanobind::typed< nanobind::object, PyOpOperand > dunderNext()
PyOpOperandIterator & dunderIter()
static void bind(nanobind::module_ &m)
A list of operation operands.
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)
size_t getOperandNumber() const
static void bind(nanobind::module_ &m)
nanobind::typed< nanobind::object, PyOpView > getOwner() const
PyOpOperands(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
static constexpr const char * pyClassName
Sliceable< PyOpOperandList, PyOpOperand > SliceableT
A list of operation results.
static void bindDerived(ClassTy &c)
PyOpResultList(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
PyOperationRef & getOperation()
Python wrapper for MlirOpResult.
static void bindDerived(ClassTy &c)
A list of operation successors.
static void bindDerived(ClassTy &c)
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)
static nanobind::typed< nanobind::object, PyOperation > buildGeneric(std::string_view name, std::tuple< int, bool > opRegionSpec, nanobind::object operandSegmentSpecObj, nanobind::object resultSegmentSpecObj, std::optional< nanobind::sequence > resultTypeList, nanobind::sequence operandList, std::optional< nanobind::dict > attributes, std::optional< std::vector< PyBlock * > > successors, std::optional< int > regions, PyLocation &location, const nanobind::object &maybeIp)
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.
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)
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)
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)
static void bind(nanobind::module_ &m)
PyOperationIterator & dunderIter()
nanobind::typed< nanobind::object, PyOpView > dunderNext()
Operations are exposed by the C-API as a forward-only linked list.
static void bind(nanobind::module_ &m)
nanobind::typed< nanobind::object, PyOpView > dunderGetItem(intptr_t index)
PyOperationIterator dunderIter()
MlirOperation get() const
static nanobind::object create(std::string_view name, std::optional< std::vector< PyType * > > results, const MlirValue *operands, size_t numOperands, 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.
void setInvalid()
Invalidate the operation.
PyOperation & getOperation() override
Each must provide access to the raw Operation.
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.
nanobind::object clone(const nanobind::object &ip)
Clones this operation.
static nanobind::object createFromCapsule(const nanobind::object &capsule)
Creates a PyOperation from the MlirOperation wrapped by a capsule.
std::optional< PyOperationRef > getParentOperation()
Gets the parent operation or raises an exception if the operation has no parent.
nanobind::object createOpView()
Creates an OpView suitable for this operation.
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirOperation.
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 detachFromParent()
Detaches the operation from its parent block and updates its state accordingly.
void erase()
Erases the underlying MlirOperation, removes its pointer from the parent context's live operations ma...
PyBlock getBlock()
Gets the owning block or raises an exception if the operation has no owning block.
static PyOperationRef createDetached(PyMlirContextRef contextRef, MlirOperation operation, nanobind::object parentKeepAlive=nanobind::object())
Creates a detached operation.
PyOperation(PyMlirContextRef contextRef, MlirOperation operation)
void setAttached(const nanobind::object &parent=nanobind::object())
Regions of an op are fixed length and indexed numerically so are represented with a sequence-like con...
PyRegionList(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Wrapper around an MlirRegion.
PyOperationRef & getParentOperation()
Bindings for MLIR symbol tables.
PyStringAttribute insert(PyOperationBase &symbol)
Inserts the given operation into the symbol table.
PySymbolTable(PyOperationBase &operation)
Constructs a symbol table for the given operation.
static PyStringAttribute getVisibility(PyOperationBase &symbol)
Gets and sets the visibility of a symbol op.
void erase(PyOperationBase &symbol)
Removes the given operation from the symbol table and erases it.
static void walkSymbolTables(PyOperationBase &from, bool allSymUsesVisible, nanobind::object callback)
Walks all symbol tables under and including 'from'.
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.
static void replaceAllSymbolUses(const std::string &oldSymbol, const std::string &newSymbol, PyOperationBase &from)
Replaces all symbol uses within an operation.
static PyStringAttribute getSymbolName(PyOperationBase &symbol)
Gets and sets the name of a symbol op.
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 setSymbolName(PyOperationBase &symbol, const std::string &name)
static void setVisibility(PyOperationBase &symbol, const std::string &visibility)
Tracks an entry in the thread context stack.
static PyInsertionPoint * getDefaultInsertionPoint()
Gets the top of stack insertion point and return nullptr if not defined.
static nanobind::object pushInsertionPoint(nanobind::object insertionPoint)
PyLocation * getLocation()
static void popInsertionPoint(PyInsertionPoint &insertionPoint)
static PyLocation * getDefaultLocation()
Gets the top of stack location and returns nullptr if not defined.
static PyThreadContextEntry * getTopOfStack()
Stack management.
PyInsertionPoint * getInsertionPoint()
static nanobind::object pushLocation(nanobind::object location)
static void popLocation(PyLocation &location)
static nanobind::object pushContext(nanobind::object context)
PyMlirContext * getContext()
static void popContext(PyMlirContext &context)
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.
Wrapper around MlirLlvmThreadPool Python object owns the C++ thread pool.
int getMaxConcurrency() const
std::string _mlir_thread_pool_ptr() const
A TypeID provides an efficient and unique identifier for a specific C++ type.
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirTypeID.
PyTypeID(MlirTypeID typeID)
bool operator==(const PyTypeID &other) const
static PyTypeID createFromCapsule(nanobind::object capsule)
Creates a PyTypeID from the MlirTypeID wrapped by a capsule.
Wrapper around the generic MlirType.
PyType(PyMlirContextRef contextRef, MlirType type)
bool operator==(const PyType &other) const
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::typed< nanobind::object, PyType > maybeDownCast()
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirValue.
PyOperationRef & getParentOperation()
PyValue(PyOperationRef parentOperation, MlirValue value)
nanobind::typed< nanobind::object, std::variant< PyBlockArgument, PyOpResult, PyValue > > maybeDownCast()
static PyValue createFromCapsule(nanobind::object capsule)
Creates a PyValue from the MlirValue wrapped by a capsule.
MLIR_CAPI_EXPORTED intptr_t mlirDiagnosticGetNumNotes(MlirDiagnostic diagnostic)
Returns the number of notes attached to the diagnostic.
MLIR_CAPI_EXPORTED MlirDiagnosticSeverity mlirDiagnosticGetSeverity(MlirDiagnostic diagnostic)
Returns the severity of the diagnostic.
MLIR_CAPI_EXPORTED void mlirDiagnosticPrint(MlirDiagnostic diagnostic, MlirStringCallback callback, void *userData)
Prints a diagnostic using the provided callback.
MLIR_CAPI_EXPORTED MlirDiagnostic mlirDiagnosticGetNote(MlirDiagnostic diagnostic, intptr_t pos)
Returns pos-th note attached to the diagnostic.
MLIR_CAPI_EXPORTED void mlirEmitError(MlirLocation location, const char *message)
Emits an error at the given location through the diagnostics engine.
MLIR_CAPI_EXPORTED MlirDiagnosticHandlerID mlirContextAttachDiagnosticHandler(MlirContext context, MlirDiagnosticHandler handler, void *userData, void(*deleteUserData)(void *))
Attaches the diagnostic handler to the context.
struct MlirDiagnostic MlirDiagnostic
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 MlirLocation mlirDiagnosticGetLocation(MlirDiagnostic diagnostic)
Returns the location at which the diagnostic is reported.
MLIR_CAPI_EXPORTED MlirAttribute mlirDenseI32ArrayGet(MlirContext ctx, intptr_t size, int32_t const *values)
MLIR_CAPI_EXPORTED MlirAttribute mlirStringAttrGet(MlirContext ctx, MlirStringRef str)
Creates a string attribute in the given context containing the given string.
MLIR_CAPI_EXPORTED MlirDynamicOpTrait mlirDynamicOpTraitIsTerminatorCreate(void)
Get the dynamic op trait that indicates the operation is a terminator.
MLIR_CAPI_EXPORTED MlirTypeID mlirDynamicOpTraitIsTerminatorGetTypeID(void)
Get the type ID of the dynamic op trait that indicates the operation is a terminator.
MLIR_CAPI_EXPORTED MlirDynamicOpTrait mlirDynamicOpTraitCreate(MlirTypeID typeID, MlirDynamicOpTraitCallbacks callbacks, void *userData)
Create a custom dynamic op trait with the given type ID and callbacks.
MLIR_CAPI_EXPORTED bool mlirDynamicOpTraitAttach(MlirDynamicOpTrait dynamicOpTrait, MlirStringRef opName, MlirContext context)
Attach a dynamic op trait to the given operation name.
MLIR_CAPI_EXPORTED MlirTypeID mlirDynamicOpTraitNoTerminatorGetTypeID(void)
Get the type ID of the dynamic op trait that indicates regions have no terminator.
MLIR_CAPI_EXPORTED MlirDynamicOpTrait mlirDynamicOpTraitNoTerminatorCreate(void)
Get the dynamic op trait that indicates regions have no terminator.
MLIR_CAPI_EXPORTED MlirAttribute mlirLocationGetAttribute(MlirLocation location)
Returns the underlying location attribute of this location.
MlirWalkResult(* MlirOperationWalkCallback)(MlirOperation, void *userData)
Operation walker type.
MLIR_CAPI_EXPORTED MlirLocation mlirValueGetLocation(MlirValue v)
Gets the location of the value.
MLIR_CAPI_EXPORTED unsigned mlirContextGetNumThreads(MlirContext context)
Gets the number of threads of the thread pool of the context when multithreading is enabled.
MLIR_CAPI_EXPORTED void mlirOperationWriteBytecode(MlirOperation op, MlirStringCallback callback, void *userData)
Same as mlirOperationPrint but writing the bytecode format.
MLIR_CAPI_EXPORTED MlirLocation mlirLocationFileLineColGet(MlirContext context, MlirStringRef filename, unsigned line, unsigned col)
Creates an File/Line/Column location owned by the given context.
MLIR_CAPI_EXPORTED void mlirSymbolTableWalkSymbolTables(MlirOperation from, bool allSymUsesVisible, void(*callback)(MlirOperation, bool, void *userData), void *userData)
Walks all symbol table operations nested within, and including, op.
MLIR_CAPI_EXPORTED MlirStringRef mlirDialectGetNamespace(MlirDialect dialect)
Returns the namespace of the given dialect.
MLIR_CAPI_EXPORTED int mlirLocationFileLineColRangeGetEndColumn(MlirLocation location)
Getter for end_column of FileLineColRange.
MLIR_CAPI_EXPORTED MlirAttribute mlirSymbolTableInsert(MlirSymbolTable symbolTable, MlirOperation operation)
Inserts the given operation into the given symbol table.
MlirWalkOrder
Traversal order for operation walk.
MLIR_CAPI_EXPORTED MlirNamedAttribute mlirNamedAttributeGet(MlirIdentifier name, MlirAttribute attr)
Associates an attribute with the name. Takes ownership of neither.
MLIR_CAPI_EXPORTED MlirLocation mlirLocationNameGetChildLoc(MlirLocation location)
Getter for childLoc of Name.
MLIR_CAPI_EXPORTED void mlirSymbolTableErase(MlirSymbolTable symbolTable, MlirOperation operation)
Removes the given operation from the symbol table and erases it.
MLIR_CAPI_EXPORTED void mlirContextAppendDialectRegistry(MlirContext ctx, MlirDialectRegistry registry)
Append the contents of the given dialect registry to the registry associated with the context.
MLIR_CAPI_EXPORTED MlirStringRef mlirIdentifierStr(MlirIdentifier ident)
Gets the string value of the identifier.
MLIR_CAPI_EXPORTED MlirType mlirTypeParseGet(MlirContext context, MlirStringRef type)
Parses a type. The type is owned by the context.
MLIR_CAPI_EXPORTED MlirOpOperand mlirOpOperandGetNextUse(MlirOpOperand opOperand)
Returns an op operand representing the next use of the value, or a null op operand if there is no nex...
MLIR_CAPI_EXPORTED void mlirContextSetAllowUnregisteredDialects(MlirContext context, bool allow)
Sets whether unregistered dialects are allowed in this context.
MLIR_CAPI_EXPORTED void mlirRegionInsertOwnedBlockBefore(MlirRegion region, MlirBlock reference, MlirBlock block)
Takes a block owned by the caller and inserts it before the (non-owned) reference block in the given ...
MLIR_CAPI_EXPORTED bool mlirLocationIsAFileLineColRange(MlirLocation location)
Checks whether the given location is an FileLineColRange.
MLIR_CAPI_EXPORTED unsigned mlirLocationFusedGetNumLocations(MlirLocation location)
Getter for number of locations fused together.
MLIR_CAPI_EXPORTED void mlirValueReplaceAllUsesOfWith(MlirValue of, MlirValue with)
Replace all uses of 'of' value with the 'with' value, updating anything in the IR that uses 'of' to u...
MLIR_CAPI_EXPORTED void mlirValuePrintAsOperand(MlirValue value, MlirAsmState state, MlirStringCallback callback, void *userData)
Prints a value as an operand (i.e., the ValueID).
MLIR_CAPI_EXPORTED MlirLocation mlirLocationUnknownGet(MlirContext context)
Creates a location with unknown position owned by the given context.
MLIR_CAPI_EXPORTED MlirOperation mlirOpOperandGetOwner(MlirOpOperand opOperand)
Returns the owner operation of an op operand.
MLIR_CAPI_EXPORTED MlirIdentifier mlirLocationFileLineColRangeGetFilename(MlirLocation location)
Getter for filename of FileLineColRange.
MLIR_CAPI_EXPORTED void mlirLocationFusedGetLocations(MlirLocation location, MlirLocation *locationsCPtr)
Getter for locations of Fused.
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`...
MLIR_CAPI_EXPORTED MlirRegion mlirBlockGetParentRegion(MlirBlock block)
Returns the region that contains this block.
MLIR_CAPI_EXPORTED void mlirOperationMoveBefore(MlirOperation op, MlirOperation other)
Moves the given operation immediately before the other operation in its parent block.
MLIR_CAPI_EXPORTED void mlirValueReplaceAllUsesExcept(MlirValue of, MlirValue with, intptr_t numExceptions, MlirOperation *exceptions)
Replace all uses of 'of' value with 'with' value, updating anything in the IR that uses 'of' to use '...
MLIR_CAPI_EXPORTED void mlirOperationPrintWithState(MlirOperation op, MlirAsmState state, MlirStringCallback callback, void *userData)
Same as mlirOperationPrint but accepts AsmState controlling the printing behavior as well as caching ...
MlirWalkResult
Operation walk result.
MLIR_CAPI_EXPORTED void mlirRegionInsertOwnedBlock(MlirRegion region, intptr_t pos, MlirBlock block)
Takes a block owned by the caller and inserts it at pos to the given region.
static bool mlirTypeIsNull(MlirType type)
Checks whether a type is null.
MLIR_CAPI_EXPORTED bool mlirContextIsRegisteredOperation(MlirContext context, MlirStringRef name)
Returns whether the given fully-qualified operation (i.e.
MLIR_CAPI_EXPORTED intptr_t mlirBlockGetNumArguments(MlirBlock block)
Returns the number of arguments of the block.
MLIR_CAPI_EXPORTED int mlirLocationFileLineColRangeGetStartLine(MlirLocation location)
Getter for start_line of FileLineColRange.
MLIR_CAPI_EXPORTED MlirLocation mlirLocationFusedGet(MlirContext ctx, intptr_t nLocations, MlirLocation const *locations, MlirAttribute metadata)
Creates a fused location with an array of locations and metadata.
MLIR_CAPI_EXPORTED void mlirBlockInsertOwnedOperationBefore(MlirBlock block, MlirOperation reference, MlirOperation operation)
Takes an operation owned by the caller and inserts it before the (non-owned) reference operation in t...
static bool mlirContextIsNull(MlirContext context)
Checks whether a context is null.
MLIR_CAPI_EXPORTED MlirDialect mlirContextGetOrLoadDialect(MlirContext context, MlirStringRef name)
Gets the dialect instance owned by the given context using the dialect namespace to identify it,...
MLIR_CAPI_EXPORTED bool mlirLocationIsACallSite(MlirLocation location)
Checks whether the given location is an CallSite.
MLIR_CAPI_EXPORTED void mlirRegionInsertOwnedBlockAfter(MlirRegion region, MlirBlock reference, MlirBlock block)
Takes a block owned by the caller and inserts it after the (non-owned) reference block in the given r...
MLIR_CAPI_EXPORTED MlirBlock mlirBlockCreate(intptr_t nArgs, MlirType const *args, MlirLocation const *locs)
Creates a new empty block with the given argument types and transfers ownership to the caller.
static bool mlirBlockIsNull(MlirBlock block)
Checks whether a block is null.
MLIR_CAPI_EXPORTED void mlirBlockAppendOwnedOperation(MlirBlock block, MlirOperation operation)
Takes an operation owned by the caller and appends it to the block.
MLIR_CAPI_EXPORTED MlirValue mlirBlockGetArgument(MlirBlock block, intptr_t pos)
Returns pos-th argument of the block.
MLIR_CAPI_EXPORTED MlirOperation mlirSymbolTableLookup(MlirSymbolTable symbolTable, MlirStringRef name)
Looks up a symbol with the given name in the given symbol table and returns the operation that corres...
MLIR_CAPI_EXPORTED MlirContext mlirTypeGetContext(MlirType type)
Gets the context that a type was created with.
MLIR_CAPI_EXPORTED MlirLocation mlirLocationFileLineColRangeGet(MlirContext context, MlirStringRef filename, unsigned start_line, unsigned start_col, unsigned end_line, unsigned end_col)
Creates an File/Line/Column range location owned by the given context.
MLIR_CAPI_EXPORTED bool mlirOpOperandIsNull(MlirOpOperand opOperand)
Returns whether the op operand is null.
MLIR_CAPI_EXPORTED MlirSymbolTable mlirSymbolTableCreate(MlirOperation operation)
Creates a symbol table for the given operation.
MLIR_CAPI_EXPORTED bool mlirLocationEqual(MlirLocation l1, MlirLocation l2)
Checks if two locations are equal.
MLIR_CAPI_EXPORTED int mlirLocationFileLineColRangeGetStartColumn(MlirLocation location)
Getter for start_column of FileLineColRange.
MLIR_CAPI_EXPORTED bool mlirLocationIsAFused(MlirLocation location)
Checks whether the given location is an Fused.
static bool mlirLocationIsNull(MlirLocation location)
Checks if the location is null.
MLIR_CAPI_EXPORTED MlirValue mlirBlockAddArgument(MlirBlock block, MlirType type, MlirLocation loc)
Appends an argument of the specified type to the block.
MLIR_CAPI_EXPORTED void mlirOperationPrintWithFlags(MlirOperation op, MlirOpPrintingFlags flags, MlirStringCallback callback, void *userData)
Same as mlirOperationPrint but accepts flags controlling the printing behavior.
MLIR_CAPI_EXPORTED MlirOpOperand mlirValueGetFirstUse(MlirValue value)
Returns an op operand representing the first use of the value, or a null op operand if there are no u...
MLIR_CAPI_EXPORTED void mlirContextSetThreadPool(MlirContext context, MlirLlvmThreadPool threadPool)
Sets the thread pool of the context explicitly, enabling multithreading in the process.
MLIR_CAPI_EXPORTED bool mlirOperationVerify(MlirOperation op)
Verify the operation and return true if it passes, false if it fails.
MLIR_CAPI_EXPORTED bool mlirTypeEqual(MlirType t1, MlirType t2)
Checks if two types are equal.
MLIR_CAPI_EXPORTED unsigned mlirOpOperandGetOperandNumber(MlirOpOperand opOperand)
Returns the operand number of an op operand.
MLIR_CAPI_EXPORTED MlirLocation mlirLocationCallSiteGetCaller(MlirLocation location)
Getter for caller of CallSite.
MLIR_CAPI_EXPORTED MlirOperation mlirBlockGetTerminator(MlirBlock block)
Returns the terminator operation in the block or null if no terminator.
MLIR_CAPI_EXPORTED MlirIdentifier mlirLocationNameGetName(MlirLocation location)
Getter for name of Name.
MLIR_CAPI_EXPORTED bool mlirOperationIsBeforeInBlock(MlirOperation op, MlirOperation other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
MLIR_CAPI_EXPORTED MlirLocation mlirLocationFromAttribute(MlirAttribute attribute)
Creates a location from a location attribute.
MLIR_CAPI_EXPORTED MlirTypeID mlirTypeGetTypeID(MlirType type)
Gets the type ID of the type.
MLIR_CAPI_EXPORTED MlirStringRef mlirSymbolTableGetVisibilityAttributeName(void)
Returns the name of the attribute used to store symbol visibility.
static bool mlirDialectIsNull(MlirDialect dialect)
Checks if the dialect is null.
MLIR_CAPI_EXPORTED MlirBlock mlirBlockGetNextInRegion(MlirBlock block)
Returns the block immediately following the given block in its parent region.
MLIR_CAPI_EXPORTED MlirLocation mlirLocationCallSiteGet(MlirLocation callee, MlirLocation caller)
Creates a call site location with a callee and a caller.
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 void mlirOperationWalk(MlirOperation op, MlirOperationWalkCallback callback, void *userData, MlirWalkOrder walkOrder)
Walks operation op in walkOrder and calls callback on that operation.
MLIR_CAPI_EXPORTED MlirContext mlirContextCreateWithThreading(bool threadingEnabled)
Creates an MLIR context with an explicit setting of the multithreading setting and transfers its owne...
MLIR_CAPI_EXPORTED MlirOperation mlirBlockGetParentOperation(MlirBlock)
Returns the closest surrounding operation that contains this block.
MLIR_CAPI_EXPORTED MlirContext mlirLocationGetContext(MlirLocation location)
Gets the context that a location was created with.
MLIR_CAPI_EXPORTED void mlirBlockEraseArgument(MlirBlock block, unsigned index)
Erase the argument at 'index' and remove it from the argument list.
MLIR_CAPI_EXPORTED void mlirAttributeDump(MlirAttribute attr)
Prints the attribute to the standard error stream.
MLIR_CAPI_EXPORTED MlirLogicalResult mlirSymbolTableReplaceAllSymbolUses(MlirStringRef oldSymbol, MlirStringRef newSymbol, MlirOperation from)
Attempt to replace all uses that are nested within the given operation of the given symbol 'oldSymbol...
MLIR_CAPI_EXPORTED void mlirRegionAppendOwnedBlock(MlirRegion region, MlirBlock block)
Takes a block owned by the caller and appends it to the given region.
MLIR_CAPI_EXPORTED MlirOperation mlirBlockGetFirstOperation(MlirBlock block)
Returns the first operation in the block.
static bool mlirRegionIsNull(MlirRegion region)
Checks whether a region is null.
MLIR_CAPI_EXPORTED MlirDialect mlirTypeGetDialect(MlirType type)
Gets the dialect a type belongs to.
MLIR_CAPI_EXPORTED MlirIdentifier mlirIdentifierGet(MlirContext context, MlirStringRef str)
Gets an identifier with the given string value.
MLIR_CAPI_EXPORTED void mlirContextLoadAllAvailableDialects(MlirContext context)
Eagerly loads all available dialects registered with a context, making them available for use for IR ...
MLIR_CAPI_EXPORTED MlirLlvmThreadPool mlirContextGetThreadPool(MlirContext context)
Gets the thread pool of the context when enabled multithreading, otherwise an assertion is raised.
MLIR_CAPI_EXPORTED int mlirLocationFileLineColRangeGetEndLine(MlirLocation location)
Getter for end_line of FileLineColRange.
MLIR_CAPI_EXPORTED MlirLocation mlirLocationNameGet(MlirContext context, MlirStringRef name, MlirLocation childLoc)
Creates a name location owned by the given context.
MLIR_CAPI_EXPORTED void mlirContextEnableMultithreading(MlirContext context, bool enable)
Set threading mode (must be set to false to mlir-print-ir-after-all).
MLIR_CAPI_EXPORTED MlirLocation mlirLocationCallSiteGetCallee(MlirLocation location)
Getter for callee of CallSite.
MLIR_CAPI_EXPORTED MlirContext mlirValueGetContext(MlirValue v)
Gets the context that a value was created with.
MLIR_CAPI_EXPORTED MlirStringRef mlirSymbolTableGetSymbolAttributeName(void)
Returns the name of the attribute used to store symbol names compatible with symbol tables.
MLIR_CAPI_EXPORTED MlirRegion mlirRegionCreate(void)
Creates a new empty region and transfers ownership to the caller.
MLIR_CAPI_EXPORTED void mlirBlockDetach(MlirBlock block)
Detach a block from the owning region and assume ownership.
MLIR_CAPI_EXPORTED void mlirOperationDump(MlirOperation op)
Prints an operation to stderr.
static bool mlirSymbolTableIsNull(MlirSymbolTable symbolTable)
Returns true if the symbol table is null.
MLIR_CAPI_EXPORTED bool mlirContextGetAllowUnregisteredDialects(MlirContext context)
Returns whether the context allows unregistered dialects.
MLIR_CAPI_EXPORTED void mlirOperationReplaceUsesOfWith(MlirOperation op, MlirValue of, MlirValue with)
Replace uses of 'of' value with the 'with' value inside the 'op' operation.
MLIR_CAPI_EXPORTED void mlirOperationMoveAfter(MlirOperation op, MlirOperation other)
Moves the given operation immediately after the other operation in its parent block.
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`.
MLIR_CAPI_EXPORTED MlirLogicalResult mlirOperationWriteBytecodeWithConfig(MlirOperation op, MlirBytecodeWriterConfig config, MlirStringCallback callback, void *userData)
Same as mlirOperationWriteBytecode but with writer config and returns failure only if desired bytecod...
MLIR_CAPI_EXPORTED void mlirContextDestroy(MlirContext context)
Takes an MLIR context owned by the caller and destroys it.
MLIR_CAPI_EXPORTED MlirBlock mlirRegionGetFirstBlock(MlirRegion region)
Gets the first block in the region.
static MlirStringRef mlirStringRefCreate(const char *str, size_t length)
Constructs a string reference from the pointer and length.
static MlirLogicalResult mlirLogicalResultFailure(void)
Creates a logical result representing a failure.
struct MlirLogicalResult MlirLogicalResult
MLIR_CAPI_EXPORTED int mlirLlvmThreadPoolGetMaxConcurrency(MlirLlvmThreadPool pool)
Returns the maximum number of threads in the thread pool.
MLIR_CAPI_EXPORTED void mlirLlvmThreadPoolDestroy(MlirLlvmThreadPool pool)
Destroy an LLVM thread pool.
MLIR_CAPI_EXPORTED MlirLlvmThreadPool mlirLlvmThreadPoolCreate(void)
Create an LLVM thread pool.
MLIR_CAPI_EXPORTED size_t mlirTypeIDHashValue(MlirTypeID typeID)
Returns the hash value of the type id.
static MlirLogicalResult mlirLogicalResultSuccess(void)
Creates a logical result representing a success.
struct MlirStringRef MlirStringRef
static bool mlirLogicalResultIsFailure(MlirLogicalResult res)
Checks if the given logical result represents a failure.
static bool mlirTypeIDIsNull(MlirTypeID typeID)
Checks whether a type id is null.
MLIR_CAPI_EXPORTED bool mlirTypeIDEqual(MlirTypeID typeID1, MlirTypeID typeID2)
Checks if two type ids are equal.
MLIR_PYTHON_API_EXPORTED MlirValue getUniqueResult(MlirOperation operation)
static std::string formatMLIRError(const MLIRError &e)
MLIR_PYTHON_API_EXPORTED void populateRoot(nanobind::module_ &m)
static void maybeInsertOperation(PyOperationRef &op, const nb::object &maybeIp)
static void populateResultTypes(std::string_view name, nb::sequence resultTypeList, const nb::object &resultSegmentSpecObj, std::vector< int32_t > &resultSegmentLengths, std::vector< PyType * > &resultTypes)
PyObjectRef< PyMlirContext > PyMlirContextRef
Wrapper around MlirContext.
static MlirValue getOpResultOrValue(nb::handle operand)
PyObjectRef< PyOperation > PyOperationRef
MlirStringRef toMlirStringRef(const std::string &s)
static bool attachOpTrait(const nb::object &opName, MlirDynamicOpTrait trait, PyMlirContext &context)
PyObjectRef< PyModule > PyModuleRef
static MlirLogicalResult verifyTraitByMethod(MlirOperation op, void *userData, const char *methodName)
static PyOperationRef getValueOwnerRef(MlirValue value)
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.
static std::vector< nb::typed< nb::object, PyType > > getValueTypes(Container &container, PyMlirContextRef &context)
Returns the list of types of the values held by container.
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.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
std::string join(const Ts &...args)
Helper function to concatenate arguments into a std::string.
An opaque reference to a diagnostic, always owned by the diagnostics engine (context).
MlirLogicalResult(* verifyTrait)(MlirOperation op, void *userData)
The callback function to verify the operation.
void(* construct)(void *userData)
Optional constructor for the user data.
void(* destruct)(void *userData)
Optional destructor for the user data.
MlirLogicalResult(* verifyRegionTrait)(MlirOperation op, void *userData)
The callback function to verify the operation with access to regions.
A logical result value, essentially a boolean with named states.
A pointer to a sized fragment of a string, not necessarily null-terminated.
const char * data
Pointer to the first symbol.
size_t length
Length of the fragment.
Accumulates into a python string from a method that accepts an MlirStringCallback.
MlirStringCallback getCallback()
Custom exception that allows access to error diagnostic information.
MLIRError(std::string message, std::vector< PyDiagnostic::DiagnosticInfo > &&errorDiagnostics={})
std::vector< PyDiagnostic::DiagnosticInfo > errorDiagnostics
static void bind(nanobind::module_ &m)
Bind the MLIRError exception class to the given module.
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
static void set(nanobind::object &o, bool enable)
static bool get(const nanobind::object &)
static void bind(nanobind::module_ &m)
RAII object that captures any error diagnostics emitted to the provided context.
std::vector< PyDiagnostic::DiagnosticInfo > take()
ErrorCapture(PyMlirContextRef ctx)