MLIR 24.0.0git
IRCore.cpp
Go to the documentation of this file.
1//===- IRModules.cpp - IR Submodules of pybind module ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9// clang-format off
13#include "mlir-c/Bindings/Python/Interop.h" // This is expected after nanobind.
14// clang-format on
16#include "mlir-c/Debug.h"
17#include "mlir-c/Diagnostics.h"
19#include "mlir-c/IR.h"
20#include "mlir-c/Remarks.h"
21#include "mlir-c/Support.h"
22
23#include <array>
24#include <cassert>
25#include <functional>
26#include <optional>
27#include <string>
28
29namespace nb = nanobind;
30using namespace nb::literals;
31using namespace mlir;
33
34static const char kModuleParseDocstring[] =
35 R"(Parses a module's assembly format from a string.
36
37Returns a new MlirModule or raises an MLIRError if the parsing fails.
38
39See also: https://mlir.llvm.org/docs/LangRef/
40)";
41
42static const char kDumpDocstring[] =
43 "Dumps a debug representation of the object to stderr.";
44
46 R"(Replace all uses of this value with the `with` value, except for those
47in `exceptions`. `exceptions` can be either a single operation or a list of
48operations.
49)";
50
51//------------------------------------------------------------------------------
52// Utilities.
53//------------------------------------------------------------------------------
54
55/// Local helper to compute std::hash for a value.
56template <typename T>
57static size_t hash(const T &value) {
58 return std::hash<T>{}(value);
59}
60
61static nb::object
62createCustomDialectWrapper(const std::string &dialectNamespace,
63 nb::object dialectDescriptor) {
64 auto dialectClass =
66 dialectNamespace);
67 if (!dialectClass) {
68 // Use the base class.
70 std::move(dialectDescriptor)));
71 }
72
73 // Create the custom implementation.
74 return (*dialectClass)(std::move(dialectDescriptor));
75}
76
77namespace mlir {
78namespace python {
80MlirBlock createBlock(
81 const nb::typed<nb::sequence, PyType> &pyArgTypes,
82 const std::optional<nb::typed<nb::sequence, PyLocation>> &pyArgLocs) {
83 std::vector<MlirType> argTypes;
84 argTypes.reserve(nb::len(pyArgTypes));
85 for (nb::handle pyType : pyArgTypes)
86 argTypes.push_back(
87 nb::cast<python::MLIR_BINDINGS_PYTHON_DOMAIN::PyType &>(pyType));
88
89 std::vector<MlirLocation> argLocs;
90 if (pyArgLocs) {
91 argLocs.reserve(nb::len(*pyArgLocs));
92 for (nb::handle pyLoc : *pyArgLocs)
93 argLocs.push_back(
94 nb::cast<python::MLIR_BINDINGS_PYTHON_DOMAIN::PyLocation &>(pyLoc));
95 } else if (!argTypes.empty()) {
96 argLocs.assign(
97 argTypes.size(),
99 }
100
101 if (argTypes.size() != argLocs.size())
102 throw nb::value_error(
103 join("Expected ", argTypes.size(), " locations, got: ", argLocs.size())
104 .c_str());
105 return mlirBlockCreate(argTypes.size(), argTypes.data(), argLocs.data());
106}
107
108void PyGlobalDebugFlag::set(nb::object &o, bool enable) {
109 nb::ft_lock_guard lock(mutex);
110 mlirEnableGlobalDebug(enable);
111}
112
113bool PyGlobalDebugFlag::get(const nb::object &) {
114 nb::ft_lock_guard lock(mutex);
116}
117
118void PyGlobalDebugFlag::bind(nb::module_ &m) {
119 // Debug flags.
120 nb::class_<PyGlobalDebugFlag>(m, "_GlobalDebug")
121 .def_prop_rw_static("flag", &PyGlobalDebugFlag::get,
122 &PyGlobalDebugFlag::set, "LLVM-wide debug flag.")
123 .def_static(
124 "set_types",
125 [](const std::string &type) {
126 nb::ft_lock_guard lock(mutex);
127 mlirSetGlobalDebugType(type.c_str());
128 },
129 "types"_a, "Sets specific debug types to be produced by LLVM.")
130 .def_static(
131 "set_types",
132 [](const std::vector<std::string> &types) {
133 std::vector<const char *> pointers;
134 pointers.reserve(types.size());
135 for (const std::string &str : types)
136 pointers.push_back(str.c_str());
137 nb::ft_lock_guard lock(mutex);
138 mlirSetGlobalDebugTypes(pointers.data(), pointers.size());
139 },
140 "types"_a,
141 "Sets multiple specific debug types to be produced by LLVM.");
142}
143
144nb::ft_mutex PyGlobalDebugFlag::mutex;
145
146bool PyAttrBuilderMap::dunderContains(const std::string &attributeKind) {
147 return PyGlobals::get().lookupAttributeBuilder(attributeKind).has_value();
148}
149
150nb::callable
151PyAttrBuilderMap::dunderGetItemNamed(const std::string &attributeKind) {
152 auto builder = PyGlobals::get().lookupAttributeBuilder(attributeKind);
153 if (!builder)
154 throw nb::key_error(attributeKind.c_str());
155 return *builder;
156}
157
158void PyAttrBuilderMap::dunderSetItemNamed(const std::string &attributeKind,
159 nb::callable func, bool replace,
160 bool allow_existing) {
161 PyGlobals::get().registerAttributeBuilder(attributeKind, std::move(func),
162 replace, allow_existing);
163}
164
165void PyAttrBuilderMap::bind(nb::module_ &m) {
166 nb::class_<PyAttrBuilderMap>(m, "AttrBuilder")
167 .def_static("contains", &PyAttrBuilderMap::dunderContains,
168 "attribute_kind"_a,
169 "Checks whether an attribute builder is registered for the "
170 "given attribute kind.")
171 .def_static("get", &PyAttrBuilderMap::dunderGetItemNamed,
172 "attribute_kind"_a,
173 "Gets the registered attribute builder for the given "
174 "attribute kind.")
175 .def_static("insert", &PyAttrBuilderMap::dunderSetItemNamed,
176 "attribute_kind"_a, "attr_builder"_a, "replace"_a = false,
177 "allow_existing"_a = false,
178 "Register an attribute builder for building MLIR "
179 "attributes from Python values.");
180}
181
182//------------------------------------------------------------------------------
183// PyBlock
184//------------------------------------------------------------------------------
185
187 return nb::steal<nb::object>(mlirPythonBlockToCapsule(get()));
188}
189
190//------------------------------------------------------------------------------
191// Collections.
192//------------------------------------------------------------------------------
193
197 length == -1 ? mlirOperationGetNumRegions(operation->get())
198 : length,
199 step),
200 operation(std::move(operation)) {}
201
202intptr_t PyRegionList::getRawNumElements() {
203 operation->checkValid();
204 return mlirOperationGetNumRegions(operation->get());
205}
206
207PyRegion PyRegionList::getRawElement(intptr_t pos) {
208 operation->checkValid();
209 return PyRegion(operation, mlirOperationGetRegion(operation->get(), pos));
210}
211
212PyRegionList PyRegionList::slice(intptr_t startIndex, intptr_t length,
213 intptr_t step) const {
214 return PyRegionList(operation, startIndex, length, step);
215}
216
217nb::typed<nb::object, PyBlock> PyBlockIterator::dunderNext() {
218 operation->checkValid();
219 if (mlirBlockIsNull(next)) {
220 PyErr_SetNone(PyExc_StopIteration);
221 // python functions should return NULL after setting any exception
222 return nb::object();
223 }
224
225 PyBlock returnBlock(operation, next);
226 next = mlirBlockGetNextInRegion(next);
227 return nb::cast(returnBlock);
228}
229
230void PyBlockIterator::bind(nb::module_ &m) {
231 nb::class_<PyBlockIterator>(m, "BlockIterator")
232 .def("__iter__", &PyBlockIterator::dunderIter,
233 "Returns an iterator over the blocks in the operation's region.")
234 .def("__next__", &PyBlockIterator::dunderNext,
235 "Returns the next block in the iteration.");
236}
237
239 operation->checkValid();
240 return PyBlockIterator(operation, mlirRegionGetFirstBlock(region));
241}
242
244 operation->checkValid();
245 intptr_t count = 0;
246 MlirBlock block = mlirRegionGetFirstBlock(region);
247 while (!mlirBlockIsNull(block)) {
248 count += 1;
249 block = mlirBlockGetNextInRegion(block);
250 }
251 return count;
252}
253
255 operation->checkValid();
256 if (index < 0) {
257 index += dunderLen();
258 }
259 if (index < 0) {
260 throw nb::index_error("attempt to access out of bounds block");
261 }
262 MlirBlock block = mlirRegionGetFirstBlock(region);
263 while (!mlirBlockIsNull(block)) {
264 if (index == 0) {
265 return PyBlock(operation, block);
266 }
267 block = mlirBlockGetNextInRegion(block);
268 index -= 1;
269 }
270 throw nb::index_error("attempt to access out of bounds block");
271}
272
273PyBlock PyBlockList::appendBlock(const nb::args &pyArgTypes,
274 const std::optional<nb::sequence> &pyArgLocs) {
275 operation->checkValid();
276 MlirBlock block = createBlock(nb::cast<nb::sequence>(pyArgTypes), pyArgLocs);
277 mlirRegionAppendOwnedBlock(region, block);
278 return PyBlock(operation, block);
279}
280
281void PyBlockList::bind(nb::module_ &m) {
282 nb::class_<PyBlockList>(m, "BlockList")
283 .def("__getitem__", &PyBlockList::dunderGetItem,
284 "Returns the block at the specified index.")
285 .def("__iter__", &PyBlockList::dunderIter,
286 "Returns an iterator over blocks in the operation's region.")
287 .def("__len__", &PyBlockList::dunderLen,
288 "Returns the number of blocks in the operation's region.")
289 .def("append", &PyBlockList::appendBlock,
290 R"(
291 Appends a new block, with argument types as positional args.
292
293 Returns:
294 The created block.
295 )",
296 "args"_a, nb::kw_only(), "arg_locs"_a = std::nullopt);
297}
298
299nb::typed<nb::object, PyOpView> PyOperationIterator::dunderNext() {
300 parentOperation->checkValid();
301 if (mlirOperationIsNull(next)) {
302 PyErr_SetNone(PyExc_StopIteration);
303 // python functions should return NULL after setting any exception
304 return nb::object();
305 }
306
307 PyOperationRef returnOperation =
308 PyOperation::forOperation(parentOperation->getContext(), next);
309 next = mlirOperationGetNextInBlock(next);
310 return returnOperation->createOpView();
311}
312
313void PyOperationIterator::bind(nb::module_ &m) {
314 nb::class_<PyOperationIterator>(m, "OperationIterator")
315 .def("__iter__", &PyOperationIterator::dunderIter,
316 "Returns an iterator over the operations in an operation's block.")
317 .def("__next__", &PyOperationIterator::dunderNext,
318 "Returns the next operation in the iteration.");
319}
320
322 parentOperation->checkValid();
323 return PyOperationIterator(parentOperation,
325}
326
328 parentOperation->checkValid();
329 intptr_t count = 0;
330 MlirOperation childOp = mlirBlockGetFirstOperation(block);
331 while (!mlirOperationIsNull(childOp)) {
332 count += 1;
333 childOp = mlirOperationGetNextInBlock(childOp);
334 }
335 return count;
336}
337
338nb::typed<nb::object, PyOpView> PyOperationList::dunderGetItem(intptr_t index) {
339 parentOperation->checkValid();
340 if (index < 0) {
341 index += dunderLen();
342 }
343 if (index < 0) {
344 throw nb::index_error("attempt to access out of bounds operation");
345 }
346 MlirOperation childOp = mlirBlockGetFirstOperation(block);
347 while (!mlirOperationIsNull(childOp)) {
348 if (index == 0) {
349 return PyOperation::forOperation(parentOperation->getContext(), childOp)
350 ->createOpView();
351 }
352 childOp = mlirOperationGetNextInBlock(childOp);
353 index -= 1;
354 }
355 throw nb::index_error("attempt to access out of bounds operation");
356}
357
358void PyOperationList::bind(nb::module_ &m) {
359 nb::class_<PyOperationList>(m, "OperationList")
360 .def("__getitem__", &PyOperationList::dunderGetItem,
361 "Returns the operation at the specified index.")
362 .def("__iter__", &PyOperationList::dunderIter,
363 "Returns an iterator over operations in the list.")
364 .def("__len__", &PyOperationList::dunderLen,
365 "Returns the number of operations in the list.");
366}
367
368nb::typed<nb::object, PyOpView> PyOpOperand::getOwner() const {
369 MlirOperation owner = mlirOpOperandGetOwner(opOperand);
373}
375size_t PyOpOperand::getOperandNumber() const {
376 return mlirOpOperandGetOperandNumber(opOperand);
377}
378
379void PyOpOperand::bind(nb::module_ &m) {
380 nb::class_<PyOpOperand>(m, "OpOperand")
381 .def_prop_ro("owner", &PyOpOperand::getOwner,
382 "Returns the operation that owns this operand.")
383 .def_prop_ro("operand_number", &PyOpOperand::getOperandNumber,
384 "Returns the operand number in the owning operation.");
385}
386
387nb::typed<nb::object, PyOpOperand> PyOpOperandIterator::dunderNext() {
388 if (mlirOpOperandIsNull(opOperand)) {
389 PyErr_SetNone(PyExc_StopIteration);
390 // python functions should return NULL after setting any exception
391 return nb::object();
392 }
393
394 PyOpOperand returnOpOperand(opOperand);
395 opOperand = mlirOpOperandGetNextUse(opOperand);
396 return nb::cast(returnOpOperand);
397}
398
399void PyOpOperandIterator::bind(nb::module_ &m) {
400 nb::class_<PyOpOperandIterator>(m, "OpOperandIterator")
401 .def("__iter__", &PyOpOperandIterator::dunderIter,
402 "Returns an iterator over operands.")
403 .def("__next__", &PyOpOperandIterator::dunderNext,
404 "Returns the next operand in the iteration.");
405}
407//------------------------------------------------------------------------------
408// PyThreadPool
409//------------------------------------------------------------------------------
410
412
414 if (threadPool.ptr)
415 mlirLlvmThreadPoolDestroy(threadPool);
416}
419 return mlirLlvmThreadPoolGetMaxConcurrency(threadPool);
420}
421
422std::string PyThreadPool::_mlir_thread_pool_ptr() const {
423 std::stringstream ss;
424 ss << threadPool.ptr;
425 return ss.str();
426}
428//------------------------------------------------------------------------------
429// PyMlirContext
430//------------------------------------------------------------------------------
431
432PyMlirContext::PyMlirContext(MlirContext context) : context(context) {
433 nb::gil_scoped_acquire acquire;
434 nb::ft_lock_guard lock(live_contexts_mutex);
435 auto &liveContexts = getLiveContexts();
436 liveContexts[context.ptr] = this;
437}
438
440 // Note that the only public way to construct an instance is via the
441 // forContext method, which always puts the associated handle into
442 // liveContexts.
443 nb::gil_scoped_acquire acquire;
444 {
445 nb::ft_lock_guard lock(live_contexts_mutex);
446 getLiveContexts().erase(context.ptr);
447 }
448 mlirContextDestroy(context);
449}
452 return PyMlirContextRef(this, nb::cast(this));
453}
455nb::object PyMlirContext::getCapsule() {
456 return nb::steal<nb::object>(mlirPythonContextToCapsule(get()));
457}
458
459nb::object PyMlirContext::createFromCapsule(nb::object capsule) {
460 MlirContext rawContext = mlirPythonCapsuleToContext(capsule.ptr());
461 if (mlirContextIsNull(rawContext))
462 throw nb::python_error();
463 return forContext(rawContext).releaseObject();
464}
465
466PyMlirContextRef PyMlirContext::forContext(MlirContext context) {
467 nb::gil_scoped_acquire acquire;
468 nb::ft_lock_guard lock(live_contexts_mutex);
469 auto &liveContexts = getLiveContexts();
470 auto it = liveContexts.find(context.ptr);
471 if (it == liveContexts.end()) {
472 // Create.
473 PyMlirContext *unownedContextWrapper = new PyMlirContext(context);
474 nb::object pyRef = nb::cast(unownedContextWrapper);
475 assert(pyRef && "cast to nb::object failed");
476 liveContexts[context.ptr] = unownedContextWrapper;
477 return PyMlirContextRef(unownedContextWrapper, std::move(pyRef));
478 }
479 // Use existing.
480 nb::object pyRef = nb::cast(it->second);
481 return PyMlirContextRef(it->second, std::move(pyRef));
482}
483
484nb::ft_mutex PyMlirContext::live_contexts_mutex;
485
486PyMlirContext::LiveContextMap &PyMlirContext::getLiveContexts() {
487 static LiveContextMap liveContexts;
488 return liveContexts;
489}
490
492 nb::ft_lock_guard lock(live_contexts_mutex);
493 return getLiveContexts().size();
494}
496nb::object PyMlirContext::contextEnter(nb::object context) {
497 return PyThreadContextEntry::pushContext(context);
498}
499
500void PyMlirContext::contextExit(const nb::object &excType,
501 const nb::object &excVal,
502 const nb::object &excTb) {
504}
505
506nb::object PyMlirContext::attachDiagnosticHandler(nb::object callback) {
507 // Note that ownership is transferred to the delete callback below by way of
508 // an explicit inc_ref (borrow).
509 PyDiagnosticHandler *pyHandler =
510 new PyDiagnosticHandler(get(), std::move(callback));
511 nb::object pyHandlerObject =
512 nb::cast(pyHandler, nb::rv_policy::take_ownership);
513 (void)pyHandlerObject.inc_ref();
514
515 // In these C callbacks, the userData is a PyDiagnosticHandler* that is
516 // guaranteed to be known to pybind.
517 auto handlerCallback =
518 +[](MlirDiagnostic diagnostic, void *userData) -> MlirLogicalResult {
519 // Since this can be called from arbitrary C++ contexts, always get the GIL.
520 nb::gil_scoped_acquire gil;
521 PyDiagnostic *pyDiagnostic = new PyDiagnostic(diagnostic);
522 nb::object pyDiagnosticObject =
523 nb::cast(pyDiagnostic, nb::rv_policy::take_ownership);
524
525 auto *pyHandler = static_cast<PyDiagnosticHandler *>(userData);
526 bool result = false;
527 try {
528 result = nb::cast<bool>(pyHandler->callback(pyDiagnostic));
529 } catch (std::exception &e) {
530 fprintf(stderr, "MLIR Python Diagnostic handler raised exception: %s\n",
531 e.what());
532 pyHandler->hadError = true;
533 }
534
535 pyDiagnostic->invalidate();
537 };
538 auto deleteCallback = +[](void *userData) {
539 // May run during context destruction, so always get the GIL.
540 nb::gil_scoped_acquire gil;
541 auto *pyHandler = static_cast<PyDiagnosticHandler *>(userData);
542 assert(pyHandler->registeredID && "handler is not registered");
543 pyHandler->registeredID.reset();
544
545 // Decrement reference, balancing the inc_ref() above.
546 nb::object pyHandlerObject = nb::cast(pyHandler, nb::rv_policy::reference);
547 pyHandlerObject.dec_ref();
548 };
549
550 pyHandler->registeredID = mlirContextAttachDiagnosticHandler(
551 get(), handlerCallback, static_cast<void *>(pyHandler), deleteCallback);
552 return pyHandlerObject;
553}
554
555MlirLogicalResult PyMlirContext::ErrorCapture::handler(MlirDiagnostic diag,
556 void *userData) {
557 auto *self = static_cast<ErrorCapture *>(userData);
558 // Check if the context requested we emit errors instead of capturing them.
559 if (self->ctx->emitErrorDiagnostics)
561
562 if (mlirDiagnosticGetSeverity(diag) !=
563 MlirDiagnosticSeverity::MlirDiagnosticError)
565
566 // This may be invoked from a thread that is not attached to the
567 // interpreter (e.g. while PassManager.run has released the GIL),
568 // so reacquire the GIL.
569 nb::gil_scoped_acquire acquire;
570 self->errors.emplace_back(PyDiagnostic(diag).getInfo());
572}
573
576 if (!context) {
577 throw std::runtime_error(
578 "An MLIR function requires a Context but none was provided in the call "
579 "or from the surrounding environment. Either pass to the function with "
580 "a 'context=' argument or establish a default using 'with Context():'");
581 }
582 return *context;
583}
585//------------------------------------------------------------------------------
586// PyThreadContextEntry management
587//------------------------------------------------------------------------------
588
589std::vector<PyThreadContextEntry> &PyThreadContextEntry::getStack() {
590 static thread_local std::vector<PyThreadContextEntry> stack;
591 return stack;
592}
593
595 auto &stack = getStack();
596 if (stack.empty())
597 return nullptr;
598 return &stack.back();
599}
600
601void PyThreadContextEntry::push(FrameKind frameKind, nb::object context,
602 nb::object insertionPoint,
603 nb::object location) {
604 auto &stack = getStack();
605 stack.emplace_back(frameKind, std::move(context), std::move(insertionPoint),
606 std::move(location));
607 // If the new stack has more than one entry and the context of the new top
608 // entry matches the previous, copy the insertionPoint and location from the
609 // previous entry if missing from the new top entry.
610 if (stack.size() > 1) {
611 auto &prev = *(stack.rbegin() + 1);
612 auto &current = stack.back();
613 if (current.context.is(prev.context)) {
614 // Default non-context objects from the previous entry.
615 if (!current.insertionPoint)
616 current.insertionPoint = prev.insertionPoint;
617 if (!current.location)
618 current.location = prev.location;
619 }
620 }
621}
622
624 if (!context)
625 return nullptr;
626 return nb::cast<PyMlirContext *>(context);
627}
628
630 if (!insertionPoint)
631 return nullptr;
632 return nb::cast<PyInsertionPoint *>(insertionPoint);
633}
634
636 if (!location)
637 return nullptr;
638 return nb::cast<PyLocation *>(location);
639}
640
642 auto *tos = getTopOfStack();
643 return tos ? tos->getContext() : nullptr;
644}
645
647 auto *tos = getTopOfStack();
648 return tos ? tos->getInsertionPoint() : nullptr;
649}
650
652 auto *tos = getTopOfStack();
653 return tos ? tos->getLocation() : nullptr;
654}
655
656nb::object PyThreadContextEntry::pushContext(nb::object context) {
657 push(FrameKind::Context, /*context=*/context,
658 /*insertionPoint=*/nb::object(),
659 /*location=*/nb::object());
660 return context;
661}
662
664 auto &stack = getStack();
665 if (stack.empty())
666 throw std::runtime_error("Unbalanced Context enter/exit");
667 auto &tos = stack.back();
668 if (tos.frameKind != FrameKind::Context && tos.getContext() != &context)
669 throw std::runtime_error("Unbalanced Context enter/exit");
670 stack.pop_back();
671}
672
673nb::object
674PyThreadContextEntry::pushInsertionPoint(nb::object insertionPointObj) {
675 PyInsertionPoint &insertionPoint =
676 nb::cast<PyInsertionPoint &>(insertionPointObj);
677 nb::object contextObj =
678 insertionPoint.getBlock().getParentOperation()->getContext().getObject();
679 push(FrameKind::InsertionPoint,
680 /*context=*/contextObj,
681 /*insertionPoint=*/insertionPointObj,
682 /*location=*/nb::object());
683 return insertionPointObj;
684}
685
687 auto &stack = getStack();
688 if (stack.empty())
689 throw std::runtime_error("Unbalanced InsertionPoint enter/exit");
690 auto &tos = stack.back();
691 if (tos.frameKind != FrameKind::InsertionPoint &&
692 tos.getInsertionPoint() != &insertionPoint)
693 throw std::runtime_error("Unbalanced InsertionPoint enter/exit");
694 stack.pop_back();
695}
696
697nb::object PyThreadContextEntry::pushLocation(nb::object locationObj) {
698 PyLocation &location = nb::cast<PyLocation &>(locationObj);
699 nb::object contextObj = location.getContext().getObject();
700 push(FrameKind::Location, /*context=*/contextObj,
701 /*insertionPoint=*/nb::object(),
702 /*location=*/locationObj);
703 return locationObj;
704}
705
707 auto &stack = getStack();
708 if (stack.empty())
709 throw std::runtime_error("Unbalanced Location enter/exit");
710 auto &tos = stack.back();
711 if (tos.frameKind != FrameKind::Location && tos.getLocation() != &location)
712 throw std::runtime_error("Unbalanced Location enter/exit");
713 stack.pop_back();
714}
716//------------------------------------------------------------------------------
717// PyDiagnostic*
718//------------------------------------------------------------------------------
719
721 valid = false;
722 if (materializedNotes) {
723 for (nb::handle noteObject : *materializedNotes) {
724 PyDiagnostic *note = nb::cast<PyDiagnostic *>(noteObject);
725 note->invalidate();
726 }
727 }
728}
729
731 nb::object callback)
732 : context(context), callback(std::move(callback)) {}
733
735
737 if (!registeredID)
738 return;
739 MlirDiagnosticHandlerID localID = *registeredID;
740 mlirContextDetachDiagnosticHandler(context, localID);
741 assert(!registeredID && "should have unregistered");
742 // Not strictly necessary but keeps stale pointers from being around to cause
743 // issues.
744 context = {nullptr};
745}
746
747void PyDiagnostic::checkValid() {
748 if (!valid) {
749 throw std::invalid_argument(
750 "Diagnostic is invalid (used outside of callback)");
751 }
752}
753
755 checkValid();
756 return static_cast<PyDiagnosticSeverity>(
757 mlirDiagnosticGetSeverity(diagnostic));
758}
759
760nb::typed<nb::object, PyLocation> PyDiagnostic::getLocation() {
761 checkValid();
762 MlirLocation loc = mlirDiagnosticGetLocation(diagnostic);
763 MlirContext context = mlirLocationGetContext(loc);
764 return PyLocation(PyMlirContext::forContext(context), loc).maybeDownCast();
765}
766
767nb::str PyDiagnostic::getMessage() {
768 checkValid();
769 nb::object fileObject = nb::module_::import_("io").attr("StringIO")();
770 PyFileAccumulator accum(fileObject, /*binary=*/false);
771 mlirDiagnosticPrint(diagnostic, accum.getCallback(), accum.getUserData());
772 return nb::cast<nb::str>(fileObject.attr("getvalue")());
773}
774
775nb::typed<nb::tuple, PyDiagnostic> PyDiagnostic::getNotes() {
776 checkValid();
777 if (materializedNotes)
778 return *materializedNotes;
779 intptr_t numNotes = mlirDiagnosticGetNumNotes(diagnostic);
780 nb::tuple notes = nb::steal<nb::tuple>(PyTuple_New(numNotes));
781 for (intptr_t i = 0; i < numNotes; ++i) {
782 MlirDiagnostic noteDiag = mlirDiagnosticGetNote(diagnostic, i);
783 nb::object diagnostic = nb::cast(PyDiagnostic(noteDiag));
784 PyTuple_SetItem(notes.ptr(), i, diagnostic.release().ptr());
785 }
786 materializedNotes = std::move(notes);
787
788 return *materializedNotes;
789}
790
792 std::vector<DiagnosticInfo> notes;
793 for (nb::handle n : getNotes())
794 notes.emplace_back(nb::cast<PyDiagnostic>(n).getInfo());
795 return {getSeverity(), nb::cast<PyLocation>(getLocation()),
796 nb::cast<std::string>(getMessage()), std::move(notes)};
797}
799//------------------------------------------------------------------------------
800// PyDialect, PyDialectDescriptor, PyDialects, PyDialectRegistry
801//------------------------------------------------------------------------------
802
803MlirDialect PyDialects::getDialectForKey(const std::string &key,
804 bool attrError) {
805 MlirDialect dialect = mlirContextGetOrLoadDialect(getContext()->get(),
806 {key.data(), key.size()});
807 if (mlirDialectIsNull(dialect)) {
808 std::string msg = join("Dialect '", key, "' not found");
809 if (attrError)
810 throw nb::attribute_error(msg.c_str());
811 throw nb::index_error(msg.c_str());
812 }
813 return dialect;
814}
817 return nb::steal<nb::object>(mlirPythonDialectRegistryToCapsule(*this));
818}
819
821 MlirDialectRegistry rawRegistry =
823 if (mlirDialectRegistryIsNull(rawRegistry))
824 throw nb::python_error();
825 return PyDialectRegistry(rawRegistry);
826}
828//------------------------------------------------------------------------------
829// PyLocation
830//------------------------------------------------------------------------------
832nb::object PyLocation::getCapsule() {
833 return nb::steal<nb::object>(mlirPythonLocationToCapsule(*this));
834}
835
836PyLocation PyLocation::createFromCapsule(nb::object capsule) {
837 MlirLocation rawLoc = mlirPythonCapsuleToLocation(capsule.ptr());
838 if (mlirLocationIsNull(rawLoc))
839 throw nb::python_error();
841 rawLoc);
842}
844nb::object PyLocation::contextEnter(nb::object locationObj) {
845 return PyThreadContextEntry::pushLocation(locationObj);
846}
847
848void PyLocation::contextExit(const nb::object &excType,
849 const nb::object &excVal,
850 const nb::object &excTb) {
852}
853
856 if (!location) {
857 throw std::runtime_error(
858 "An MLIR function requires a Location but none was provided in the "
859 "call or from the surrounding environment. Either pass to the function "
860 "with a 'loc=' argument or establish a default using 'with loc:'");
861 }
862 return *location;
863}
864
865//------------------------------------------------------------------------------
866// PyModule
867//------------------------------------------------------------------------------
868
869PyModule::PyModule(PyMlirContextRef contextRef, MlirModule module)
870 : BaseContextObject(std::move(contextRef)), module(module) {}
871
873 nb::gil_scoped_acquire acquire;
874 auto &liveModules = getContext()->liveModules;
875 assert(liveModules.count(module.ptr) == 1 &&
876 "destroying module not in live map");
877 liveModules.erase(module.ptr);
878 mlirModuleDestroy(module);
879}
880
881PyModuleRef PyModule::forModule(MlirModule module) {
882 MlirContext context = mlirModuleGetContext(module);
883 PyMlirContextRef contextRef = PyMlirContext::forContext(context);
884
885 nb::gil_scoped_acquire acquire;
886 auto &liveModules = contextRef->liveModules;
887 auto it = liveModules.find(module.ptr);
888 if (it == liveModules.end()) {
889 // Create.
890 PyModule *unownedModule = new PyModule(std::move(contextRef), module);
891 // Note that the default return value policy on cast is automatic_reference,
892 // which does not take ownership (delete will not be called).
893 // Just be explicit.
894 nb::object pyRef = nb::cast(unownedModule, nb::rv_policy::take_ownership);
895 unownedModule->handle = pyRef;
896 liveModules[module.ptr] =
897 std::make_pair(unownedModule->handle, unownedModule);
898 return PyModuleRef(unownedModule, std::move(pyRef));
899 }
900 // Use existing.
901 PyModule *existing = it->second.second;
902 nb::object pyRef = nb::borrow<nb::object>(it->second.first);
903 return PyModuleRef(existing, std::move(pyRef));
904}
905
906nb::object PyModule::createFromCapsule(nb::object capsule) {
907 MlirModule rawModule = mlirPythonCapsuleToModule(capsule.ptr());
908 if (mlirModuleIsNull(rawModule))
909 throw nb::python_error();
910 return forModule(rawModule).releaseObject();
911}
912
913nb::object PyModule::getCapsule() {
914 return nb::steal<nb::object>(mlirPythonModuleToCapsule(get()));
915}
917//------------------------------------------------------------------------------
918// PyOperation
919//------------------------------------------------------------------------------
920
921PyOperation::PyOperation(PyMlirContextRef contextRef, MlirOperation operation)
922 : BaseContextObject(std::move(contextRef)), operation(operation) {}
923
925 // If the operation has already been invalidated there is nothing to do.
926 if (!valid)
927 return;
928 // Otherwise, invalidate the operation when it is attached.
929 if (isAttached())
930 setInvalid();
931 else {
932 // And destroy it when it is detached, i.e. owned by Python.
933 erase();
934 }
935}
936
937namespace {
938// Constructs a new object of type T in-place on the Python heap, returning a
939// PyObjectRef to it, loosely analogous to std::make_shared<T>().
940template <typename T, class... Args>
941PyObjectRef<T> makeObjectRef(Args &&...args) {
942 nb::handle type = nb::type<T>();
943 nb::object instance = nb::inst_alloc(type);
944 T *ptr = nb::inst_ptr<T>(instance);
945 new (ptr) T(std::forward<Args>(args)...);
946 nb::inst_mark_ready(instance);
947 return PyObjectRef<T>(ptr, std::move(instance));
948}
949} // namespace
950
951PyOperationRef PyOperation::createInstance(PyMlirContextRef contextRef,
952 MlirOperation operation,
953 nb::object parentKeepAlive) {
954 // Create.
955 PyOperationRef unownedOperation =
956 makeObjectRef<PyOperation>(std::move(contextRef), operation);
957 unownedOperation->handle = unownedOperation.getObject();
958 if (parentKeepAlive) {
959 unownedOperation->parentKeepAlive = std::move(parentKeepAlive);
960 }
961 return unownedOperation;
962}
963
965 MlirOperation operation,
966 nb::object parentKeepAlive) {
967 return createInstance(std::move(contextRef), operation,
968 std::move(parentKeepAlive));
969}
970
972 MlirOperation operation,
973 nb::object parentKeepAlive) {
974 PyOperationRef created = createInstance(std::move(contextRef), operation,
975 std::move(parentKeepAlive));
976 created->attached = false;
977 return created;
978}
979
981 const std::string &sourceStr,
982 const std::string &sourceName) {
983 PyMlirContext::ErrorCapture errors(contextRef);
984 MlirOperation op =
985 mlirOperationCreateParse(contextRef->get(), toMlirStringRef(sourceStr),
986 toMlirStringRef(sourceName));
987 if (mlirOperationIsNull(op))
988 throw MLIRError("Unable to parse operation assembly", errors.take());
989 return PyOperation::createDetached(std::move(contextRef), op);
990}
991
994 setDetached();
995 parentKeepAlive = nb::object();
996}
997
998MlirOperation PyOperation::get() const {
999 checkValid();
1000 return operation;
1001}
1004 return PyOperationRef(this, nb::borrow<nb::object>(handle));
1005}
1006
1007void PyOperation::setAttached(const nb::object &parent) {
1008 assert(!attached && "operation already attached");
1009 attached = true;
1010}
1011
1013 assert(attached && "operation already detached");
1014 attached = false;
1015}
1016
1017void PyOperation::checkValid() const {
1018 if (!valid) {
1019 throw std::runtime_error("the operation has been invalidated");
1020 }
1021}
1022
1023void PyOperationBase::print(std::optional<int64_t> largeElementsLimit,
1024 std::optional<int64_t> largeResourceLimit,
1025 bool enableDebugInfo, bool prettyDebugInfo,
1026 bool printGenericOpForm, bool useLocalScope,
1027 bool useNameLocAsPrefix, bool assumeVerified,
1028 nb::object fileObject, bool binary,
1029 bool skipRegions) {
1030 PyOperation &operation = getOperation();
1031 operation.checkValid();
1032 if (fileObject.is_none())
1033 fileObject = nb::module_::import_("sys").attr("stdout");
1034
1035 MlirOpPrintingFlags flags = mlirOpPrintingFlagsCreate();
1036 if (largeElementsLimit)
1037 mlirOpPrintingFlagsElideLargeElementsAttrs(flags, *largeElementsLimit);
1038 if (largeResourceLimit)
1039 mlirOpPrintingFlagsElideLargeResourceString(flags, *largeResourceLimit);
1040 if (enableDebugInfo)
1041 mlirOpPrintingFlagsEnableDebugInfo(flags, /*enable=*/true,
1042 /*prettyForm=*/prettyDebugInfo);
1043 if (printGenericOpForm)
1045 if (useLocalScope)
1047 if (assumeVerified)
1049 if (skipRegions)
1051 if (useNameLocAsPrefix)
1053
1054 PyFileAccumulator accum(fileObject, binary);
1055 mlirOperationPrintWithFlags(operation, flags, accum.getCallback(),
1056 accum.getUserData());
1058}
1059
1060void PyOperationBase::print(PyAsmState &state, nb::object fileObject,
1061 bool binary) {
1062 PyOperation &operation = getOperation();
1063 operation.checkValid();
1064 if (fileObject.is_none())
1065 fileObject = nb::module_::import_("sys").attr("stdout");
1066 PyFileAccumulator accum(fileObject, binary);
1067 mlirOperationPrintWithState(operation, state.get(), accum.getCallback(),
1068 accum.getUserData());
1069}
1070
1071void PyOperationBase::writeBytecode(const nb::object &fileOrStringObject,
1072 std::optional<int64_t> bytecodeVersion) {
1073 PyOperation &operation = getOperation();
1074 operation.checkValid();
1075 PyFileAccumulator accum(fileOrStringObject, /*binary=*/true);
1076
1077 if (!bytecodeVersion.has_value())
1078 return mlirOperationWriteBytecode(operation, accum.getCallback(),
1079 accum.getUserData());
1080
1081 MlirBytecodeWriterConfig config = mlirBytecodeWriterConfigCreate();
1082 mlirBytecodeWriterConfigDesiredEmitVersion(config, *bytecodeVersion);
1084 operation, config, accum.getCallback(), accum.getUserData());
1087 throw nb::value_error(
1088 join("Unable to honor desired bytecode version ", *bytecodeVersion)
1089 .c_str());
1090}
1091
1092void PyOperationBase::walk(std::function<PyWalkResult(MlirOperation)> callback,
1093 PyWalkOrder walkOrder) {
1094 PyOperation &operation = getOperation();
1095 operation.checkValid();
1096 struct UserData {
1097 std::function<PyWalkResult(MlirOperation)> callback;
1098 bool gotException;
1099 std::string exceptionWhat;
1100 nb::object exceptionType;
1101 };
1102 UserData userData{callback, false, {}, {}};
1103 MlirOperationWalkCallback walkCallback = [](MlirOperation op,
1104 void *userData) {
1105 UserData *calleeUserData = static_cast<UserData *>(userData);
1106 try {
1107 return static_cast<MlirWalkResult>((calleeUserData->callback)(op));
1108 } catch (nb::python_error &e) {
1109 calleeUserData->gotException = true;
1110 calleeUserData->exceptionWhat = std::string(e.what());
1111 calleeUserData->exceptionType = nb::borrow(e.type());
1112 return MlirWalkResult::MlirWalkResultInterrupt;
1113 }
1114 };
1115 mlirOperationWalk(operation, walkCallback, &userData,
1116 static_cast<MlirWalkOrder>(walkOrder));
1117 if (userData.gotException) {
1118 std::string message("Exception raised in callback: ");
1119 message.append(userData.exceptionWhat);
1120 throw std::runtime_error(message);
1121 }
1122}
1123
1124nb::object PyOperationBase::getAsm(bool binary,
1125 std::optional<int64_t> largeElementsLimit,
1126 std::optional<int64_t> largeResourceLimit,
1127 bool enableDebugInfo, bool prettyDebugInfo,
1128 bool printGenericOpForm, bool useLocalScope,
1129 bool useNameLocAsPrefix, bool assumeVerified,
1130 bool skipRegions) {
1131 nb::object fileObject;
1132 if (binary) {
1133 fileObject = nb::module_::import_("io").attr("BytesIO")();
1134 } else {
1135 fileObject = nb::module_::import_("io").attr("StringIO")();
1136 }
1137 print(/*largeElementsLimit=*/largeElementsLimit,
1138 /*largeResourceLimit=*/largeResourceLimit,
1139 /*enableDebugInfo=*/enableDebugInfo,
1140 /*prettyDebugInfo=*/prettyDebugInfo,
1141 /*printGenericOpForm=*/printGenericOpForm,
1142 /*useLocalScope=*/useLocalScope,
1143 /*useNameLocAsPrefix=*/useNameLocAsPrefix,
1144 /*assumeVerified=*/assumeVerified,
1145 /*fileObject=*/fileObject,
1146 /*binary=*/binary,
1147 /*skipRegions=*/skipRegions);
1148
1149 return fileObject.attr("getvalue")();
1150}
1151
1153 PyOperation &operation = getOperation();
1154 PyOperation &otherOp = other.getOperation();
1155 operation.checkValid();
1156 otherOp.checkValid();
1157 mlirOperationMoveAfter(operation, otherOp);
1158 operation.parentKeepAlive = otherOp.parentKeepAlive;
1159}
1160
1162 PyOperation &operation = getOperation();
1163 PyOperation &otherOp = other.getOperation();
1164 operation.checkValid();
1165 otherOp.checkValid();
1166 mlirOperationMoveBefore(operation, otherOp);
1167 operation.parentKeepAlive = otherOp.parentKeepAlive;
1168}
1169
1171 PyOperation &operation = getOperation();
1172 PyOperation &otherOp = other.getOperation();
1173 operation.checkValid();
1174 otherOp.checkValid();
1175 return mlirOperationIsBeforeInBlock(operation, otherOp);
1176}
1177
1179 PyOperation &operation = getOperation();
1180 PyOperation &otherOp = other.getOperation();
1181 operation.checkValid();
1182 otherOp.checkValid();
1183 return mlirOperationIsAncestor(operation, otherOp);
1184}
1185
1187 PyOperation &operation = getOperation();
1188 PyOperation &otherOp = other.getOperation();
1189 operation.checkValid();
1190 otherOp.checkValid();
1191 return mlirOperationIsProperAncestor(operation, otherOp);
1192}
1193
1195 PyOperation &op = getOperation();
1198 throw MLIRError("Verification failed", errors.take());
1199 return true;
1200}
1201
1202std::optional<PyOperationRef> PyOperation::getParentOperation() {
1203 checkValid();
1204 if (!isAttached())
1205 throw nb::value_error("Detached operations have no parent");
1206 MlirOperation operation = mlirOperationGetParentOperation(get());
1207 if (mlirOperationIsNull(operation))
1208 return {};
1209 return PyOperation::forOperation(getContext(), operation);
1210}
1211
1213 checkValid();
1214 std::optional<PyOperationRef> parentOperation = getParentOperation();
1215 MlirBlock block = mlirOperationGetBlock(get());
1216 assert(!mlirBlockIsNull(block) && "Attached operation has null parent");
1217 assert(parentOperation && "Operation has no parent");
1218 return PyBlock{std::move(*parentOperation), block};
1219}
1220
1222 checkValid();
1223 return nb::steal<nb::object>(mlirPythonOperationToCapsule(get()));
1224}
1225
1226nb::object PyOperation::createFromCapsule(const nb::object &capsule) {
1227 MlirOperation rawOperation = mlirPythonCapsuleToOperation(capsule.ptr());
1228 if (mlirOperationIsNull(rawOperation))
1229 throw nb::python_error();
1230 MlirContext rawCtxt = mlirOperationGetContext(rawOperation);
1231 return forOperation(PyMlirContext::forContext(rawCtxt), rawOperation)
1232 .releaseObject();
1233}
1234
1235static void maybeInsertOperation(PyOperationRef &op,
1236 const nb::object &maybeIp) {
1237 // InsertPoint active?
1238 if (!maybeIp.is(nb::cast(false))) {
1239 PyInsertionPoint *ip;
1240 if (maybeIp.is_none()) {
1242 } else {
1243 ip = nb::cast<PyInsertionPoint *>(maybeIp);
1244 }
1245 if (ip)
1246 ip->insert(*op.get());
1247 }
1248}
1249
1250nb::object PyOperation::create(std::string_view name,
1251 std::optional<std::vector<PyType *>> results,
1252 const MlirValue *operands, size_t numOperands,
1253 std::optional<nb::dict> attributes,
1254 std::optional<std::vector<PyBlock *>> successors,
1255 int regions, PyLocation &location,
1256 const nb::object &maybeIp, bool inferType) {
1257 std::vector<MlirType> mlirResults;
1258 std::vector<MlirBlock> mlirSuccessors;
1259 std::vector<std::pair<std::string, MlirAttribute>> mlirAttributes;
1260
1261 // General parameter validation.
1262 if (regions < 0)
1263 throw nb::value_error("number of regions must be >= 0");
1264
1265 // Unpack/validate results.
1266 if (results) {
1267 mlirResults.reserve(results->size());
1268 for (PyType *result : *results) {
1269 // TODO: Verify result type originate from the same context.
1270 if (!result)
1271 throw nb::value_error("result type cannot be None");
1272 mlirResults.push_back(*result);
1273 }
1274 }
1275 // Unpack/validate attributes.
1276 if (attributes) {
1277 mlirAttributes.reserve(attributes->size());
1278 for (std::pair<nb::handle, nb::handle> it : *attributes) {
1279 std::string key;
1280 try {
1281 key = nb::cast<std::string>(it.first);
1282 } catch (nb::cast_error &err) {
1283 std::string msg = join("Invalid attribute key (not a string) when "
1284 "attempting to create the operation \"",
1285 name, "\" (", err.what(), ")");
1286 throw nb::type_error(msg.c_str());
1287 }
1288 try {
1289 auto &attribute = nb::cast<PyAttribute &>(it.second);
1290 // TODO: Verify attribute originates from the same context.
1291 mlirAttributes.emplace_back(std::move(key), attribute);
1292 } catch (std::exception &err) {
1293 if (it.second.is_none()) {
1294 std::string msg = join(
1295 "Found an invalid (`None`?) attribute value for the key \"", key,
1296 "\" when attempting to create the operation \"", name, "\"");
1297 throw std::runtime_error(msg);
1298 }
1299 std::string msg = join("Invalid attribute value for the key \"", key,
1300 "\" when attempting to create the operation \"",
1301 name, "\" (", err.what(), ")");
1302 throw nb::type_error(msg.c_str());
1303 }
1304 }
1305 }
1306 // Unpack/validate successors.
1307 if (successors) {
1308 mlirSuccessors.reserve(successors->size());
1309 for (PyBlock *successor : *successors) {
1310 // TODO: Verify successor originate from the same context.
1311 if (!successor)
1312 throw nb::value_error("successor block cannot be None");
1313 mlirSuccessors.push_back(successor->get());
1314 }
1315 }
1316
1317 // Apply unpacked/validated to the operation state. Beyond this
1318 // point, exceptions cannot be thrown or else the state will leak.
1319 MlirOperationState state =
1320 mlirOperationStateGet(toMlirStringRef(name), location);
1321 if (numOperands > 0)
1322 mlirOperationStateAddOperands(&state, numOperands, operands);
1323 state.enableResultTypeInference = inferType;
1324 if (!mlirResults.empty())
1325 mlirOperationStateAddResults(&state, mlirResults.size(),
1326 mlirResults.data());
1327 if (!mlirAttributes.empty()) {
1328 // Note that the attribute names directly reference bytes in
1329 // mlirAttributes, so that vector must not be changed from here
1330 // on.
1331 std::vector<MlirNamedAttribute> mlirNamedAttributes;
1332 mlirNamedAttributes.reserve(mlirAttributes.size());
1333 for (const std::pair<std::string, MlirAttribute> &it : mlirAttributes)
1334 mlirNamedAttributes.push_back(mlirNamedAttributeGet(
1336 toMlirStringRef(it.first)),
1337 it.second));
1338 mlirOperationStateAddAttributes(&state, mlirNamedAttributes.size(),
1339 mlirNamedAttributes.data());
1340 }
1341 if (!mlirSuccessors.empty())
1342 mlirOperationStateAddSuccessors(&state, mlirSuccessors.size(),
1343 mlirSuccessors.data());
1344 if (regions) {
1345 std::vector<MlirRegion> mlirRegions;
1346 mlirRegions.resize(regions);
1347 for (int i = 0; i < regions; ++i)
1348 mlirRegions[i] = mlirRegionCreate();
1349 mlirOperationStateAddOwnedRegions(&state, mlirRegions.size(),
1350 mlirRegions.data());
1351 }
1352
1353 // Construct the operation.
1354 PyMlirContext::ErrorCapture errors(location.getContext());
1355 MlirOperation operation = mlirOperationCreate(&state);
1356 if (!operation.ptr)
1357 throw MLIRError("Operation creation failed", errors.take());
1358 PyOperationRef created =
1359 PyOperation::createDetached(location.getContext(), operation);
1360 maybeInsertOperation(created, maybeIp);
1361
1362 return created.getObject();
1363}
1364
1365nb::object PyOperation::clone(const nb::object &maybeIp) {
1366 MlirOperation clonedOperation = mlirOperationClone(operation);
1367 PyOperationRef cloned =
1368 PyOperation::createDetached(getContext(), clonedOperation);
1369 maybeInsertOperation(cloned, maybeIp);
1370
1371 return cloned->createOpView();
1372}
1373
1374nb::object PyOperation::createOpView() {
1375 checkValid();
1376 MlirIdentifier ident = mlirOperationGetName(get());
1377 MlirStringRef identStr = mlirIdentifierStr(ident);
1378 auto operationCls = PyGlobals::get().lookupOperationClass(
1379 std::string_view(identStr.data, identStr.length));
1380 if (operationCls)
1381 return PyOpView::constructDerived(*operationCls, getRef().getObject());
1382 return nb::cast(PyOpView(getRef().getObject()));
1383}
1384
1385void PyOperation::erase() {
1387 setInvalid();
1388 mlirOperationDestroy(operation);
1389}
1390
1391void PyOpResult::bindDerived(ClassTy &c) {
1392 c.def_prop_ro(
1393 "owner",
1394 [](PyOpResult &self) -> nb::typed<nb::object, PyOpView> {
1395 assert(mlirOperationEqual(self.getParentOperation()->get(),
1396 mlirOpResultGetOwner(self.get())) &&
1397 "expected the owner of the value in Python to match that in "
1398 "the IR");
1399 return self.getParentOperation()->createOpView();
1400 },
1401 "Returns the operation that produces this result.");
1402 c.def_prop_ro(
1403 "result_number",
1404 [](PyOpResult &self) { return mlirOpResultGetResultNumber(self.get()); },
1405 "Returns the position of this result in the operation's result list.");
1407
1408/// Returns the list of types of the values held by container.
1409template <typename Container>
1410static std::vector<nb::typed<nb::object, PyType>>
1411getValueTypes(Container &container, PyMlirContextRef &context) {
1412 std::vector<nb::typed<nb::object, PyType>> result;
1413 result.reserve(container.size());
1414 for (int i = 0, e = container.size(); i < e; ++i) {
1415 result.push_back(PyType(context->getRef(),
1416 mlirValueGetType(container.getElement(i).get()))
1418 }
1419 return result;
1420}
1421
1423 intptr_t length, intptr_t step)
1424 : Sliceable(startIndex,
1426 : length,
1427 step),
1428 operation(std::move(operation)) {}
1429
1430void PyOpResultList::bindDerived(ClassTy &c) {
1431 c.def_prop_ro(
1432 "types",
1433 [](PyOpResultList &self) {
1434 return getValueTypes(self, self.operation->getContext());
1435 },
1436 "Returns a list of types for all results in this result list.");
1437 c.def_prop_ro(
1438 "owner",
1439 [](PyOpResultList &self) -> nb::typed<nb::object, PyOpView> {
1440 return self.operation->createOpView();
1441 },
1442 "Returns the operation that owns this result list.");
1443}
1444
1445intptr_t PyOpResultList::getRawNumElements() {
1446 operation->checkValid();
1447 return mlirOperationGetNumResults(operation->get());
1448}
1449
1450PyOpResult PyOpResultList::getRawElement(intptr_t index) {
1451 PyValue value(operation, mlirOperationGetResult(operation->get(), index));
1452 return PyOpResult(value);
1453}
1454
1455PyOpResultList PyOpResultList::slice(intptr_t startIndex, intptr_t length,
1456 intptr_t step) const {
1457 return PyOpResultList(operation, startIndex, length, step);
1458}
1460//------------------------------------------------------------------------------
1461// PyOpView
1462//------------------------------------------------------------------------------
1463
1464static void populateResultTypes(std::string_view name,
1465 nb::sequence resultTypeList,
1466 const nb::object &resultSegmentSpecObj,
1467 std::vector<int32_t> &resultSegmentLengths,
1468 std::vector<PyType *> &resultTypes) {
1469 resultTypes.reserve(nb::len(resultTypeList));
1470 if (resultSegmentSpecObj.is_none()) {
1471 // Non-variadic result unpacking.
1472 size_t index = 0;
1473 for (nb::handle resultType : resultTypeList) {
1474 try {
1475 resultTypes.push_back(nb::cast<PyType *>(resultType));
1476 if (!resultTypes.back())
1477 throw nb::cast_error();
1478 } catch (nb::cast_error &err) {
1479 throw nb::value_error(join("Result ", index, " of operation \"", name,
1480 "\" must be a Type (", err.what(), ")")
1481 .c_str());
1482 }
1483 ++index;
1484 }
1485 } else {
1486 // Sized result unpacking.
1487 auto resultSegmentSpec = nb::cast<std::vector<int>>(resultSegmentSpecObj);
1488 if (resultSegmentSpec.size() != nb::len(resultTypeList)) {
1489 throw nb::value_error(
1490 join("Operation \"", name, "\" requires ", resultSegmentSpec.size(),
1491 " result segments but was provided ", nb::len(resultTypeList))
1492 .c_str());
1493 }
1494 resultSegmentLengths.reserve(nb::len(resultTypeList));
1495 for (size_t i = 0, e = resultSegmentSpec.size(); i < e; ++i) {
1496 int segmentSpec = resultSegmentSpec[i];
1497 if (segmentSpec == 1 || segmentSpec == 0) {
1498 // Unpack unary element.
1499 try {
1500 auto *resultType = nb::cast<PyType *>(resultTypeList[i]);
1501 if (resultType) {
1502 resultTypes.push_back(resultType);
1503 resultSegmentLengths.push_back(1);
1504 } else if (segmentSpec == 0) {
1505 // Allowed to be optional.
1506 resultSegmentLengths.push_back(0);
1507 } else {
1508 throw nb::value_error(
1509 join("Result ", i, " of operation \"", name,
1510 "\" must be a Type (was None and result is not optional)")
1511 .c_str());
1512 }
1513 } catch (nb::cast_error &err) {
1514 throw nb::value_error(join("Result ", i, " of operation \"", name,
1515 "\" must be a Type (", err.what(), ")")
1516 .c_str());
1517 }
1518 } else if (segmentSpec == -1) {
1519 // Unpack sequence by appending.
1520 try {
1521 if (resultTypeList[i].is_none()) {
1522 // Treat it as an empty list.
1523 resultSegmentLengths.push_back(0);
1524 } else {
1525 // Unpack the list.
1526 auto segment = nb::cast<nb::sequence>(resultTypeList[i]);
1527 for (nb::handle segmentItem : segment) {
1528 resultTypes.push_back(nb::cast<PyType *>(segmentItem));
1529 if (!resultTypes.back()) {
1530 throw nb::type_error("contained a None item");
1531 }
1532 }
1533 resultSegmentLengths.push_back(nb::len(segment));
1534 }
1535 } catch (std::exception &err) {
1536 // NOTE: Sloppy to be using a catch-all here, but there are at least
1537 // three different unrelated exceptions that can be thrown in the
1538 // above "casts". Just keep the scope above small and catch them all.
1539 throw nb::value_error(join("Result ", i, " of operation \"", name,
1540 "\" must be a Sequence of Types (",
1541 err.what(), ")")
1542 .c_str());
1543 }
1544 } else {
1545 throw nb::value_error("Unexpected segment spec");
1547 }
1548 }
1549}
1550
1551MlirValue getUniqueResult(MlirOperation operation) {
1552 auto numResults = mlirOperationGetNumResults(operation);
1553 if (numResults != 1) {
1554 auto name = mlirIdentifierStr(mlirOperationGetName(operation));
1555 throw nb::value_error(
1556 join("Cannot call .result on operation ",
1557 std::string_view(name.data, name.length), " which has ",
1558 numResults,
1559 " results (it is only valid for operations with a "
1560 "single result)")
1561 .c_str());
1562 }
1563 return mlirOperationGetResult(operation, 0);
1564}
1565
1566static MlirValue getOpResultOrValue(nb::handle operand) {
1567 if (operand.is_none()) {
1568 throw nb::value_error("contained a None item");
1569 }
1570 PyOperationBase *op;
1571 if (nb::try_cast<PyOperationBase *>(operand, op)) {
1572 return getUniqueResult(op->getOperation());
1573 }
1574 PyOpResultList *opResultList;
1575 if (nb::try_cast<PyOpResultList *>(operand, opResultList)) {
1576 return getUniqueResult(opResultList->getOperation()->get());
1577 }
1578 PyValue *value;
1579 if (nb::try_cast<PyValue *>(operand, value)) {
1580 return value->get();
1581 }
1582 throw nb::value_error("is not a Value");
1583}
1584
1585nb::typed<nb::object, PyOperation> PyOpView::buildGeneric(
1586 std::string_view name, std::tuple<int, bool> opRegionSpec,
1587 nb::object operandSegmentSpecObj, nb::object resultSegmentSpecObj,
1588 std::optional<nb::sequence> resultTypeList, nb::sequence operandList,
1589 std::optional<nb::dict> attributes,
1590 std::optional<std::vector<PyBlock *>> successors,
1591 std::optional<int> regions, PyLocation &location,
1592 const nb::object &maybeIp) {
1593 PyMlirContextRef context = location.getContext();
1594
1595 // Class level operation construction metadata.
1596 // Operand and result segment specs are either none, which does no
1597 // variadic unpacking, or a list of ints with segment sizes, where each
1598 // element is either a positive number (typically 1 for a scalar) or -1 to
1599 // indicate that it is derived from the length of the same-indexed operand
1600 // or result (implying that it is a list at that position).
1601 std::vector<int32_t> operandSegmentLengths;
1602 std::vector<int32_t> resultSegmentLengths;
1603
1604 // Validate/determine region count.
1605 int opMinRegionCount = std::get<0>(opRegionSpec);
1606 bool opHasNoVariadicRegions = std::get<1>(opRegionSpec);
1607 if (!regions) {
1608 regions = opMinRegionCount;
1609 }
1610 if (*regions < opMinRegionCount) {
1611 throw nb::value_error(join("Operation \"", name,
1612 "\" requires a minimum of ", opMinRegionCount,
1613 " regions but was built with regions=", *regions)
1614 .c_str());
1615 }
1616 if (opHasNoVariadicRegions && *regions > opMinRegionCount) {
1617 throw nb::value_error(join("Operation \"", name,
1618 "\" requires a maximum of ", opMinRegionCount,
1619 " regions but was built with regions=", *regions)
1620 .c_str());
1621 }
1622
1623 // Unpack results.
1624 std::vector<PyType *> resultTypes;
1625 if (resultTypeList.has_value()) {
1626 populateResultTypes(name, *resultTypeList, resultSegmentSpecObj,
1627 resultSegmentLengths, resultTypes);
1628 }
1629
1630 // Unpack operands.
1631 std::vector<MlirValue> operands;
1632 operands.reserve(operands.size());
1633 size_t index = 0;
1634 if (operandSegmentSpecObj.is_none()) {
1635 // Non-sized operand unpacking.
1636 for (nb::handle operand : operandList) {
1637 try {
1638 operands.push_back(getOpResultOrValue(operand));
1639 } catch (nb::builtin_exception &err) {
1640 throw nb::value_error(join("Operand ", index, " of operation \"", name,
1641 "\" must be a Value (", err.what(), ")")
1642 .c_str());
1643 }
1644 ++index;
1645 }
1646 } else {
1647 // Sized operand unpacking.
1648 auto operandSegmentSpec = nb::cast<std::vector<int>>(operandSegmentSpecObj);
1649 if (operandSegmentSpec.size() != nb::len(operandList)) {
1650 throw nb::value_error(
1651 join("Operation \"", name, "\" requires ", operandSegmentSpec.size(),
1652 "operand segments but was provided ", nb::len(operandList))
1653 .c_str());
1654 }
1655 operandSegmentLengths.reserve(nb::len(operandList));
1656 for (size_t i = 0, e = operandSegmentSpec.size(); i < e; ++i) {
1657 int segmentSpec = operandSegmentSpec[i];
1658 if (segmentSpec == 1 || segmentSpec == 0) {
1659 // Unpack unary element.
1660 const nanobind::handle operand = operandList[i];
1661 if (!operand.is_none()) {
1662 try {
1663 operands.push_back(getOpResultOrValue(operand));
1664 } catch (nb::builtin_exception &err) {
1665 throw nb::value_error(join("Operand ", i, " of operation \"", name,
1666 "\" must be a Value (", err.what(), ")")
1667 .c_str());
1668 }
1669
1670 operandSegmentLengths.push_back(1);
1671 } else if (segmentSpec == 0) {
1672 // Allowed to be optional.
1673 operandSegmentLengths.push_back(0);
1674 } else {
1675 throw nb::value_error(
1676 join("Operand ", i, " of operation \"", name,
1677 "\" must be a Value (was None and operand is not optional)")
1678 .c_str());
1679 }
1680 } else if (segmentSpec == -1) {
1681 // Unpack sequence by appending.
1682 try {
1683 if (operandList[i].is_none()) {
1684 // Treat it as an empty list.
1685 operandSegmentLengths.push_back(0);
1686 } else {
1687 // Unpack the list.
1688 auto segment = nb::cast<nb::sequence>(operandList[i]);
1689 for (nb::handle segmentItem : segment) {
1690 operands.push_back(getOpResultOrValue(segmentItem));
1691 }
1692 operandSegmentLengths.push_back(nb::len(segment));
1693 }
1694 } catch (std::exception &err) {
1695 // NOTE: Sloppy to be using a catch-all here, but there are at least
1696 // three different unrelated exceptions that can be thrown in the
1697 // above "casts". Just keep the scope above small and catch them all.
1698 throw nb::value_error(join("Operand ", i, " of operation \"", name,
1699 "\" must be a Sequence of Values (",
1700 err.what(), ")")
1701 .c_str());
1702 }
1703 } else {
1704 throw nb::value_error("Unexpected segment spec");
1705 }
1706 }
1707 }
1708
1709 // Merge operand/result segment lengths into attributes if needed.
1710 if (!operandSegmentLengths.empty() || !resultSegmentLengths.empty()) {
1711 // Dup.
1712 if (attributes) {
1713 attributes = nb::dict(*attributes);
1714 } else {
1715 attributes = nb::dict();
1716 }
1717 if (attributes->contains("resultSegmentSizes") ||
1718 attributes->contains("operandSegmentSizes")) {
1719 throw nb::value_error("Manually setting a 'resultSegmentSizes' or "
1720 "'operandSegmentSizes' attribute is unsupported. "
1721 "Use Operation.create for such low-level access.");
1722 }
1723
1724 // Add resultSegmentSizes attribute.
1725 if (!resultSegmentLengths.empty()) {
1726 MlirAttribute segmentLengthAttr =
1727 mlirDenseI32ArrayGet(context->get(), resultSegmentLengths.size(),
1728 resultSegmentLengths.data());
1729 (*attributes)["resultSegmentSizes"] =
1730 PyAttribute(context, segmentLengthAttr);
1731 }
1732
1733 // Add operandSegmentSizes attribute.
1734 if (!operandSegmentLengths.empty()) {
1735 MlirAttribute segmentLengthAttr =
1736 mlirDenseI32ArrayGet(context->get(), operandSegmentLengths.size(),
1737 operandSegmentLengths.data());
1738 (*attributes)["operandSegmentSizes"] =
1739 PyAttribute(context, segmentLengthAttr);
1740 }
1741 }
1742
1743 // Delegate to create.
1744 return PyOperation::create(name,
1745 /*results=*/std::move(resultTypes),
1746 /*operands=*/operands.data(),
1747 /*numOperands=*/operands.size(),
1748 /*attributes=*/std::move(attributes),
1749 /*successors=*/std::move(successors),
1750 /*regions=*/*regions, location, maybeIp,
1751 !resultTypeList);
1752}
1753
1754nb::object PyOpView::constructDerived(const nb::object &cls,
1755 const nb::object &operation) {
1756 nb::handle opViewType = nb::type<PyOpView>();
1757 nb::object instance = cls.attr("__new__")(cls);
1758 opViewType.attr("__init__")(instance, operation);
1759 return instance;
1760}
1761
1762PyOpView::PyOpView(const nb::object &operationObject)
1763 // Casting through the PyOperationBase base-class and then back to the
1764 // Operation lets us accept any PyOperationBase subclass.
1765 : operation(nb::cast<PyOperationBase &>(operationObject).getOperation()),
1766 operationObject(operation.getRef().getObject()) {}
1768//------------------------------------------------------------------------------
1769// PyAsmState
1770//------------------------------------------------------------------------------
1771
1772PyAsmState::PyAsmState(MlirValue value, bool useLocalScope) {
1773 flags = mlirOpPrintingFlagsCreate();
1774 // The OpPrintingFlags are not exposed Python side, create locally and
1775 // associate lifetime with the state.
1776 if (useLocalScope)
1778 state = mlirAsmStateCreateForValue(value, flags);
1779}
1780
1781PyAsmState::PyAsmState(PyOperationBase &operation, bool useLocalScope) {
1782 flags = mlirOpPrintingFlagsCreate();
1783 // The OpPrintingFlags are not exposed Python side, create locally and
1784 // associate lifetime with the state.
1785 if (useLocalScope)
1787 state = mlirAsmStateCreateForOperation(operation.getOperation().get(), flags);
1788}
1790//------------------------------------------------------------------------------
1791// PyInsertionPoint.
1792//------------------------------------------------------------------------------
1793
1794PyInsertionPoint::PyInsertionPoint(const PyBlock &block) : block(block) {}
1797 : refOperation(beforeOperationBase.getOperation().getRef()),
1798 block((*refOperation)->getBlock()) {}
1799
1801 : refOperation(beforeOperationRef), block((*refOperation)->getBlock()) {}
1802
1803void PyInsertionPoint::insert(PyOperationBase &operationBase) {
1804 PyOperation &operation = operationBase.getOperation();
1805 if (operation.isAttached())
1806 throw nb::value_error(
1807 "Attempt to insert operation that is already attached");
1808 block.getParentOperation()->checkValid();
1809 MlirOperation beforeOp = {nullptr};
1810 if (refOperation) {
1811 // Insert before operation.
1812 (*refOperation)->checkValid();
1813 beforeOp = (*refOperation)->get();
1814 } else {
1815 // Insert at end (before null) is only valid if the block does not
1816 // already end in a known terminator (violating this will cause assertion
1817 // failures later).
1818 if (!mlirOperationIsNull(mlirBlockGetTerminator(block.get()))) {
1819 throw nb::index_error("Cannot insert operation at the end of a block "
1820 "that already has a terminator. Did you mean to "
1821 "use 'InsertionPoint.at_block_terminator(block)' "
1822 "versus 'InsertionPoint(block)'?");
1823 }
1825 mlirBlockInsertOwnedOperationBefore(block.get(), beforeOp, operation);
1826 operation.setAttached();
1827}
1828
1830 MlirOperation firstOp = mlirBlockGetFirstOperation(block.get());
1831 if (mlirOperationIsNull(firstOp)) {
1832 // Just insert at end.
1833 return PyInsertionPoint(block);
1834 }
1835
1836 // Insert before first op.
1838 block.getParentOperation()->getContext(), firstOp);
1839 return PyInsertionPoint{block, std::move(firstOpRef)};
1840}
1841
1843 MlirOperation terminator = mlirBlockGetTerminator(block.get());
1844 if (mlirOperationIsNull(terminator))
1845 throw nb::value_error("Block has no terminator");
1847 block.getParentOperation()->getContext(), terminator);
1848 return PyInsertionPoint{block, std::move(terminatorOpRef)};
1849}
1850
1852 PyOperation &operation = op.getOperation();
1853 PyBlock block = operation.getBlock();
1854 MlirOperation nextOperation = mlirOperationGetNextInBlock(operation);
1855 if (mlirOperationIsNull(nextOperation))
1856 return PyInsertionPoint(block);
1858 block.getParentOperation()->getContext(), nextOperation);
1859 return PyInsertionPoint{block, std::move(nextOpRef)};
1860}
1861
1862size_t PyMlirContext::getLiveModuleCount() { return liveModules.size(); }
1864nb::object PyInsertionPoint::contextEnter(nb::object insertPoint) {
1865 return PyThreadContextEntry::pushInsertionPoint(std::move(insertPoint));
1866}
1867
1868void PyInsertionPoint::contextExit(const nb::object &excType,
1869 const nb::object &excVal,
1870 const nb::object &excTb) {
1872}
1874//------------------------------------------------------------------------------
1875// PyAttribute.
1876//------------------------------------------------------------------------------
1878bool PyAttribute::operator==(const PyAttribute &other) const {
1879 return mlirAttributeEqual(attr, other.attr);
1880}
1882nb::object PyAttribute::getCapsule() {
1883 return nb::steal<nb::object>(mlirPythonAttributeToCapsule(*this));
1884}
1885
1886PyAttribute PyAttribute::createFromCapsule(const nb::object &capsule) {
1887 MlirAttribute rawAttr = mlirPythonCapsuleToAttribute(capsule.ptr());
1888 if (mlirAttributeIsNull(rawAttr))
1889 throw nb::python_error();
1890 return PyAttribute(
1892}
1893
1894nb::typed<nb::object, PyAttribute> PyAttribute::maybeDownCast() {
1895 MlirTypeID mlirTypeID = mlirAttributeGetTypeID(this->get());
1896 assert(!mlirTypeIDIsNull(mlirTypeID) &&
1897 "mlirTypeID was expected to be non-null.");
1898 std::optional<nb::callable> typeCaster = PyGlobals::get().lookupTypeCaster(
1899 mlirTypeID, mlirAttributeGetDialect(this->get()));
1900 // nb::rv_policy::move means use std::move to move the return value
1901 // contents into a new instance that will be owned by Python.
1902 nb::object thisObj = nb::cast(this, nb::rv_policy::move);
1903 if (!typeCaster)
1904 return thisObj;
1905 return typeCaster.value()(thisObj);
1906}
1908//------------------------------------------------------------------------------
1909// PyLocation::maybeDownCast.
1910//------------------------------------------------------------------------------
1911
1912nb::typed<nb::object, PyLocation> PyLocation::maybeDownCast() {
1913 MlirAttribute locAttr = mlirLocationGetAttribute(this->get());
1914 MlirTypeID mlirTypeID = mlirAttributeGetTypeID(locAttr);
1915 assert(!mlirTypeIDIsNull(mlirTypeID) &&
1916 "mlirTypeID was expected to be non-null.");
1917 std::optional<nb::callable> typeCaster = PyGlobals::get().lookupTypeCaster(
1918 mlirTypeID, mlirAttributeGetDialect(locAttr));
1919 nb::object thisObj = nb::cast(this, nb::rv_policy::move);
1920 if (!typeCaster)
1921 return thisObj;
1922 return typeCaster.value()(thisObj);
1923}
1925//------------------------------------------------------------------------------
1926// PyNamedAttribute.
1927//------------------------------------------------------------------------------
1928
1929PyNamedAttribute::PyNamedAttribute(MlirAttribute attr, std::string ownedName)
1930 : ownedName(new std::string(std::move(ownedName))) {
1933 toMlirStringRef(*this->ownedName)),
1934 attr);
1935}
1937//------------------------------------------------------------------------------
1938// PyType.
1939//------------------------------------------------------------------------------
1941bool PyType::operator==(const PyType &other) const {
1942 return mlirTypeEqual(type, other.type);
1943}
1945nb::object PyType::getCapsule() {
1946 return nb::steal<nb::object>(mlirPythonTypeToCapsule(*this));
1947}
1948
1949PyType PyType::createFromCapsule(nb::object capsule) {
1950 MlirType rawType = mlirPythonCapsuleToType(capsule.ptr());
1951 if (mlirTypeIsNull(rawType))
1952 throw nb::python_error();
1954 rawType);
1955}
1956
1957nb::typed<nb::object, PyType> PyType::maybeDownCast() {
1958 MlirTypeID mlirTypeID = mlirTypeGetTypeID(this->get());
1959 assert(!mlirTypeIDIsNull(mlirTypeID) &&
1960 "mlirTypeID was expected to be non-null.");
1961 std::optional<nb::callable> typeCaster = PyGlobals::get().lookupTypeCaster(
1962 mlirTypeID, mlirTypeGetDialect(this->get()));
1963 // nb::rv_policy::move means use std::move to move the return value
1964 // contents into a new instance that will be owned by Python.
1965 nb::object thisObj = nb::cast(this, nb::rv_policy::move);
1966 if (!typeCaster)
1967 return thisObj;
1968 return typeCaster.value()(thisObj);
1969}
1971//------------------------------------------------------------------------------
1972// PyTypeID.
1973//------------------------------------------------------------------------------
1975nb::object PyTypeID::getCapsule() {
1976 return nb::steal<nb::object>(mlirPythonTypeIDToCapsule(*this));
1977}
1978
1979PyTypeID PyTypeID::createFromCapsule(nb::object capsule) {
1980 MlirTypeID mlirTypeID = mlirPythonCapsuleToTypeID(capsule.ptr());
1981 if (mlirTypeIDIsNull(mlirTypeID))
1982 throw nb::python_error();
1983 return PyTypeID(mlirTypeID);
1984}
1985bool PyTypeID::operator==(const PyTypeID &other) const {
1986 return mlirTypeIDEqual(typeID, other.typeID);
1987}
1989//------------------------------------------------------------------------------
1990// PyValue and subclasses.
1991//------------------------------------------------------------------------------
1993nb::object PyValue::getCapsule() {
1994 return nb::steal<nb::object>(mlirPythonValueToCapsule(get()));
1995}
1996
1997static PyOperationRef getValueOwnerRef(MlirValue value) {
1998 MlirOperation owner;
1999 if (mlirValueIsAOpResult(value))
2000 owner = mlirOpResultGetOwner(value);
2001 else if (mlirValueIsABlockArgument(value))
2003 else
2004 assert(false && "Value must be an block arg or op result.");
2005 if (mlirOperationIsNull(owner))
2006 throw nb::python_error();
2007 MlirContext ctx = mlirOperationGetContext(owner);
2009}
2010
2011nb::typed<nb::object, std::variant<PyBlockArgument, PyOpResult, PyValue>>
2013 MlirType type = mlirValueGetType(get());
2014 MlirTypeID mlirTypeID = mlirTypeGetTypeID(type);
2015 assert(!mlirTypeIDIsNull(mlirTypeID) &&
2016 "mlirTypeID was expected to be non-null.");
2017 std::optional<nb::callable> valueCaster =
2019 // nb::rv_policy::move means use std::move to move the return value
2020 // contents into a new instance that will be owned by Python.
2021 nb::object thisObj;
2022 if (mlirValueIsAOpResult(value))
2023 thisObj = nb::cast<PyOpResult>(*this, nb::rv_policy::move);
2024 else if (mlirValueIsABlockArgument(value))
2025 thisObj = nb::cast<PyBlockArgument>(*this, nb::rv_policy::move);
2026 else
2027 assert(false && "Value must be an block arg or op result.");
2028 if (valueCaster)
2029 return valueCaster.value()(thisObj);
2030 return thisObj;
2031}
2032
2033PyValue PyValue::createFromCapsule(nb::object capsule) {
2034 MlirValue value = mlirPythonCapsuleToValue(capsule.ptr());
2035 if (mlirValueIsNull(value))
2036 throw nb::python_error();
2037 PyOperationRef ownerRef = getValueOwnerRef(value);
2038 return PyValue(ownerRef, value);
2039}
2041//------------------------------------------------------------------------------
2042// PySymbolTable.
2043//------------------------------------------------------------------------------
2044
2046 : operation(operation.getOperation().getRef()) {
2047 symbolTable = mlirSymbolTableCreate(operation.getOperation().get());
2048 if (mlirSymbolTableIsNull(symbolTable)) {
2049 throw nb::type_error("Operation is not a Symbol Table.");
2050 }
2051}
2052
2053nb::object PySymbolTable::dunderGetItem(const std::string &name) {
2054 operation->checkValid();
2055 MlirOperation symbol = mlirSymbolTableLookup(
2056 symbolTable, mlirStringRefCreate(name.data(), name.length()));
2057 if (mlirOperationIsNull(symbol))
2058 throw nb::key_error(
2059 join("Symbol '", name, "' not in the symbol table.").c_str());
2060
2061 return PyOperation::forOperation(operation->getContext(), symbol,
2062 operation.getObject())
2063 ->createOpView();
2064}
2065
2067 operation->checkValid();
2068 symbol.getOperation().checkValid();
2069 mlirSymbolTableErase(symbolTable, symbol.getOperation().get());
2070 // The operation is also erased, so we must invalidate it. There may be Python
2071 // references to this operation so we don't want to delete it from the list of
2072 // live operations here.
2073 symbol.getOperation().valid = false;
2074}
2075
2076void PySymbolTable::dunderDel(const std::string &name) {
2077 nb::object operation = dunderGetItem(name);
2078 erase(nb::cast<PyOperationBase &>(operation));
2079}
2080
2082 operation->checkValid();
2083 symbol.getOperation().checkValid();
2084 MlirAttribute symbolAttr = mlirOperationGetAttributeByName(
2086 if (mlirAttributeIsNull(symbolAttr))
2087 throw nb::value_error("Expected operation to have a symbol name.");
2089 symbol.getOperation().getContext(),
2090 mlirSymbolTableInsert(symbolTable, symbol.getOperation().get()));
2091}
2092
2094 // Op must already be a symbol.
2095 PyOperation &operation = symbol.getOperation();
2096 operation.checkValid();
2098 MlirAttribute existingNameAttr =
2099 mlirOperationGetAttributeByName(operation.get(), attrName);
2100 if (mlirAttributeIsNull(existingNameAttr))
2101 throw nb::value_error("Expected operation to have a symbol name.");
2102 return PyStringAttribute(symbol.getOperation().getContext(),
2103 existingNameAttr);
2104}
2105
2107 const std::string &name) {
2108 // Op must already be a symbol.
2109 PyOperation &operation = symbol.getOperation();
2110 operation.checkValid();
2112 MlirAttribute existingNameAttr =
2113 mlirOperationGetAttributeByName(operation.get(), attrName);
2114 if (mlirAttributeIsNull(existingNameAttr))
2115 throw nb::value_error("Expected operation to have a symbol name.");
2116 MlirAttribute newNameAttr =
2117 mlirStringAttrGet(operation.getContext()->get(), toMlirStringRef(name));
2118 mlirOperationSetAttributeByName(operation.get(), attrName, newNameAttr);
2119}
2120
2122 PyOperation &operation = symbol.getOperation();
2123 operation.checkValid();
2125 MlirAttribute existingVisAttr =
2126 mlirOperationGetAttributeByName(operation.get(), attrName);
2127 if (mlirAttributeIsNull(existingVisAttr))
2128 throw nb::value_error("Expected operation to have a symbol visibility.");
2129 return PyStringAttribute(symbol.getOperation().getContext(), existingVisAttr);
2130}
2131
2133 const std::string &visibility) {
2134 if (visibility != "public" && visibility != "private" &&
2135 visibility != "nested")
2136 throw nb::value_error(
2137 "Expected visibility to be 'public', 'private' or 'nested'");
2138 PyOperation &operation = symbol.getOperation();
2139 operation.checkValid();
2141 MlirAttribute existingVisAttr =
2142 mlirOperationGetAttributeByName(operation.get(), attrName);
2143 if (mlirAttributeIsNull(existingVisAttr))
2144 throw nb::value_error("Expected operation to have a symbol visibility.");
2145 MlirAttribute newVisAttr = mlirStringAttrGet(operation.getContext()->get(),
2146 toMlirStringRef(visibility));
2147 mlirOperationSetAttributeByName(operation.get(), attrName, newVisAttr);
2148}
2149
2150void PySymbolTable::replaceAllSymbolUses(const std::string &oldSymbol,
2151 const std::string &newSymbol,
2152 PyOperationBase &from) {
2153 PyOperation &fromOperation = from.getOperation();
2154 fromOperation.checkValid();
2156 toMlirStringRef(oldSymbol), toMlirStringRef(newSymbol),
2158
2159 throw nb::value_error("Symbol rename failed");
2160}
2161
2163 bool allSymUsesVisible,
2164 nb::object callback) {
2165 PyOperation &fromOperation = from.getOperation();
2166 fromOperation.checkValid();
2167 struct UserData {
2168 PyMlirContextRef context;
2169 nb::object callback;
2170 bool gotException;
2171 std::string exceptionWhat;
2172 nb::object exceptionType;
2173 };
2174 UserData userData{
2175 fromOperation.getContext(), std::move(callback), false, {}, {}};
2177 fromOperation.get(), allSymUsesVisible,
2178 [](MlirOperation foundOp, bool isVisible, void *calleeUserDataVoid) {
2179 UserData *calleeUserData = static_cast<UserData *>(calleeUserDataVoid);
2180 auto pyFoundOp =
2181 PyOperation::forOperation(calleeUserData->context, foundOp);
2182 if (calleeUserData->gotException)
2183 return;
2184 try {
2185 calleeUserData->callback(pyFoundOp.getObject(), isVisible);
2186 } catch (nb::python_error &e) {
2187 calleeUserData->gotException = true;
2188 calleeUserData->exceptionWhat = e.what();
2189 calleeUserData->exceptionType = nb::borrow(e.type());
2190 }
2191 },
2192 static_cast<void *>(&userData));
2193 if (userData.gotException) {
2194 std::string message("Exception raised in callback: ");
2195 message.append(userData.exceptionWhat);
2196 throw std::runtime_error(message);
2197 }
2198}
2199
2200void PyBlockArgument::bindDerived(ClassTy &c) {
2201 c.def_prop_ro(
2202 "owner",
2203 [](PyBlockArgument &self) {
2204 return PyBlock(self.getParentOperation(),
2206 },
2207 "Returns the block that owns this argument.");
2208 c.def_prop_ro(
2209 "arg_number",
2210 [](PyBlockArgument &self) {
2211 return mlirBlockArgumentGetArgNumber(self.get());
2212 },
2213 "Returns the position of this argument in the block's argument list.");
2214 c.def(
2215 "set_type",
2216 [](PyBlockArgument &self, PyType type) {
2217 return mlirBlockArgumentSetType(self.get(), type);
2218 },
2219 "type"_a, "Sets the type of this block argument.");
2220 c.def(
2221 "set_location",
2222 [](PyBlockArgument &self, PyLocation loc) {
2224 },
2225 "loc"_a, "Sets the location of this block argument.");
2226}
2227
2229 MlirBlock block, intptr_t startIndex,
2232 length == -1 ? mlirBlockGetNumArguments(block) : length, step),
2233 operation(std::move(operation)), block(block) {}
2234
2235void PyBlockArgumentList::bindDerived(ClassTy &c) {
2236 c.def_prop_ro(
2237 "types",
2238 [](PyBlockArgumentList &self) {
2239 return getValueTypes(self, self.operation->getContext());
2240 },
2241 "Returns a list of types for all arguments in this argument list.");
2242}
2243
2244intptr_t PyBlockArgumentList::getRawNumElements() {
2245 operation->checkValid();
2246 return mlirBlockGetNumArguments(block);
2247}
2248
2249PyBlockArgument PyBlockArgumentList::getRawElement(intptr_t pos) const {
2250 MlirValue argument = mlirBlockGetArgument(block, pos);
2251 return PyBlockArgument(operation, argument);
2252}
2253
2254PyBlockArgumentList PyBlockArgumentList::slice(intptr_t startIndex,
2256 intptr_t step) const {
2257 return PyBlockArgumentList(operation, block, startIndex, length, step);
2258}
2259
2261 intptr_t length, intptr_t step)
2262 : Sliceable(startIndex,
2264 : length,
2265 step),
2266 operation(operation) {}
2267
2270 mlirOperationSetOperand(operation->get(), index, value.get());
2271}
2272
2273void PyOpOperandList::bindDerived(ClassTy &c) {
2274 c.def("__setitem__", &PyOpOperandList::dunderSetItem, "index"_a, "value"_a,
2275 "Sets the operand at the specified index to a new value.");
2276}
2277
2278intptr_t PyOpOperandList::getRawNumElements() {
2279 operation->checkValid();
2280 return mlirOperationGetNumOperands(operation->get());
2281}
2282
2283PyValue PyOpOperandList::getRawElement(intptr_t pos) {
2284 MlirValue operand = mlirOperationGetOperand(operation->get(), pos);
2285 PyOperationRef pyOwner = getValueOwnerRef(operand);
2286 return PyValue(pyOwner, operand);
2287}
2288
2289PyOpOperandList PyOpOperandList::slice(intptr_t startIndex, intptr_t length,
2290 intptr_t step) const {
2291 return PyOpOperandList(operation, startIndex, length, step);
2292}
2294/// A list of OpOperands. Internally, these are stored as consecutive elements,
2295/// random access is cheap. The (returned) OpOperand list is associated with the
2296/// operation whose operands these are, and thus extends the lifetime of this
2297/// operation.
2298class PyOpOperands : public Sliceable<PyOpOperands, PyOpOperand> {
2299public:
2300 static constexpr const char *pyClassName = "OpOperands";
2302
2304 intptr_t length = -1, intptr_t step = 1)
2306 length == -1 ? mlirOperationGetNumOperands(operation->get())
2307 : length,
2308 step),
2309 operation(operation) {}
2310
2311private:
2312 /// Give the parent CRTP class access to hook implementations below.
2313 friend class Sliceable<PyOpOperands, PyOpOperand>;
2314
2315 intptr_t getRawNumElements() {
2316 operation->checkValid();
2317 return mlirOperationGetNumOperands(operation->get());
2318 }
2319
2320 PyOpOperand getRawElement(intptr_t pos) {
2321 MlirOpOperand opOperand = mlirOperationGetOpOperand(operation->get(), pos);
2322 return PyOpOperand(opOperand);
2323 }
2324
2326 return PyOpOperands(operation, startIndex, length, step);
2328
2329 PyOperationRef operation;
2330};
2331
2333 intptr_t length, intptr_t step)
2334 : Sliceable(startIndex,
2336 : length,
2337 step),
2338 operation(operation) {}
2339
2342 mlirOperationSetSuccessor(operation->get(), index, block.get());
2343}
2344
2345void PyOpSuccessors::bindDerived(ClassTy &c) {
2346 c.def("__setitem__", &PyOpSuccessors::dunderSetItem, "index"_a, "block"_a,
2347 "Sets the successor block at the specified index.");
2348}
2349
2350intptr_t PyOpSuccessors::getRawNumElements() {
2351 operation->checkValid();
2352 return mlirOperationGetNumSuccessors(operation->get());
2353}
2354
2355PyBlock PyOpSuccessors::getRawElement(intptr_t pos) {
2356 MlirBlock block = mlirOperationGetSuccessor(operation->get(), pos);
2357 return PyBlock(operation, block);
2358}
2359
2361 intptr_t step) const {
2362 return PyOpSuccessors(operation, startIndex, length, step);
2363}
2364
2366 intptr_t startIndex, intptr_t length,
2367 intptr_t step)
2368 : Sliceable(startIndex,
2369 length == -1 ? mlirBlockGetNumSuccessors(block.get()) : length,
2370 step),
2371 operation(operation), block(block) {}
2372
2373intptr_t PyBlockSuccessors::getRawNumElements() {
2374 block.checkValid();
2375 return mlirBlockGetNumSuccessors(block.get());
2376}
2377
2378PyBlock PyBlockSuccessors::getRawElement(intptr_t pos) {
2379 MlirBlock block = mlirBlockGetSuccessor(this->block.get(), pos);
2380 return PyBlock(operation, block);
2381}
2382
2384 intptr_t step) const {
2385 return PyBlockSuccessors(block, operation, startIndex, length, step);
2386}
2387
2389 PyOperationRef operation,
2390 intptr_t startIndex, intptr_t length,
2391 intptr_t step)
2392 : Sliceable(startIndex,
2393 length == -1 ? mlirBlockGetNumPredecessors(block.get())
2394 : length,
2395 step),
2396 operation(operation), block(block) {}
2397
2398intptr_t PyBlockPredecessors::getRawNumElements() {
2399 block.checkValid();
2400 return mlirBlockGetNumPredecessors(block.get());
2401}
2402
2403PyBlock PyBlockPredecessors::getRawElement(intptr_t pos) {
2404 MlirBlock block = mlirBlockGetPredecessor(this->block.get(), pos);
2405 return PyBlock(operation, block);
2406}
2407
2408PyBlockPredecessors PyBlockPredecessors::slice(intptr_t startIndex,
2409 intptr_t length,
2410 intptr_t step) const {
2411 return PyBlockPredecessors(block, operation, startIndex, length, step);
2412}
2413
2414nb::typed<nb::object, PyAttribute>
2415PyOpAttributeMap::dunderGetItemNamed(const std::string &name) {
2416 MlirAttribute attr =
2418 if (mlirAttributeIsNull(attr)) {
2419 throw nb::key_error("attempt to access a non-existent attribute");
2421 return PyAttribute(operation->getContext(), attr).maybeDownCast();
2422}
2423
2424nb::typed<nb::object, std::optional<PyAttribute>>
2425PyOpAttributeMap::get(const std::string &key, nb::object defaultValue) {
2426 MlirAttribute attr =
2428 if (mlirAttributeIsNull(attr))
2429 return defaultValue;
2430 return PyAttribute(operation->getContext(), attr).maybeDownCast();
2431}
2432
2434 if (index < 0) {
2435 index += dunderLen();
2436 }
2437 if (index < 0 || index >= dunderLen()) {
2438 throw nb::index_error("attempt to access out of bounds attribute");
2439 }
2440 MlirNamedAttribute namedAttr =
2441 mlirOperationGetAttribute(operation->get(), index);
2442 return PyNamedAttribute(
2443 namedAttr.attribute,
2444 std::string(mlirIdentifierStr(namedAttr.name).data,
2445 mlirIdentifierStr(namedAttr.name).length));
2446}
2447
2448void PyOpAttributeMap::dunderSetItem(const std::string &name,
2449 const PyAttribute &attr) {
2450 mlirOperationSetAttributeByName(operation->get(), toMlirStringRef(name),
2451 attr);
2452}
2453
2454void PyOpAttributeMap::dunderDelItem(const std::string &name) {
2455 int removed = mlirOperationRemoveAttributeByName(operation->get(),
2457 if (!removed)
2458 throw nb::key_error("attempt to delete a non-existent attribute");
2459}
2462 return mlirOperationGetNumAttributes(operation->get());
2463}
2464
2465bool PyOpAttributeMap::dunderContains(const std::string &name) {
2466 return !mlirAttributeIsNull(
2467 mlirOperationGetAttributeByName(operation->get(), toMlirStringRef(name)));
2468}
2469
2471 MlirOperation op, std::function<void(MlirStringRef, MlirAttribute)> fn) {
2473 for (intptr_t i = 0; i < n; ++i) {
2476 fn(name, na.attribute);
2477 }
2478}
2479
2480void PyOpAttributeMap::bind(nb::module_ &m) {
2481 nb::class_<PyOpAttributeMap>(m, "OpAttributeMap")
2482 .def("__contains__", &PyOpAttributeMap::dunderContains, "name"_a,
2483 "Checks if an attribute with the given name exists in the map.")
2484 .def("__len__", &PyOpAttributeMap::dunderLen,
2485 "Returns the number of attributes in the map.")
2486 .def("__getitem__", &PyOpAttributeMap::dunderGetItemNamed, "name"_a,
2487 "Gets an attribute by name.")
2488 .def("__getitem__", &PyOpAttributeMap::dunderGetItemIndexed, "index"_a,
2489 "Gets a named attribute by index.")
2490 .def("__setitem__", &PyOpAttributeMap::dunderSetItem, "name"_a, "attr"_a,
2491 "Sets an attribute with the given name.")
2492 .def("__delitem__", &PyOpAttributeMap::dunderDelItem, "name"_a,
2493 "Deletes an attribute with the given name.")
2494 .def("get", &PyOpAttributeMap::get, nb::arg("key"),
2495 nb::arg("default") = nb::none(),
2496 "Gets an attribute by name or the default value, if it does not "
2497 "exist.")
2498 .def(
2499 "__iter__",
2500 [](PyOpAttributeMap &self) -> nb::typed<nb::iterator, nb::str> {
2501 nb::list keys;
2503 self.operation->get(), [&](MlirStringRef name, MlirAttribute) {
2504 keys.append(nb::str(name.data, name.length));
2505 });
2506 return nb::iter(keys);
2507 },
2508 "Iterates over attribute names.")
2509 .def(
2510 "keys",
2511 [](PyOpAttributeMap &self) -> nb::typed<nb::list, nb::str> {
2512 nb::list out;
2514 self.operation->get(), [&](MlirStringRef name, MlirAttribute) {
2515 out.append(nb::str(name.data, name.length));
2516 });
2517 return out;
2518 },
2519 "Returns a list of attribute names.")
2520 .def(
2521 "values",
2522 [](PyOpAttributeMap &self) -> nb::typed<nb::list, PyAttribute> {
2523 nb::list out;
2525 self.operation->get(), [&](MlirStringRef, MlirAttribute attr) {
2526 out.append(PyAttribute(self.operation->getContext(), attr)
2527 .maybeDownCast());
2528 });
2529 return out;
2530 },
2531 "Returns a list of attribute values.")
2532 .def(
2533 "items",
2534 [](PyOpAttributeMap &self)
2535 -> nb::typed<nb::list,
2536 nb::typed<nb::tuple, nb::str, PyAttribute>> {
2537 nb::list out;
2539 self.operation->get(),
2540 [&](MlirStringRef name, MlirAttribute attr) {
2541 out.append(nb::make_tuple(
2542 nb::str(name.data, name.length),
2543 PyAttribute(self.operation->getContext(), attr)
2544 .maybeDownCast()));
2545 });
2546 return out;
2547 },
2548 "Returns a list of `(name, attribute)` tuples.");
2549}
2550
2551void PyOpAdaptor::bind(nb::module_ &m) {
2552 nb::class_<PyOpAdaptor>(m, "OpAdaptor")
2553 .def(nb::init<nb::typed<nb::list, PyValue>, PyOpAttributeMap>(),
2554 "Creates an OpAdaptor with the given operands and attributes.",
2555 "operands"_a, "attributes"_a)
2556 .def(nb::init<nb::typed<nb::list, PyValue>, PyOpView &>(),
2557 "Creates an OpAdaptor with the given operands and operation view.",
2558 "operands"_a, "opview"_a)
2559 .def_prop_ro(
2560 "operands", [](PyOpAdaptor &self) { return self.operands; },
2561 "Returns the operands of the adaptor.")
2562 .def_prop_ro(
2563 "attributes", [](PyOpAdaptor &self) { return self.attributes; },
2564 "Returns the attributes of the adaptor.");
2565}
2566
2567static MlirLogicalResult verifyTraitByMethod(MlirOperation op, void *userData,
2568 const char *methodName) {
2569 nb::handle targetObj(static_cast<PyObject *>(userData));
2570 if (!nb::hasattr(targetObj, methodName))
2571 return mlirLogicalResultSuccess();
2573 nb::object opView = PyOperation::forOperation(ctx, op)->createOpView();
2574 bool success = nb::cast<bool>(targetObj.attr(methodName)(opView));
2576};
2577
2578static bool attachOpTrait(const nb::object &opName, MlirDynamicOpTrait trait,
2579 PyMlirContext &context) {
2580 std::string opNameStr;
2581 if (opName.is_type()) {
2582 opNameStr = nb::cast<std::string>(opName.attr("OPERATION_NAME"));
2583 } else if (nb::isinstance<nb::str>(opName)) {
2584 opNameStr = nb::cast<std::string>(opName);
2585 } else {
2586 throw nb::type_error("the root argument must be a type or a string");
2587 }
2590 trait, MlirStringRef{opNameStr.data(), opNameStr.size()}, context.get());
2591}
2592
2593bool PyDynamicOpTrait::attach(const nb::object &opName,
2594 const nb::object &target,
2595 PyMlirContext &context) {
2596 if (!nb::hasattr(target, "verify_invariants") &&
2597 !nb::hasattr(target, "verify_region_invariants"))
2598 throw nb::type_error(
2599 "the target object must have at least one of 'verify_invariants' or "
2600 "'verify_region_invariants' methods");
2601
2603 callbacks.construct = [](void *userData) {
2604 nb::handle(static_cast<PyObject *>(userData)).inc_ref();
2605 };
2606 callbacks.destruct = [](void *userData) {
2607 nb::handle(static_cast<PyObject *>(userData)).dec_ref();
2608 };
2609
2610 callbacks.verifyTrait = [](MlirOperation op,
2611 void *userData) -> MlirLogicalResult {
2612 return verifyTraitByMethod(op, userData, "verify_invariants");
2613 };
2614 callbacks.verifyRegionTrait = [](MlirOperation op,
2615 void *userData) -> MlirLogicalResult {
2616 return verifyTraitByMethod(op, userData, "verify_region_invariants");
2617 };
2618
2619 // To ensure that the same dynamic trait gets the same TypeID despite how many
2620 // times `attach` is called, we store it as an attribute on the target class.
2621 if (!nb::hasattr(target, typeIDAttr)) {
2622 nb::setattr(target, typeIDAttr,
2623 nb::cast(PyTypeID(PyGlobals::get().allocateTypeID())));
2624 }
2625 MlirDynamicOpTrait trait = mlirDynamicOpTraitCreate(
2626 nb::cast<PyTypeID>(target.attr(typeIDAttr)).get(), callbacks,
2627 static_cast<void *>(target.ptr()));
2628 return attachOpTrait(opName, trait, context);
2629}
2630
2631void PyDynamicOpTrait::bind(nb::module_ &m) {
2632 nb::class_<PyDynamicOpTrait> cls(m, "DynamicOpTrait");
2633 cls.attr("attach") = classmethod(
2634 [](const nb::object &cls,
2635 const nb::typed<nb::object, std::variant<nb::type_object, nb::str>>
2636 &opName,
2637 nb::object target, DefaultingPyMlirContext context) {
2638 if (target.is_none())
2639 target = cls;
2640 return PyDynamicOpTrait::attach(opName, target, *context.get());
2641 },
2642 nb::arg("cls"), nb::arg("op_name"), nb::arg("target").none() = nb::none(),
2643 nb::arg("context").none() = nb::none(),
2644 "Attach the dynamic op trait subclass to the given operation name.");
2645}
2646
2647bool PyDynamicOpTraits::IsTerminator::attach(const nb::object &opName,
2648 PyMlirContext &context) {
2649 MlirDynamicOpTrait trait = mlirDynamicOpTraitIsTerminatorCreate();
2650 return attachOpTrait(opName, trait, context);
2651}
2652
2653void PyDynamicOpTraits::IsTerminator::bind(nb::module_ &m) {
2654 nb::class_<PyDynamicOpTraits::IsTerminator, PyDynamicOpTrait> cls(
2655 m, "IsTerminatorTrait");
2656 cls.def_prop_ro_static(typeIDAttr, [](nanobind::object & /*class*/) {
2658 });
2659 cls.attr("attach") = classmethod(
2660 [](const nb::object &cls,
2661 const nb::typed<nb::object, std::variant<nb::type_object, nb::str>>
2662 &opName,
2663 DefaultingPyMlirContext context) {
2664 return PyDynamicOpTraits::IsTerminator::attach(opName, *context.get());
2666 "Attach IsTerminator trait to the given operation name.", nb::arg("cls"),
2667 nb::arg("op_name"), nb::arg("context").none() = nb::none());
2668}
2669
2670bool PyDynamicOpTraits::NoTerminator::attach(const nb::object &opName,
2671 PyMlirContext &context) {
2672 MlirDynamicOpTrait trait = mlirDynamicOpTraitNoTerminatorCreate();
2673 return attachOpTrait(opName, trait, context);
2674}
2675
2676void PyDynamicOpTraits::NoTerminator::bind(nb::module_ &m) {
2677 nb::class_<PyDynamicOpTraits::NoTerminator, PyDynamicOpTrait> cls(
2678 m, "NoTerminatorTrait");
2679 cls.def_prop_ro_static(typeIDAttr, [](nanobind::object & /*class*/) {
2681 });
2682 cls.attr("attach") = classmethod(
2683 [](const nb::object &cls,
2684 const nb::typed<nb::object, std::variant<nb::type_object, nb::str>>
2685 &opName,
2686 DefaultingPyMlirContext context) {
2687 return PyDynamicOpTraits::NoTerminator::attach(opName, *context.get());
2689 "Attach NoTerminator trait to the given operation name.", nb::arg("cls"),
2690 nb::arg("op_name"), nb::arg("context").none() = nb::none());
2691}
2692
2693bool PyDynamicOpTraits::IsIsolatedFromAbove::attach(const nb::object &opName,
2694 PyMlirContext &context) {
2695 MlirDynamicOpTrait trait = mlirDynamicOpTraitIsIsolatedFromAboveCreate();
2696 return attachOpTrait(opName, trait, context);
2697}
2698
2700 nb::class_<PyDynamicOpTraits::IsIsolatedFromAbove, PyDynamicOpTrait> cls(
2701 m, "IsIsolatedFromAboveTrait");
2702 cls.def_prop_ro_static(typeIDAttr, [](nanobind::object & /*class*/) {
2704 });
2705 cls.attr("attach") = classmethod(
2706 [](const nb::object &cls,
2707 const nb::typed<nb::object, std::variant<nb::type_object, nb::str>>
2708 &opName,
2709 DefaultingPyMlirContext context) {
2711 *context.get());
2712 },
2713 "Attach IsIsolatedFromAbove trait to the given operation name.",
2714 nb::arg("cls"), nb::arg("op_name"),
2715 nb::arg("context").none() = nb::none());
2716}
2717
2718bool PyDynamicOpTraits::RecursiveMemoryEffects::attach(const nb::object &opName,
2719 PyMlirContext &context) {
2720 MlirDynamicOpTrait trait = mlirDynamicOpTraitRecursiveMemoryEffectsCreate();
2721 return attachOpTrait(opName, trait, context);
2722}
2723
2725 nb::class_<PyDynamicOpTraits::RecursiveMemoryEffects, PyDynamicOpTrait> cls(
2726 m, "RecursiveMemoryEffectsTrait");
2727 cls.def_prop_ro_static(typeIDAttr, [](nanobind::object & /*class*/) {
2729 });
2730 cls.attr("attach") = classmethod(
2731 [](const nb::object &cls,
2732 const nb::typed<nb::object, std::variant<nb::type_object, nb::str>>
2733 &opName,
2734 DefaultingPyMlirContext context) {
2736 opName, *context.get());
2737 },
2738 "Attach RecursiveMemoryEffects trait to the given operation name.",
2739 nb::arg("cls"), nb::arg("op_name"),
2740 nb::arg("context").none() = nb::none());
2741}
2742} // namespace MLIR_BINDINGS_PYTHON_DOMAIN
2743} // namespace python
2744} // namespace mlir
2745
2746namespace {
2747using namespace mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN;
2748
2749MlirLocation tracebackToLocation(MlirContext ctx) {
2750#if defined(Py_LIMITED_API)
2751 // Frame introspection C APIs are not available under the limited API.
2752 // Traceback-based auto-location is not supported; return unknown.
2753 return mlirLocationUnknownGet(ctx);
2754#else
2755 size_t framesLimit =
2757 // Use a thread_local here to avoid requiring a large amount of space.
2758 thread_local std::array<MlirLocation, PyGlobals::TracebackLoc::kMaxFrames>
2759 frames;
2760 size_t count = 0;
2761
2762 nb::gil_scoped_acquire acquire;
2763
2764 PyThreadState *tstate = PyThreadState_GET();
2765 PyFrameObject *next;
2766 PyFrameObject *pyFrame = PyThreadState_GetFrame(tstate);
2767 // In the increment expression:
2768 // 1. get the next prev frame;
2769 // 2. decrement the ref count on the current frame (in order that it can get
2770 // gc'd, along with any objects in its closure and etc);
2771 // 3. set current = next.
2772 for (; pyFrame != nullptr && count < framesLimit;
2773 next = PyFrame_GetBack(pyFrame), Py_XDECREF(pyFrame), pyFrame = next) {
2774 PyCodeObject *code = PyFrame_GetCode(pyFrame);
2775 auto fileNameStr =
2776 nb::cast<std::string>(nb::borrow<nb::str>(code->co_filename));
2777 std::string_view fileName(fileNameStr);
2778 if (!PyGlobals::get().getTracebackLoc().isUserTracebackFilename(fileName))
2779 continue;
2780
2781 // co_qualname and PyCode_Addr2Location added in py3.11
2782#if PY_VERSION_HEX < 0x030B00F0
2783 std::string name =
2784 nb::cast<std::string>(nb::borrow<nb::str>(code->co_name));
2785 std::string_view funcName(name);
2786 int startLine = PyFrame_GetLineNumber(pyFrame);
2787 MlirLocation loc = mlirLocationFileLineColGet(
2788 ctx, mlirStringRefCreate(fileName.data(), fileName.size()), startLine,
2789 0);
2790#else
2791 std::string name =
2792 nb::cast<std::string>(nb::borrow<nb::str>(code->co_qualname));
2793 std::string_view funcName(name);
2794 int startLine, startCol, endLine, endCol;
2795 int lasti = PyFrame_GetLasti(pyFrame);
2796 if (!PyCode_Addr2Location(code, lasti, &startLine, &startCol, &endLine,
2797 &endCol)) {
2798 throw nb::python_error();
2799 }
2800 MlirLocation loc = mlirLocationFileLineColRangeGet(
2801 ctx, mlirStringRefCreate(fileName.data(), fileName.size()), startLine,
2802 startCol, endLine, endCol);
2803#endif
2804
2805 frames[count] = mlirLocationNameGet(
2806 ctx, mlirStringRefCreate(funcName.data(), funcName.size()), loc);
2807 ++count;
2808 }
2809 // When the loop breaks (after the last iter), current frame (if non-null)
2810 // is leaked without this.
2811 Py_XDECREF(pyFrame);
2812
2813 if (count == 0)
2814 return mlirLocationUnknownGet(ctx);
2815
2816 MlirLocation callee = frames[0];
2817 assert(!mlirLocationIsNull(callee) && "expected non-null callee location");
2818 if (count == 1)
2819 return callee;
2820
2821 MlirLocation caller = frames[count - 1];
2822 assert(!mlirLocationIsNull(caller) && "expected non-null caller location");
2823 for (int i = count - 2; i >= 1; i--)
2824 caller = mlirLocationCallSiteGet(frames[i], caller);
2825
2826 return mlirLocationCallSiteGet(callee, caller);
2827#endif
2828}
2829
2830/// Apply currentLocAction: wrap or fuse Location.current onto baseLoc.
2831static MlirLocation
2832applyCurrentLocAction(MlirContext ctx, MlirLocation baseLoc,
2835 if (action == Action::Fallback)
2836 return baseLoc;
2837
2838 auto *currentLoc = PyThreadContextEntry::getDefaultLocation();
2839 if (!currentLoc)
2840 return baseLoc;
2841 assert(mlirLocationGetContext(currentLoc->get()).ptr == ctx.ptr &&
2842 "Location.current must belong to the current MLIR context");
2843
2844 // NamelocWrap: walk the NameLoc chain on Location.current, collect scope
2845 // names, wrap baseLoc innermost-first so result is Outer(Inner(baseLoc)).
2846 // If Location.current is not a NameLoc, scopeNames is empty and baseLoc
2847 // is returned unchanged (nameloc_wrap is a no-op for non-NameLoc contexts).
2848 thread_local std::vector<MlirStringRef> scopeNames;
2849 scopeNames.clear();
2850 MlirLocation walk = currentLoc->get();
2851 while (mlirLocationIsAName(walk)) {
2852 scopeNames.push_back(mlirIdentifierStr(mlirLocationNameGetName(walk)));
2854 }
2855 for (auto it = scopeNames.rbegin(); it != scopeNames.rend(); ++it)
2856 baseLoc = mlirLocationNameGet(ctx, *it, baseLoc);
2857 return baseLoc;
2858}
2859
2860PyLocation
2861maybeGetTracebackLocation(const std::optional<PyLocation> &location) {
2862 auto &tbl = PyGlobals::get().getTracebackLoc();
2863
2864 // Tracebacks not enabled — return explicit loc or fall back to
2865 // Location.current.
2866 if (!tbl.locTracebacksEnabled())
2867 return location.has_value() ? location.value()
2869
2870 // From here: tracebacks are enabled.
2872 PyMlirContext &ctx = DefaultingPyMlirContext::resolve();
2873 MlirLocation baseLoc;
2874
2875 // Step 1: on_explicit — resolve explicit loc= vs traceback.
2876 if (location.has_value()) {
2877 switch (tbl.tracebackActionOnExplicitLoc()) {
2878 case OnExplicit::UseExplicit:
2879 baseLoc = location->get();
2880 break;
2881 case OnExplicit::UseTraceback:
2882 baseLoc = tracebackToLocation(ctx.get());
2883 break;
2884 }
2885 } else {
2886 baseLoc = tracebackToLocation(ctx.get());
2887 }
2888
2889 // Step 2: current_loc — compose with Location.current.
2890 baseLoc = applyCurrentLocAction(ctx.get(), baseLoc,
2891 tbl.tracebackActionOnCurrentLoc());
2892
2894 return {ref, baseLoc};
2895}
2896} // namespace
2897
2898namespace mlir {
2899namespace python {
2901static std::string formatMLIRError(const MLIRError &e) {
2902 auto locStr = [](const PyLocation &loc) {
2903 PyPrintAccumulator accum;
2904 mlirLocationPrint(loc, accum.getCallback(), accum.getUserData());
2905 std::string s = nb::cast<std::string>(nb::str(accum.join()));
2906 std::string_view sv(s);
2907 if (sv.size() > 5) {
2908 sv.remove_prefix(4); // "loc("
2909 sv.remove_suffix(1); // ")"
2910 }
2911 return std::string(sv);
2912 };
2913 auto indent = [](std::string s) {
2914 size_t pos = 0;
2915 while ((pos = s.find('\n', pos)) != std::string::npos) {
2916 s.replace(pos, 1, "\n ");
2917 pos += 3;
2918 }
2919 return s;
2920 };
2921
2922 std::ostringstream os;
2923 os << e.message;
2924 if (!e.errorDiagnostics.empty())
2925 os << ":";
2926 for (const auto &diag : e.errorDiagnostics) {
2927 os << "\nerror: " << locStr(diag.location) << ": " << indent(diag.message);
2928 for (const auto &note : diag.notes) {
2929 os << "\n note: " << locStr(note.location) << ": "
2930 << indent(note.message);
2931 }
2932 }
2933 return os.str();
2934}
2935
2936void MLIRError::bind(nb::module_ &m) {
2937 auto cls = nb::exception<MLIRError>(m, "MLIRError", PyExc_Exception);
2938 nb::register_exception_translator(
2939 [](const std::exception_ptr &p, void *payload) {
2940 try {
2941 if (p)
2942 std::rethrow_exception(p);
2943 } catch (MLIRError &e) {
2944 std::string formatted = formatMLIRError(e);
2945 nb::object ty = nb::borrow(static_cast<PyObject *>(payload));
2946 nb::object obj = ty(formatted);
2947 obj.attr("_message") = nb::cast(std::move(e.message));
2948 obj.attr("_error_diagnostics") =
2949 nb::cast(std::move(e.errorDiagnostics));
2950 PyErr_SetObject(static_cast<PyObject *>(payload), obj.ptr());
2951 }
2952 },
2953 cls.ptr());
2954 auto propertyType = nb::borrow<nb::type_object>(
2955 reinterpret_cast<PyObject *>(&PyProperty_Type));
2956 nb::setattr(
2957 cls, "message",
2958 propertyType(nb::cpp_function(
2959 [](nb::object self) -> nb::str { return self.attr("_message"); },
2960 nb::is_method())));
2961 nb::setattr(cls, "error_diagnostics",
2962 propertyType(nb::cpp_function(
2963 [](nb::object self)
2964 -> nb::typed<nb::list, PyDiagnostic::DiagnosticInfo> {
2965 return self.attr("_error_diagnostics");
2966 },
2967 nb::is_method())));
2968}
2969
2970void populateRoot(nb::module_ &m) {
2971 m.attr("T") = nb::type_var("T");
2972 m.attr("U") = nb::type_var("U");
2973
2974 // Policies for how loc_tracebacks() composes the three location sources
2975 // (explicit loc=, generated traceback, Location.current).
2976 nb::enum_<PyGlobals::TracebackLoc::OnExplicitAction>(m, "OnExplicitAction")
2977 .value("USE_EXPLICIT",
2979 .value("USE_TRACEBACK",
2981
2982 nb::enum_<PyGlobals::TracebackLoc::CurrentLocAction>(m, "CurrentLocAction")
2984 .value("NAMELOC_WRAP",
2986
2987 nb::class_<PyGlobals>(m, "_Globals")
2988 .def_prop_rw("dialect_search_modules",
2991 .def("append_dialect_search_prefix", &PyGlobals::addDialectSearchPrefix,
2992 "module_name"_a)
2993 .def(
2994 "_check_dialect_module_loaded",
2995 [](PyGlobals &self, const std::string &dialectNamespace) {
2996 return self.loadDialectModule(dialectNamespace);
2997 },
2998 "dialect_namespace"_a)
2999 .def("_register_dialect_impl", &PyGlobals::registerDialectImpl,
3000 "dialect_namespace"_a, "dialect_class"_a, nb::kw_only(),
3001 "replace"_a = false,
3002 "Testing hook for directly registering a dialect")
3003 .def("_register_operation_impl", &PyGlobals::registerOperationImpl,
3004 "operation_name"_a, "operation_class"_a, nb::kw_only(),
3005 "replace"_a = false,
3006 "Testing hook for directly registering an operation")
3007 .def("loc_tracebacks_enabled",
3008 [](PyGlobals &self) {
3009 return self.getTracebackLoc().locTracebacksEnabled();
3010 })
3011 .def("set_loc_tracebacks_enabled",
3012 [](PyGlobals &self, bool enabled) {
3014 })
3015 .def("loc_tracebacks_frame_limit",
3016 [](PyGlobals &self) {
3018 })
3019 .def("set_loc_tracebacks_frame_limit",
3020 [](PyGlobals &self, std::optional<int> n) {
3023 })
3024 .def("register_traceback_file_inclusion",
3025 [](PyGlobals &self, const std::string &filename) {
3027 })
3028 .def("register_traceback_file_exclusion",
3029 [](PyGlobals &self, const std::string &filename) {
3031 })
3032 .def("traceback_action_on_explicit_loc",
3033 [](PyGlobals &self) {
3035 })
3036 .def("set_traceback_action_on_explicit_loc",
3037 [](PyGlobals &self,
3040 })
3041 .def("traceback_action_on_current_loc",
3042 [](PyGlobals &self) {
3044 })
3045 .def("set_traceback_action_on_current_loc",
3046 [](PyGlobals &self,
3049 });
3050
3051 // Aside from making the globals accessible to python, having python manage
3052 // it is necessary to make sure it is destroyed (and releases its python
3053 // resources) properly.
3054 m.attr("globals") = nb::cast(new PyGlobals, nb::rv_policy::take_ownership);
3055
3056 // Registration decorators.
3057 m.def(
3058 "register_dialect",
3059 [](nb::type_object pyClass) {
3060 std::string dialectNamespace =
3061 nb::cast<std::string>(pyClass.attr("DIALECT_NAMESPACE"));
3062 PyGlobals::get().registerDialectImpl(dialectNamespace, pyClass);
3063 return pyClass;
3064 },
3065 "dialect_class"_a,
3066 "Class decorator for registering a custom Dialect wrapper");
3067 m.def(
3068 "register_operation",
3069 [](const nb::type_object &dialectClass, bool replace) -> nb::object {
3070 return nb::cpp_function(
3071 [dialectClass,
3072 replace](nb::type_object opClass) -> nb::type_object {
3073 std::string operationName =
3074 nb::cast<std::string>(opClass.attr("OPERATION_NAME"));
3075 PyGlobals::get().registerOperationImpl(operationName, opClass,
3076 replace);
3077 // Dict-stuff the new opClass by name onto the dialect class.
3078 nb::object opClassName = opClass.attr("__name__");
3079 dialectClass.attr(opClassName) = opClass;
3080 return opClass;
3081 });
3082 },
3083 // clang-format off
3084 nb::sig("def register_operation(dialect_class: type, *, replace: bool = False) "
3085 "-> typing.Callable[[type[T]], type[T]]"),
3086 // clang-format on
3087 "dialect_class"_a, nb::kw_only(), "replace"_a = false,
3088 "Produce a class decorator for registering an Operation class as part of "
3089 "a dialect");
3090 m.def(
3091 "register_op_adaptor",
3092 [](const nb::type_object &opClass, bool replace) -> nb::object {
3093 return nb::cpp_function(
3094 [opClass,
3095 replace](nb::type_object adaptorClass) -> nb::type_object {
3096 std::string operationName =
3097 nb::cast<std::string>(adaptorClass.attr("OPERATION_NAME"));
3098 PyGlobals::get().registerOpAdaptorImpl(operationName,
3099 adaptorClass, replace);
3100 // Dict-stuff the new adaptorClass by name onto the opClass.
3101 opClass.attr("Adaptor") = adaptorClass;
3102 return adaptorClass;
3103 });
3104 },
3105 // clang-format off
3106 nb::sig("def register_op_adaptor(op_class: type, *, replace: bool = False) "
3107 "-> typing.Callable[[type[T]], type[T]]"),
3108 // clang-format on
3109 "op_class"_a, nb::kw_only(), "replace"_a = false,
3110 "Produce a class decorator for registering an OpAdaptor class for an "
3111 "operation.");
3112 m.def(
3114 [](PyTypeID mlirTypeID, bool replace) -> nb::object {
3115 return nb::cpp_function([mlirTypeID, replace](
3116 nb::callable typeCaster) -> nb::object {
3117 PyGlobals::get().registerTypeCaster(mlirTypeID, typeCaster, replace);
3118 return typeCaster;
3119 });
3120 },
3121 // clang-format off
3122 nb::sig("def register_type_caster(typeid: _mlir.ir.TypeID, *, replace: bool = False) "
3123 "-> typing.Callable[[typing.Callable[[T], U]], typing.Callable[[T], U]]"),
3124 // clang-format on
3125 "typeid"_a, nb::kw_only(), "replace"_a = false,
3126 "Register a type caster for casting MLIR types to custom user types.");
3127 m.def(
3129 [](PyTypeID mlirTypeID, bool replace) -> nb::object {
3130 return nb::cpp_function(
3131 [mlirTypeID, replace](nb::callable valueCaster) -> nb::object {
3132 PyGlobals::get().registerValueCaster(mlirTypeID, valueCaster,
3133 replace);
3134 return valueCaster;
3135 });
3136 },
3137 // clang-format off
3138 nb::sig("def register_value_caster(typeid: _mlir.ir.TypeID, *, replace: bool = False) "
3139 "-> typing.Callable[[typing.Callable[[T], U]], typing.Callable[[T], U]]"),
3140 // clang-format on
3141 "typeid"_a, nb::kw_only(), "replace"_a = false,
3142 "Register a value caster for casting MLIR values to custom user values.");
3143}
3144
3145//------------------------------------------------------------------------------
3146// Location subclass bindDerived implementations.
3147//------------------------------------------------------------------------------
3148
3150 c.def_static(
3151 "get",
3152 [](DefaultingPyMlirContext context) {
3153 return PyUnknownLocation(context->getRef(),
3154 mlirLocationUnknownGet(context->get()));
3155 },
3156 "context"_a = nb::none(),
3157 "Gets a Location representing an unknown location.");
3158}
3159
3161 c.def_static(
3162 "get",
3163 [](std::string filename, int line, int col,
3164 DefaultingPyMlirContext context) {
3165 return PyFileLineColLocation(
3166 context->getRef(),
3168 toMlirStringRef(filename), line, col));
3169 },
3170 "filename"_a, "line"_a, "col"_a, "context"_a = nb::none(),
3171 "Gets a FileLineColLoc for a file, line, and column.");
3172 c.def_static(
3173 "get",
3174 [](std::string filename, int startLine, int startCol, int endLine,
3175 int endCol, DefaultingPyMlirContext context) {
3176 return PyFileLineColLocation(
3177 context->getRef(), mlirLocationFileLineColRangeGet(
3178 context->get(), toMlirStringRef(filename),
3179 startLine, startCol, endLine, endCol));
3180 },
3181 "filename"_a, "start_line"_a, "start_col"_a, "end_line"_a, "end_col"_a,
3182 "context"_a = nb::none(),
3183 "Gets a FileLineColLoc spanning a file and line/column range.");
3184 c.def_prop_ro(
3185 "filename",
3186 [](PyFileLineColLocation &self) {
3187 return mlirIdentifierStr(
3189 },
3190 "Gets the filename from a `FileLineColLoc`.");
3191 c.def_prop_ro(
3192 "start_line",
3193 [](PyFileLineColLocation &self) {
3195 },
3196 "Gets the start line number from a `FileLineColLoc`.");
3197 c.def_prop_ro(
3198 "start_col",
3199 [](PyFileLineColLocation &self) {
3201 },
3202 "Gets the start column number from a `FileLineColLoc`.");
3203 c.def_prop_ro(
3204 "end_line",
3205 [](PyFileLineColLocation &self) {
3207 },
3208 "Gets the end line number from a `FileLineColLoc`.");
3209 c.def_prop_ro(
3210 "end_col",
3211 [](PyFileLineColLocation &self) {
3213 },
3214 "Gets the end column number from a `FileLineColLoc`.");
3215}
3216
3218 c.def_static(
3219 "get",
3220 [](std::string name, std::optional<PyLocation> childLoc,
3221 DefaultingPyMlirContext context) {
3222 return PyNameLocation(
3223 context->getRef(),
3224 mlirLocationNameGet(context->get(), toMlirStringRef(name),
3225 childLoc
3226 ? childLoc->get()
3227 : mlirLocationUnknownGet(context->get())));
3228 },
3229 "name"_a, "child_loc"_a = nb::none(), "context"_a = nb::none(),
3230 "Gets a NameLoc with an optional child location.");
3231 c.def_prop_ro(
3232 "name_str",
3233 [](PyNameLocation &self) {
3235 },
3236 "Gets the name string from a `NameLoc`.");
3237 c.def_prop_ro(
3238 "child_loc",
3239 [](PyNameLocation &self) {
3240 return PyLocation(self.getContext(),
3242 .maybeDownCast();
3243 },
3244 "Gets the child location from a `NameLoc`.");
3245}
3246
3248 c.def_static(
3249 "get",
3250 [](PyLocation callee, const std::vector<PyLocation> &frames,
3251 DefaultingPyMlirContext context) {
3252 if (frames.empty())
3253 throw nb::value_error("No caller frames provided.");
3254 MlirLocation caller = frames.back().get();
3255 for (size_t index = frames.size() - 1; index-- > 0;) {
3256 caller = mlirLocationCallSiteGet(frames[index].get(), caller);
3257 }
3258 return PyCallSiteLocation(
3259 context->getRef(), mlirLocationCallSiteGet(callee.get(), caller));
3260 },
3261 "callee"_a, "frames"_a, "context"_a = nb::none(),
3262 "Gets a CallSiteLoc chaining a callee and one or more caller frames.");
3263 c.def_prop_ro(
3264 "callee",
3265 [](PyCallSiteLocation &self) {
3266 return PyLocation(self.getContext(),
3268 .maybeDownCast();
3269 },
3270 "Gets the callee location from a `CallSiteLoc`.");
3271 c.def_prop_ro(
3272 "caller",
3273 [](PyCallSiteLocation &self) {
3274 return PyLocation(self.getContext(),
3276 .maybeDownCast();
3277 },
3278 "Gets the caller location from a `CallSiteLoc`.");
3279}
3280
3282 c.def_static(
3283 "get",
3284 [](const std::vector<PyLocation> &pyLocations,
3285 std::optional<PyAttribute> metadata, DefaultingPyMlirContext context) {
3286 std::vector<MlirLocation> locations;
3287 locations.reserve(pyLocations.size());
3288 for (const PyLocation &pyLocation : pyLocations)
3289 locations.push_back(pyLocation.get());
3290 MlirLocation location = mlirLocationFusedGet(
3291 context->get(), locations.size(), locations.data(),
3292 metadata ? metadata->get() : MlirAttribute{0});
3293 // Strict: `Location.fused(...)` handles the collapse case.
3294 if (!mlirLocationIsAFused(location))
3295 throw nb::value_error(
3296 "FusedLoc.get would collapse to a non-fused location; use "
3297 "Location.fused(...) for the permissive variant.");
3298 return PyFusedLocation(context->getRef(), location);
3299 },
3300 "locations"_a, "metadata"_a = nb::none(), "context"_a = nb::none(),
3301 "Gets a FusedLoc from an array of locations and optional metadata. "
3302 "Raises if the fuse would collapse to a non-fused location; use "
3303 "`Location.fused(...)` for the permissive variant.");
3304 c.def_prop_ro(
3305 "locations",
3306 [](PyFusedLocation &self) {
3307 unsigned numLocations = mlirLocationFusedGetNumLocations(self.get());
3308 std::vector<MlirLocation> locations(numLocations);
3309 if (numLocations)
3310 mlirLocationFusedGetLocations(self.get(), locations.data());
3311 std::vector<nb::object> pyLocations;
3312 pyLocations.reserve(numLocations);
3313 for (unsigned i = 0; i < numLocations; ++i)
3314 pyLocations.push_back(
3315 PyLocation(self.getContext(), locations[i]).maybeDownCast());
3316 return pyLocations;
3317 },
3318 "Gets the list of locations from a `FusedLoc`.");
3319 c.def_prop_ro(
3320 "metadata",
3321 [](PyFusedLocation &self) -> std::optional<PyAttribute> {
3322 MlirAttribute metadata = mlirLocationFusedGetMetadata(self.get());
3323 if (mlirAttributeIsNull(metadata))
3324 return std::nullopt;
3325 return PyAttribute(self.getContext(), metadata);
3326 },
3327 "Gets the metadata attribute from a `FusedLoc`, or None if absent.");
3328}
3329
3330//------------------------------------------------------------------------------
3331// Populates the core exports of the 'ir' submodule.
3332//------------------------------------------------------------------------------
3333void populateIRCore(nb::module_ &m) {
3334 //----------------------------------------------------------------------------
3335 // Enums.
3336 //----------------------------------------------------------------------------
3337 nb::enum_<PyDiagnosticSeverity>(m, "DiagnosticSeverity")
3338 .value("ERROR", PyDiagnosticSeverity::Error)
3339 .value("WARNING", PyDiagnosticSeverity::Warning)
3340 .value("NOTE", PyDiagnosticSeverity::Note)
3341 .value("REMARK", PyDiagnosticSeverity::Remark);
3342
3343 nb::enum_<PyWalkOrder>(m, "WalkOrder")
3344 .value("PRE_ORDER", PyWalkOrder::PreOrder)
3345 .value("POST_ORDER", PyWalkOrder::PostOrder);
3346
3347 nb::enum_<PyOperationEquivalenceFlags>(m, "OperationEquivalenceFlags",
3348 nb::is_arithmetic(), nb::is_flag())
3349 .value("NONE", PyOperationEquivalenceFlags::None)
3350 .value("IGNORE_LOCATIONS", PyOperationEquivalenceFlags::IgnoreLocations)
3351 .value("IGNORE_DISCARDABLE_ATTRS",
3353 .value("IGNORE_PROPERTIES", PyOperationEquivalenceFlags::IgnoreProperties)
3354 .value("IGNORE_COMMUTATIVITY",
3356
3357 nb::enum_<PyWalkResult>(m, "WalkResult")
3358 .value("ADVANCE", PyWalkResult::Advance)
3359 .value("INTERRUPT", PyWalkResult::Interrupt)
3360 .value("SKIP", PyWalkResult::Skip);
3361
3362 //----------------------------------------------------------------------------
3363 // Mapping of Diagnostics.
3364 //----------------------------------------------------------------------------
3365 nb::class_<PyDiagnostic>(m, "Diagnostic")
3366 .def_prop_ro("severity", &PyDiagnostic::getSeverity,
3367 "Returns the severity of the diagnostic.")
3368 .def_prop_ro("location", &PyDiagnostic::getLocation,
3369 "Returns the location associated with the diagnostic.")
3370 .def_prop_ro("message", &PyDiagnostic::getMessage,
3371 "Returns the message text of the diagnostic.")
3372 .def_prop_ro("notes", &PyDiagnostic::getNotes,
3373 "Returns a tuple of attached note diagnostics.")
3374 .def(
3375 "__str__",
3376 [](PyDiagnostic &self) -> nb::str {
3377 if (!self.isValid())
3378 return nb::str("<Invalid Diagnostic>");
3379 return self.getMessage();
3380 },
3381 "Returns the diagnostic message as a string.");
3382
3383 nb::class_<PyDiagnostic::DiagnosticInfo>(m, "DiagnosticInfo")
3384 .def(
3385 "__init__",
3387 new (&self) PyDiagnostic::DiagnosticInfo(diag.getInfo());
3388 },
3389 "diag"_a, "Creates a DiagnosticInfo from a Diagnostic.")
3390 .def_ro("severity", &PyDiagnostic::DiagnosticInfo::severity,
3391 "The severity level of the diagnostic.")
3392 .def_ro("location", &PyDiagnostic::DiagnosticInfo::location,
3393 "The location associated with the diagnostic.")
3394 .def_ro("message", &PyDiagnostic::DiagnosticInfo::message,
3395 "The message text of the diagnostic.")
3396 .def_ro("notes", &PyDiagnostic::DiagnosticInfo::notes,
3397 "List of attached note diagnostics.")
3398 .def(
3399 "__str__",
3400 [](PyDiagnostic::DiagnosticInfo &self) { return self.message; },
3401 "Returns the diagnostic message as a string.");
3402
3403 nb::class_<PyDiagnosticHandler>(m, "DiagnosticHandler")
3404 .def("detach", &PyDiagnosticHandler::detach,
3405 "Detaches the diagnostic handler from the context.")
3406 .def_prop_ro("attached", &PyDiagnosticHandler::isAttached,
3407 "Returns True if the handler is attached to a context.")
3408 .def_prop_ro("had_error", &PyDiagnosticHandler::getHadError,
3409 "Returns True if an error was encountered during diagnostic "
3410 "handling.")
3411 .def("__enter__", &PyDiagnosticHandler::contextEnter,
3412 "Enters the diagnostic handler as a context manager.",
3413 nb::sig("def __enter__(self, /) -> DiagnosticHandler"))
3414 .def("__exit__", &PyDiagnosticHandler::contextExit, "exc_type"_a.none(),
3415 "exc_value"_a.none(), "traceback"_a.none(),
3416 "Exits the diagnostic handler context manager.");
3417
3418 // Expose DefaultThreadPool to python
3419 nb::class_<PyThreadPool>(m, "ThreadPool")
3420 .def(
3421 "__init__", [](PyThreadPool &self) { new (&self) PyThreadPool(); },
3422 "Creates a new thread pool with default concurrency.")
3423 .def("get_max_concurrency", &PyThreadPool::getMaxConcurrency,
3424 "Returns the maximum number of threads in the pool.")
3425 .def("_mlir_thread_pool_ptr", &PyThreadPool::_mlir_thread_pool_ptr,
3426 "Returns the raw pointer to the LLVM thread pool as a string.");
3427
3428 nb::class_<PyMlirContext>(m, "Context")
3429 .def(
3430 "__init__",
3431 [](PyMlirContext &self) {
3432 MlirContext context = mlirContextCreateWithThreading(false);
3433 new (&self) PyMlirContext(context);
3434 },
3435 R"(
3436 Creates a new MLIR context.
3437
3438 The context is the top-level container for all MLIR objects. It owns the storage
3439 for types, attributes, locations, and other core IR objects. A context can be
3440 configured to allow or disallow unregistered dialects and can have dialects
3441 loaded on-demand.)")
3442 .def_static("_get_live_count", &PyMlirContext::getLiveCount,
3443 "Gets the number of live Context objects.")
3444 .def(
3445 "_get_context_again",
3446 [](PyMlirContext &self) -> nb::typed<nb::object, PyMlirContext> {
3448 return ref.releaseObject();
3449 },
3450 "Gets another reference to the same context.")
3451 .def("_get_live_module_count", &PyMlirContext::getLiveModuleCount,
3452 "Gets the number of live modules owned by this context.")
3454 "Gets a capsule wrapping the MlirContext.")
3457 "Creates a Context from a capsule wrapping MlirContext.")
3458 .def("__enter__", &PyMlirContext::contextEnter,
3459 "Enters the context as a context manager.",
3460 nb::sig("def __enter__(self, /) -> Context"))
3461 .def("__exit__", &PyMlirContext::contextExit, "exc_type"_a.none(),
3462 "exc_value"_a.none(), "traceback"_a.none(),
3463 "Exits the context manager.")
3464 .def_prop_ro_static(
3465 "current",
3466 [](nb::object & /*class*/)
3467 -> std::optional<nb::typed<nb::object, PyMlirContext>> {
3469 if (!context)
3470 return {};
3471 return nb::cast(context);
3472 },
3473 nb::sig("def current(/) -> Context | None"),
3474 "Gets the Context bound to the current thread or returns None if no "
3475 "context is set.")
3476 .def_prop_ro(
3477 "dialects",
3478 [](PyMlirContext &self) { return PyDialects(self.getRef()); },
3479 "Gets a container for accessing dialects by name.")
3480 .def_prop_ro(
3481 "d", [](PyMlirContext &self) { return PyDialects(self.getRef()); },
3482 "Alias for `dialects`.")
3483 .def(
3484 "get_dialect_descriptor",
3485 [](PyMlirContext &self, std::string &name) {
3486 MlirDialect dialect = mlirContextGetOrLoadDialect(
3487 self.get(), {name.data(), name.size()});
3488 if (mlirDialectIsNull(dialect)) {
3489 throw nb::value_error(
3490 join("Dialect '", name, "' not found").c_str());
3491 }
3492 return PyDialectDescriptor(self.getRef(), dialect);
3493 },
3494 "dialect_name"_a,
3495 "Gets or loads a dialect by name, returning its descriptor object.")
3496 .def(
3497 "is_dialect_loaded",
3498 [](PyMlirContext &self, std::string &name) {
3499 MlirDialect dialect = mlirContextGetLoadedDialect(
3500 self.get(), {name.data(), name.size()});
3501 return !mlirDialectIsNull(dialect);
3502 },
3503 "dialect_name"_a, "Checks if a dialect is loaded in the context.")
3504 .def_prop_rw(
3505 "allow_unregistered_dialects",
3506 [](PyMlirContext &self) -> bool {
3507 return mlirContextGetAllowUnregisteredDialects(self.get());
3508 },
3509 [](PyMlirContext &self, bool value) {
3510 mlirContextSetAllowUnregisteredDialects(self.get(), value);
3511 },
3512 "Controls whether unregistered dialects are allowed in this context.")
3513 .def("attach_diagnostic_handler", &PyMlirContext::attachDiagnosticHandler,
3514 "callback"_a,
3515 "Attaches a diagnostic handler that will receive callbacks.")
3516 .def("enable_remarks", &PyMlirContext::enableRemarks, nb::kw_only(),
3517 "policy"_a = PyRemarkPolicy::All,
3518 "output_file"_a.none() = nb::none(),
3519 "format"_a = PyRemarkFormat::YAML, "all_filter"_a = "",
3520 "passed_filter"_a = "", "missed_filter"_a = "",
3521 "analysis_filter"_a = "", "failed_filter"_a = "",
3522 "callback"_a.none() = nb::none(),
3523 "print_as_emit_remarks"_a.none() = nb::none(),
3524 R"(
3525 Enables the optimization remark engine on this context.
3526
3527 Remarks are reported by passes (and by `Location.emit_remark`) and
3528 selected by the category filters, regular expressions anchored by
3529 the engine: `all_filter` applies to every kind, the other filters to
3530 one kind each; a kind without a matching filter is not reported.
3531
3532 The sink is selected by the arguments: `output_file` streams the
3533 remarks to a file in `format`, `callback` delivers them to Python,
3534 and without either they are emitted as MLIR remark diagnostics.
3535
3536 Args:
3537 policy: `RemarkPolicy.ALL` reports remarks as they are emitted;
3538 `RemarkPolicy.FINAL` postpones them until `finalize_remarks()`
3539 and reports the final set, grouping related remarks under
3540 their parents.
3541 output_file: Path of the remark file, written on
3542 `finalize_remarks()`.
3543 format: The serialization format of `output_file`.
3544 all_filter: Category regex applied to every remark kind.
3545 passed_filter: Category regex for passed remarks.
3546 missed_filter: Category regex for missed remarks.
3547 analysis_filter: Category regex for analysis remarks.
3548 failed_filter: Category regex for failed remarks.
3549 callback: A callable receiving one `Remark` per reported remark;
3550 the remark is only valid during the call.
3551 print_as_emit_remarks: Also emit every remark as an MLIR remark
3552 diagnostic; defaults to True only without an output file or
3553 callback.
3554
3555 Raises:
3556 ValueError: When both an output file and a callback are given,
3557 when remarks are already enabled, or when the output file
3558 cannot be written.)")
3559 .def("finalize_remarks", &PyMlirContext::finalizeRemarks,
3560 R"(
3561 Finalizes and removes the remark engine of this context.
3562
3563 Postponed remarks (policy "final") are reported, the output file is
3564 written and the callback is released. Does nothing when no engine
3565 is enabled; `enable_remarks` may be called again afterwards.)")
3566 .def_prop_ro(
3567 "remarks_enabled", &PyMlirContext::getRemarksEnabled,
3568 "Returns True if a remark engine is enabled on this context.")
3569 .def(
3570 "enable_multithreading",
3571 [](PyMlirContext &self, bool enable) {
3572 mlirContextEnableMultithreading(self.get(), enable);
3573 },
3574 "enable"_a,
3575 R"(
3576 Enables or disables multi-threading support in the context.
3577
3578 Args:
3579 enable: Whether to enable (True) or disable (False) multi-threading.
3580 )")
3581 .def(
3582 "set_thread_pool",
3583 [](PyMlirContext &self, PyThreadPool &pool) {
3584 // we should disable multi-threading first before setting
3585 // new thread pool otherwise the assert in
3586 // MLIRContext::setThreadPool will be raised.
3587 mlirContextEnableMultithreading(self.get(), false);
3588 mlirContextSetThreadPool(self.get(), pool.get());
3589 },
3590 R"(
3591 Sets a custom thread pool for the context to use.
3592
3593 Args:
3594 pool: A ThreadPool object to use for parallel operations.
3595
3596 Note:
3597 Multi-threading is automatically disabled before setting the thread pool.)")
3598 .def(
3599 "get_num_threads",
3600 [](PyMlirContext &self) {
3601 return mlirContextGetNumThreads(self.get());
3602 },
3603 "Gets the number of threads in the context's thread pool.")
3604 .def(
3605 "_mlir_thread_pool_ptr",
3606 [](PyMlirContext &self) {
3607 MlirLlvmThreadPool pool = mlirContextGetThreadPool(self.get());
3608 std::stringstream ss;
3609 ss << pool.ptr;
3610 return ss.str();
3611 },
3612 "Gets the raw pointer to the LLVM thread pool as a string.")
3613 .def(
3614 "is_registered_operation",
3615 [](PyMlirContext &self, std::string &name) {
3617 self.get(), MlirStringRef{name.data(), name.size()});
3618 },
3619 "operation_name"_a,
3620 R"(
3621 Checks whether an operation with the given name is registered.
3622
3623 Args:
3624 operation_name: The fully qualified name of the operation (e.g., `arith.addf`).
3625
3626 Returns:
3627 True if the operation is registered, False otherwise.)")
3628 .def(
3629 "append_dialect_registry",
3630 [](PyMlirContext &self, PyDialectRegistry &registry) {
3631 mlirContextAppendDialectRegistry(self.get(), registry);
3632 },
3633 "registry"_a,
3634 R"(
3635 Appends the contents of a dialect registry to the context.
3636
3637 Args:
3638 registry: A DialectRegistry containing dialects to append.)")
3639 .def_prop_rw("emit_error_diagnostics",
3642 R"(
3643 Controls whether error diagnostics are emitted to diagnostic handlers.
3644
3645 By default, error diagnostics are captured and reported through MLIRError exceptions.)")
3646 .def(
3647 "load_all_available_dialects",
3648 [](PyMlirContext &self) {
3650 },
3651 R"(
3652 Loads all dialects available in the registry into the context.
3653
3654 This eagerly loads all dialects that have been registered, making them
3655 immediately available for use.)")
3656 .def(
3657 "begin_transient_scope",
3658 [](PyMlirContext &self) {
3659 if (mlirContextIsInTransientScope(self.get()))
3660 throw nb::value_error("Context is already in a transient scope");
3662 },
3663 R"(
3664 Begins a transient scope on the context, freezing the base layer.
3665
3666 All subsequently allocated types, attributes, and unregistered operations
3667 are treated as transient and will be deallocated with end_transient_scope().
3668 Raises a ValueError if the context is already in a transient scope.)")
3669 .def(
3670 "end_transient_scope",
3671 [](PyMlirContext &self) { mlirContextEndTransientScope(self.get()); },
3672 R"(
3673 Ends the transient scope and resets the context to the base state.
3674
3675 Prunes all transient types, attributes, affine expressions, distinct
3676 attributes, and unregistered operations added during the transient scope.
3677
3678 Note: Any Python objects referencing transient IR entities become invalid
3679 after this call and must not be accessed.)")
3680 .def_prop_ro(
3681 "is_in_transient_scope",
3682 [](PyMlirContext &self) -> bool {
3683 return mlirContextIsInTransientScope(self.get());
3684 },
3685 "Returns whether the context is currently in a transient scope.");
3686
3687 //----------------------------------------------------------------------------
3688 // Mapping of PyDialectDescriptor
3689 //----------------------------------------------------------------------------
3690 nb::class_<PyDialectDescriptor>(m, "DialectDescriptor")
3691 .def_prop_ro(
3692 "namespace",
3693 [](PyDialectDescriptor &self) {
3694 MlirStringRef ns = mlirDialectGetNamespace(self.get());
3695 return nb::str(ns.data, ns.length);
3696 },
3697 "Returns the namespace of the dialect.")
3698 .def(
3699 "__repr__",
3700 [](PyDialectDescriptor &self) {
3701 MlirStringRef ns = mlirDialectGetNamespace(self.get());
3702 std::string repr("<DialectDescriptor ");
3703 repr.append(ns.data, ns.length);
3704 repr.append(">");
3705 return repr;
3706 },
3707 nb::sig("def __repr__(self) -> str"),
3708 "Returns a string representation of the dialect descriptor.");
3709
3710 //----------------------------------------------------------------------------
3711 // Mapping of PyDialects
3712 //----------------------------------------------------------------------------
3713 nb::class_<PyDialects>(m, "Dialects")
3714 .def(
3715 "__getitem__",
3716 [](PyDialects &self, std::string keyName) {
3717 MlirDialect dialect =
3718 self.getDialectForKey(keyName, /*attrError=*/false);
3719 nb::object descriptor =
3720 nb::cast(PyDialectDescriptor{self.getContext(), dialect});
3721 return createCustomDialectWrapper(keyName, std::move(descriptor));
3722 },
3723 "Gets a dialect by name using subscript notation.")
3724 .def(
3725 "__getattr__",
3726 [](PyDialects &self, std::string attrName) {
3727 MlirDialect dialect =
3728 self.getDialectForKey(attrName, /*attrError=*/true);
3729 nb::object descriptor =
3730 nb::cast(PyDialectDescriptor{self.getContext(), dialect});
3731 return createCustomDialectWrapper(attrName, std::move(descriptor));
3732 },
3733 "Gets a dialect by name using attribute notation.");
3734
3735 //----------------------------------------------------------------------------
3736 // Mapping of PyDialect
3737 //----------------------------------------------------------------------------
3738 nb::class_<PyDialect>(m, "Dialect")
3739 .def(nb::init<nb::object>(), "descriptor"_a,
3740 "Creates a Dialect from a DialectDescriptor.")
3741 .def_prop_ro(
3742 "descriptor", [](PyDialect &self) { return self.getDescriptor(); },
3743 "Returns the DialectDescriptor for this dialect.")
3744 .def(
3745 "__repr__",
3746 [](const nb::object &self) {
3747 auto clazz = self.attr("__class__");
3748 return nb::str("<Dialect ") +
3749 self.attr("descriptor").attr("namespace") +
3750 nb::str(" (class ") + clazz.attr("__module__") +
3751 nb::str(".") + clazz.attr("__name__") + nb::str(")>");
3752 },
3753 nb::sig("def __repr__(self) -> str"),
3754 "Returns a string representation of the dialect.");
3755
3756 //----------------------------------------------------------------------------
3757 // Mapping of PyDialectRegistry
3758 //----------------------------------------------------------------------------
3759 nb::class_<PyDialectRegistry>(m, "DialectRegistry")
3761 "Gets a capsule wrapping the MlirDialectRegistry.")
3764 "Creates a DialectRegistry from a capsule wrapping "
3765 "`MlirDialectRegistry`.")
3766 .def(nb::init<>(), "Creates a new empty dialect registry.");
3767
3768 //----------------------------------------------------------------------------
3769 // Mapping of Location
3770 //----------------------------------------------------------------------------
3771 nb::class_<PyLocation>(m, "Location")
3773 "Gets a capsule wrapping the MlirLocation.")
3775 "Creates a Location from a capsule wrapping MlirLocation.")
3776 .def("__enter__", &PyLocation::contextEnter,
3777 "Enters the location as a context manager.",
3778 nb::sig("def __enter__(self, /) -> Location"))
3779 .def("__exit__", &PyLocation::contextExit, "exc_type"_a.none(),
3780 "exc_value"_a.none(), "traceback"_a.none(),
3781 "Exits the location context manager.")
3782 .def(
3783 "__eq__",
3784 [](PyLocation &self, PyLocation &other) -> bool {
3785 return mlirLocationEqual(self, other);
3786 },
3787 "Compares two locations for equality.")
3788 .def(
3789 "__eq__", [](PyLocation &self, nb::object other) { return false; },
3790 "Compares location with non-location object (always returns False).")
3791 .def_prop_ro_static(
3792 "current",
3793 [](nb::object & /*class*/) -> std::optional<PyLocation *> {
3795 if (!loc)
3796 return std::nullopt;
3797 return loc;
3798 },
3799 // clang-format off
3800 nb::sig("def current(/) -> Location | None"),
3801 // clang-format on
3802 "Gets the Location bound to the current thread or raises ValueError.")
3803 .def_static(
3804 "from_attr",
3805 [](PyAttribute &attribute, DefaultingPyMlirContext context) {
3806 return PyLocation(context->getRef(),
3807 mlirLocationFromAttribute(attribute))
3808 .maybeDownCast();
3809 },
3810 "attribute"_a, "context"_a = nb::none(),
3811 "Gets a Location from a `LocationAttr`.")
3812 // Factory shims kept for backward compatibility; return the concrete
3813 // subclass. New code should use the subclass `.get()` directly.
3814 .def_static(
3815 "unknown",
3816 [](DefaultingPyMlirContext context) {
3817 return PyUnknownLocation(context->getRef(),
3818 mlirLocationUnknownGet(context->get()));
3819 },
3820 "context"_a = nb::none(), "Alias for `UnknownLoc.get()`.")
3821 .def_static(
3822 "file",
3823 [](std::string filename, int line, int col,
3824 DefaultingPyMlirContext context) {
3825 return PyFileLineColLocation(
3826 context->getRef(),
3828 context->get(), toMlirStringRef(filename), line, col));
3829 },
3830 "filename"_a, "line"_a, "col"_a, "context"_a = nb::none(),
3831 "Alias for `FileLineColLoc.get()`.")
3832 .def_static(
3833 "file",
3834 [](std::string filename, int startLine, int startCol, int endLine,
3835 int endCol, DefaultingPyMlirContext context) {
3836 return PyFileLineColLocation(
3837 context->getRef(),
3839 context->get(), toMlirStringRef(filename), startLine,
3840 startCol, endLine, endCol));
3841 },
3842 "filename"_a, "start_line"_a, "start_col"_a, "end_line"_a,
3843 "end_col"_a, "context"_a = nb::none(),
3844 "Alias for `FileLineColLoc.get()` over a range.")
3845 .def_static(
3846 "name",
3847 [](std::string name, std::optional<PyLocation> childLoc,
3848 DefaultingPyMlirContext context) {
3849 return PyNameLocation(
3850 context->getRef(),
3852 context->get(), toMlirStringRef(name),
3853 childLoc ? childLoc->get()
3854 : mlirLocationUnknownGet(context->get())));
3855 },
3856 "name"_a, "childLoc"_a = nb::none(), "context"_a = nb::none(),
3857 "Alias for `NameLoc.get()`.")
3858 .def_static(
3859 "callsite",
3860 [](PyLocation callee, const std::vector<PyLocation> &frames,
3861 DefaultingPyMlirContext context) {
3862 if (frames.empty())
3863 throw nb::value_error("No caller frames provided.");
3864 MlirLocation caller = frames.back().get();
3865 for (size_t index = frames.size() - 1; index-- > 0;)
3866 caller = mlirLocationCallSiteGet(frames[index].get(), caller);
3867 return PyCallSiteLocation(
3868 context->getRef(),
3869 mlirLocationCallSiteGet(callee.get(), caller));
3870 },
3871 "callee"_a, "frames"_a, "context"_a = nb::none(),
3872 "Alias for `CallSiteLoc.get()`.")
3873 .def_static(
3874 "fused",
3875 [](const std::vector<PyLocation> &pyLocations,
3876 std::optional<PyAttribute> metadata,
3877 DefaultingPyMlirContext context) {
3878 std::vector<MlirLocation> locations;
3879 locations.reserve(pyLocations.size());
3880 for (const PyLocation &pyLocation : pyLocations)
3881 locations.push_back(pyLocation.get());
3882 MlirLocation location = mlirLocationFusedGet(
3883 context->get(), locations.size(), locations.data(),
3884 metadata ? metadata->get() : MlirAttribute{0});
3885 return PyLocation(context->getRef(), location).maybeDownCast();
3886 },
3887 "locations"_a, "metadata"_a = nb::none(), "context"_a = nb::none(),
3888 "Alias for `FusedLoc.get()` (may collapse to a non-fused location).")
3889 .def_prop_ro(
3890 "context",
3891 [](PyLocation &self) -> nb::typed<nb::object, PyMlirContext> {
3892 return self.getContext().getObject();
3893 },
3894 "Context that owns the `Location`.")
3895 .def_prop_ro(
3896 "attr",
3897 [](PyLocation &self) {
3898 return PyAttribute(self.getContext(),
3900 },
3901 "Get the underlying `LocationAttr`.")
3902 .def_prop_ro(
3903 "typeid",
3904 [](PyLocation &self) {
3905 MlirTypeID mlirTypeID =
3907 assert(!mlirTypeIDIsNull(mlirTypeID) &&
3908 "mlirTypeID was expected to be non-null.");
3909 return PyTypeID(mlirTypeID);
3910 },
3911 "Gets the `TypeID` of the underlying LocationAttr.")
3912 .def(
3913 "emit_error",
3914 [](PyLocation &self, std::string message) {
3915 mlirEmitError(self, message.c_str());
3916 },
3917 "message"_a,
3918 R"(
3919 Emits an error diagnostic at this location.
3920
3921 Args:
3922 message: The error message to emit.)")
3923 .def(
3924 "emit_warning",
3925 [](PyLocation &self, std::string message) {
3926 mlirEmitWarning(self, message.c_str());
3927 },
3928 "message"_a,
3929 R"(
3930 Emits a warning diagnostic at this location.
3931
3932 Args:
3933 message: The warning message to emit.)")
3934 .def(
3935 "emit_remark",
3936 [](PyLocation &self, PyRemarkKind kind, const std::string &remarkName,
3937 const std::string &category, const std::string &subCategory,
3938 const std::string &functionName, const std::string &message,
3939 const std::vector<std::pair<std::string, std::string>> &args)
3940 -> bool {
3941 auto remarkKind = static_cast<MlirRemarkKind>(kind);
3942 std::vector<MlirStringRef> keys, values;
3943 keys.reserve(args.size());
3944 values.reserve(args.size());
3945 for (const auto &[key, value] : args) {
3946 keys.push_back(toMlirStringRef(key));
3947 values.push_back(toMlirStringRef(value));
3948 }
3950 self, remarkKind, toMlirStringRef(remarkName),
3951 toMlirStringRef(category), toMlirStringRef(subCategory),
3952 toMlirStringRef(functionName), toMlirStringRef(message),
3953 static_cast<intptr_t>(keys.size()), keys.data(), values.data());
3954 },
3955 "kind"_a, "remark_name"_a, nb::kw_only(), "category"_a = "",
3956 "sub_category"_a = "", "function_name"_a = "", "message"_a = "",
3957 "args"_a = std::vector<std::pair<std::string, std::string>>(),
3958 R"(
3959 Emits an optimization remark at this location through the remark
3960 engine of the context (see `Context.enable_remarks`).
3961
3962 Args:
3963 kind: The `RemarkKind` of the remark.
3964 remark_name: The name identifying the remark.
3965 category: The category the filters are matched against.
3966 sub_category: An optional sub-category.
3967 function_name: The function the remark refers to.
3968 message: Free text attached to the remark.
3969 args: Key/value pairs attached to the remark.
3970
3971 Returns:
3972 True if the remark was reported; False when no remark engine is
3973 enabled or the category is filtered out.)")
3974 .def(
3975 "__str__",
3976 [](PyLocation &self) {
3977 PyPrintAccumulator printAccum;
3978 mlirLocationPrint(self, printAccum.getCallback(),
3979 printAccum.getUserData());
3980 return printAccum.join();
3981 },
3982 "Returns the assembly form of the Location.")
3983 .def(
3984 "__repr__",
3985 [](PyLocation &self) {
3986 PyPrintAccumulator printAccum;
3987 mlirLocationPrint(self, printAccum.getCallback(),
3988 printAccum.getUserData());
3989 return printAccum.join();
3990 },
3991 "Returns the assembly representation of the location.");
3992
3998
3999 //----------------------------------------------------------------------------
4000 // Mapping of Module
4001 //----------------------------------------------------------------------------
4002 nb::class_<PyModule>(m, "Module", nb::is_weak_referenceable())
4004 "Gets a capsule wrapping the MlirModule.")
4006 R"(
4007 Creates a Module from a `MlirModule` wrapped by a capsule (i.e. `module._CAPIPtr`).
4008
4009 This returns a new object **BUT** `_clear_mlir_module(module)` must be called to
4010 prevent double-frees (of the underlying `mlir::Module`).)")
4011 .def("_clear_mlir_module", &PyModule::clearMlirModule,
4012 R"(
4013 Clears the internal MLIR module reference.
4014
4015 This is used internally to prevent double-free when ownership is transferred
4016 via the C API capsule mechanism. Not intended for normal use.)")
4017 .def_static(
4018 "parse",
4019 [](const std::string &moduleAsm, DefaultingPyMlirContext context)
4020 -> nb::typed<nb::object, PyModule> {
4021 PyMlirContext::ErrorCapture errors(context->getRef());
4022 MlirModule module = mlirModuleCreateParse(
4023 context->get(), toMlirStringRef(moduleAsm));
4024 if (mlirModuleIsNull(module))
4025 throw MLIRError("Unable to parse module assembly", errors.take());
4026 return PyModule::forModule(module).releaseObject();
4027 },
4028 "asm"_a, "context"_a = nb::none(), kModuleParseDocstring)
4029 .def_static(
4030 "parse",
4031 [](nb::bytes moduleAsm, DefaultingPyMlirContext context)
4032 -> nb::typed<nb::object, PyModule> {
4033 PyMlirContext::ErrorCapture errors(context->getRef());
4034 MlirModule module = mlirModuleCreateParse(
4035 context->get(), toMlirStringRef(moduleAsm));
4036 if (mlirModuleIsNull(module))
4037 throw MLIRError("Unable to parse module assembly", errors.take());
4038 return PyModule::forModule(module).releaseObject();
4039 },
4040 "asm"_a, "context"_a = nb::none(), kModuleParseDocstring)
4041 .def_static(
4042 "parseFile",
4043 [](const std::string &path, DefaultingPyMlirContext context)
4044 -> nb::typed<nb::object, PyModule> {
4045 PyMlirContext::ErrorCapture errors(context->getRef());
4046 MlirModule module = mlirModuleCreateParseFromFile(
4047 context->get(), toMlirStringRef(path));
4048 if (mlirModuleIsNull(module))
4049 throw MLIRError("Unable to parse module assembly", errors.take());
4050 return PyModule::forModule(module).releaseObject();
4051 },
4052 "path"_a, "context"_a = nb::none(), kModuleParseDocstring)
4053 .def_static(
4054 "create",
4055 [](const std::optional<PyLocation> &loc)
4056 -> nb::typed<nb::object, PyModule> {
4057 PyLocation pyLoc = maybeGetTracebackLocation(loc);
4058 MlirModule module = mlirModuleCreateEmpty(pyLoc.get());
4059 return PyModule::forModule(module).releaseObject();
4060 },
4061 "loc"_a = nb::none(), "Creates an empty module.")
4062 .def_prop_ro(
4063 "context",
4064 [](PyModule &self) -> nb::typed<nb::object, PyMlirContext> {
4065 return self.getContext().getObject();
4066 },
4067 "Context that created the `Module`.")
4068 .def_prop_ro(
4069 "operation",
4070 [](PyModule &self) -> nb::typed<nb::object, PyOperation> {
4071 return PyOperation::forOperation(self.getContext(),
4072 mlirModuleGetOperation(self.get()),
4073 self.getRef().releaseObject())
4074 .releaseObject();
4075 },
4076 "Accesses the module as an operation.")
4077 .def_prop_ro(
4078 "body",
4079 [](PyModule &self) {
4081 self.getContext(), mlirModuleGetOperation(self.get()),
4082 self.getRef().releaseObject());
4083 PyBlock returnBlock(moduleOp, mlirModuleGetBody(self.get()));
4084 return returnBlock;
4085 },
4086 "Return the block for this module.")
4087 .def(
4088 "dump",
4089 [](PyModule &self) {
4091 },
4093 .def(
4094 "__str__",
4095 [](const nb::object &self) {
4096 // Defer to the operation's __str__.
4097 return self.attr("operation").attr("__str__")();
4098 },
4099 nb::sig("def __str__(self) -> str"),
4100 R"(
4101 Gets the assembly form of the operation with default options.
4102
4103 If more advanced control over the assembly formatting or I/O options is needed,
4104 use the dedicated print or get_asm method, which supports keyword arguments to
4105 customize behavior.
4106 )")
4107 .def(
4108 "__eq__",
4109 [](PyModule &self, PyModule &other) {
4110 return mlirModuleEqual(self.get(), other.get());
4111 },
4112 "other"_a, "Compares two modules for equality.")
4113 .def(
4114 "__hash__",
4115 [](PyModule &self) { return mlirModuleHashValue(self.get()); },
4116 "Returns the hash value of the module.");
4117
4118 //----------------------------------------------------------------------------
4119 // Mapping of Operation.
4120 //----------------------------------------------------------------------------
4121 nb::class_<PyOperationBase>(m, "_OperationBase")
4122 .def_prop_ro(
4124 [](PyOperationBase &self) {
4125 return self.getOperation().getCapsule();
4126 },
4127 "Gets a capsule wrapping the `MlirOperation`.")
4128 .def(
4129 "__eq__",
4130 [](PyOperationBase &self, PyOperationBase &other) {
4131 return mlirOperationEqual(self.getOperation().get(),
4132 other.getOperation().get());
4133 },
4134 "Compares two operations for equality.")
4135 .def(
4136 "__eq__",
4137 [](PyOperationBase &self, nb::object other) { return false; },
4138 "Compares operation with non-operation object (always returns "
4139 "False).")
4140 .def(
4141 "__hash__",
4142 [](PyOperationBase &self) {
4143 return mlirOperationHashValue(self.getOperation().get());
4144 },
4145 "Returns the hash value of the operation.")
4146 .def(
4147 "is_structurally_equivalent",
4148 [](PyOperationBase &self, PyOperationBase &other,
4150 self.getOperation().checkValid();
4151 other.getOperation().checkValid();
4153 self.getOperation().get(), other.getOperation().get(),
4154 static_cast<uint32_t>(flags));
4155 },
4156 "other"_a, "flags"_a = PyOperationEquivalenceFlags::None,
4157 R"("Checks whether two operations are structurally equivalent. The predicate recursively compares regions.")")
4158 .def(
4159 "structural_hash",
4161 self.getOperation().checkValid();
4163 self.getOperation().get(), static_cast<uint32_t>(flags));
4164 },
4166 R"(Computes a structural hash for the operation. The hash does not recurse into regions, unlike the predicate.")")
4167 .def_prop_ro(
4168 "attributes",
4169 [](PyOperationBase &self) {
4170 return PyOpAttributeMap(self.getOperation().getRef());
4171 },
4172 "Returns a dictionary-like map of operation attributes.")
4173 .def_prop_ro(
4174 "context",
4175 [](PyOperationBase &self) -> nb::typed<nb::object, PyMlirContext> {
4176 PyOperation &concreteOperation = self.getOperation();
4177 concreteOperation.checkValid();
4178 return concreteOperation.getContext().getObject();
4179 },
4180 "Context that owns the operation.")
4181 .def_prop_ro(
4182 "name",
4183 [](PyOperationBase &self) {
4184 auto &concreteOperation = self.getOperation();
4185 concreteOperation.checkValid();
4186 MlirOperation operation = concreteOperation.get();
4187 return mlirIdentifierStr(mlirOperationGetName(operation));
4188 },
4189 "Returns the fully qualified name of the operation.")
4190 .def_prop_ro(
4191 "operands",
4192 [](PyOperationBase &self) {
4193 return PyOpOperandList(self.getOperation().getRef());
4194 },
4195 "Returns the list of operation operands.")
4196 .def_prop_ro(
4197 "op_operands",
4198 [](PyOperationBase &self) {
4199 return PyOpOperands(self.getOperation().getRef());
4200 },
4201 "Returns the list of op operands.")
4202 .def_prop_ro(
4203 "regions",
4204 [](PyOperationBase &self) {
4205 return PyRegionList(self.getOperation().getRef());
4206 },
4207 "Returns the list of operation regions.")
4208 .def_prop_ro(
4209 "results",
4210 [](PyOperationBase &self) {
4211 return PyOpResultList(self.getOperation().getRef());
4212 },
4213 "Returns the list of Operation results.")
4214 .def_prop_ro(
4215 "result",
4216 [](PyOperationBase &self) -> nb::typed<nb::object, PyOpResult> {
4217 auto &operation = self.getOperation();
4218 return PyOpResult(operation.getRef(), getUniqueResult(operation))
4219 .maybeDownCast();
4220 },
4221 "Shortcut to get an op result if it has only one (throws an error "
4222 "otherwise).")
4223 .def_prop_rw(
4224 "location",
4225 [](PyOperationBase &self) {
4226 PyOperation &operation = self.getOperation();
4227 return PyLocation(operation.getContext(),
4228 mlirOperationGetLocation(operation.get()))
4229 .maybeDownCast();
4230 },
4231 [](PyOperationBase &self, const PyLocation &location) {
4232 PyOperation &operation = self.getOperation();
4233 mlirOperationSetLocation(operation.get(), location.get());
4234 },
4235 nb::for_getter("Returns the source location the operation was "
4236 "defined or derived from."),
4237 nb::for_setter("Sets the source location the operation was defined "
4238 "or derived from."))
4239 .def_prop_ro(
4240 "parent",
4241 [](PyOperationBase &self)
4242 -> std::optional<nb::typed<nb::object, PyOperation>> {
4243 auto parent = self.getOperation().getParentOperation();
4244 if (parent)
4245 return parent->getObject();
4246 return {};
4247 },
4248 "Returns the parent operation, or `None` if at top level.")
4249 .def(
4250 "__str__",
4251 [](PyOperationBase &self) {
4252 return self.getAsm(/*binary=*/false,
4253 /*largeElementsLimit=*/std::nullopt,
4254 /*largeResourceLimit=*/std::nullopt,
4255 /*enableDebugInfo=*/false,
4256 /*prettyDebugInfo=*/false,
4257 /*printGenericOpForm=*/false,
4258 /*useLocalScope=*/false,
4259 /*useNameLocAsPrefix=*/false,
4260 /*assumeVerified=*/false,
4261 /*skipRegions=*/false);
4262 },
4263 nb::sig("def __str__(self) -> str"),
4264 "Returns the assembly form of the operation.")
4265 .def("print",
4266 nb::overload_cast<PyAsmState &, nb::object, bool>(
4268 "state"_a, "file"_a = nb::none(), "binary"_a = false,
4269 R"(
4270 Prints the assembly form of the operation to a file like object.
4271
4272 Args:
4273 state: `AsmState` capturing the operation numbering and flags.
4274 file: Optional file like object to write to. Defaults to sys.stdout.
4275 binary: Whether to write `bytes` (True) or `str` (False). Defaults to False.)")
4276 .def("print",
4277 nb::overload_cast<std::optional<int64_t>, std::optional<int64_t>,
4278 bool, bool, bool, bool, bool, bool, nb::object,
4279 bool, bool>(&PyOperationBase::print),
4280 // Careful: Lots of arguments must match up with print method.
4281 "large_elements_limit"_a = nb::none(),
4282 "large_resource_limit"_a = nb::none(), "enable_debug_info"_a = false,
4283 "pretty_debug_info"_a = false, "print_generic_op_form"_a = false,
4284 "use_local_scope"_a = false, "use_name_loc_as_prefix"_a = false,
4285 "assume_verified"_a = false, "file"_a = nb::none(),
4286 "binary"_a = false, "skip_regions"_a = false,
4287 R"(
4288 Prints the assembly form of the operation to a file like object.
4289
4290 Args:
4291 large_elements_limit: Whether to elide elements attributes above this
4292 number of elements. Defaults to None (no limit).
4293 large_resource_limit: Whether to elide resource attributes above this
4294 number of characters. Defaults to None (no limit). If large_elements_limit
4295 is set and this is None, the behavior will be to use large_elements_limit
4296 as large_resource_limit.
4297 enable_debug_info: Whether to print debug/location information. Defaults
4298 to False.
4299 pretty_debug_info: Whether to format debug information for easier reading
4300 by a human (warning: the result is unparseable). Defaults to False.
4301 print_generic_op_form: Whether to print the generic assembly forms of all
4302 ops. Defaults to False.
4303 use_local_scope: Whether to print in a way that is more optimized for
4304 multi-threaded access but may not be consistent with how the overall
4305 module prints.
4306 use_name_loc_as_prefix: Whether to use location attributes (NameLoc) as
4307 prefixes for the SSA identifiers. Defaults to False.
4308 assume_verified: By default, if not printing generic form, the verifier
4309 will be run and if it fails, generic form will be printed with a comment
4310 about failed verification. While a reasonable default for interactive use,
4311 for systematic use, it is often better for the caller to verify explicitly
4312 and report failures in a more robust fashion. Set this to True if doing this
4313 in order to avoid running a redundant verification. If the IR is actually
4314 invalid, behavior is undefined.
4315 file: The file like object to write to. Defaults to sys.stdout.
4316 binary: Whether to write bytes (True) or str (False). Defaults to False.
4317 skip_regions: Whether to skip printing regions. Defaults to False.)")
4318 .def("write_bytecode", &PyOperationBase::writeBytecode, "file"_a,
4319 "desired_version"_a = nb::none(),
4320 R"(
4321 Write the bytecode form of the operation to a file like object.
4322
4323 Args:
4324 file: The file like object to write to.
4325 desired_version: Optional version of bytecode to emit.
4326 Returns:
4327 The bytecode writer status.)")
4328 .def("get_asm", &PyOperationBase::getAsm,
4329 // Careful: Lots of arguments must match up with get_asm method.
4330 "binary"_a = false, "large_elements_limit"_a = nb::none(),
4331 "large_resource_limit"_a = nb::none(), "enable_debug_info"_a = false,
4332 "pretty_debug_info"_a = false, "print_generic_op_form"_a = false,
4333 "use_local_scope"_a = false, "use_name_loc_as_prefix"_a = false,
4334 "assume_verified"_a = false, "skip_regions"_a = false,
4335 R"(
4336 Gets the assembly form of the operation with all options available.
4337
4338 Args:
4339 binary: Whether to return a bytes (True) or str (False) object. Defaults to
4340 False.
4341 ... others ...: See the print() method for common keyword arguments for
4342 configuring the printout.
4343 Returns:
4344 Either a bytes or str object, depending on the setting of the `binary`
4345 argument.)")
4346 .def("verify", &PyOperationBase::verify,
4347 "Verify the operation. Raises MLIRError if verification fails, and "
4348 "returns true otherwise.")
4349 .def("move_after", &PyOperationBase::moveAfter, "other"_a,
4350 "Puts self immediately after the other operation in its parent "
4351 "block.")
4352 .def("move_before", &PyOperationBase::moveBefore, "other"_a,
4353 "Puts self immediately before the other operation in its parent "
4354 "block.")
4355 .def("is_before_in_block", &PyOperationBase::isBeforeInBlock, "other"_a,
4356 R"(
4357 Checks if this operation is before another in the same block.
4358
4359 Args:
4360 other: Another operation in the same parent block.
4361
4362 Returns:
4363 True if this operation is before `other` in the operation list of the parent block.)")
4364 .def("is_ancestor", &PyOperationBase::isAncestor, "other"_a,
4365 R"(
4366 Checks if this operation is an ancestor of another operation.
4367
4368 Args:
4369 other: Another operation.
4370
4371 Returns:
4372 True if this operation contains `other` or is the same operation.)")
4373 .def("is_proper_ancestor", &PyOperationBase::isProperAncestor, "other"_a,
4374 R"(
4375 Checks if this operation is a proper ancestor of another operation.
4376
4377 Args:
4378 other: Another operation.
4379
4380 Returns:
4381 True if this operation contains `other` and is not the same operation.)")
4382 .def(
4383 "clone",
4384 [](PyOperationBase &self,
4385 const nb::object &ip) -> nb::typed<nb::object, PyOperation> {
4386 return self.getOperation().clone(ip);
4387 },
4388 "ip"_a = nb::none(),
4389 R"(
4390 Creates a deep copy of the operation.
4391
4392 Args:
4393 ip: Optional insertion point where the cloned operation should be inserted.
4394 If None, the current insertion point is used. If False, the operation
4395 remains detached.
4396
4397 Returns:
4398 A new Operation that is a clone of this operation.)")
4399 .def(
4400 "detach_from_parent",
4401 [](PyOperationBase &self) -> nb::typed<nb::object, PyOpView> {
4402 PyOperation &operation = self.getOperation();
4403 operation.checkValid();
4404 if (!operation.isAttached())
4405 throw nb::value_error("Detached operation has no parent.");
4406
4407 operation.detachFromParent();
4408 return operation.createOpView();
4409 },
4410 "Detaches the operation from its parent block.")
4411 .def_prop_ro(
4412 "attached",
4413 [](PyOperationBase &self) {
4414 PyOperation &operation = self.getOperation();
4415 operation.checkValid();
4416 return operation.isAttached();
4417 },
4418 "Reports if the operation is attached to its parent block.")
4419 .def(
4420 "erase", [](PyOperationBase &self) { self.getOperation().erase(); },
4421 R"(
4422 Erases the operation and frees its memory.
4423
4424 Note:
4425 After erasing, any Python references to the operation become invalid.)")
4426 .def(
4427 "walk",
4428 [](PyOperationBase &self,
4429 std::function<PyWalkResult(MlirOperation)> callback,
4430 PyWalkOrder walkOrder, std::optional<nb::object> opClass) {
4431 if (!opClass)
4432 return self.walk(callback, walkOrder);
4433 self.walk(
4434 [&](MlirOperation mlirOp) -> PyWalkResult {
4435 nb::object opview =
4437 self.getOperation().getContext(), mlirOp)
4438 ->createOpView();
4439 if (nb::isinstance(opview, *opClass))
4440 return callback(mlirOp);
4441 return PyWalkResult::Advance;
4442 },
4443 walkOrder);
4444 },
4445 "callback"_a, "walk_order"_a = PyWalkOrder::PostOrder,
4446 "op_class"_a = nb::none(),
4447 // clang-format off
4448 nb::sig("def walk(self, callback: Callable[[Operation], WalkResult], walk_order: WalkOrder = ..., op_class: type[OpView] | None = None) -> None"),
4449 // clang-format on
4450 R"(
4451 Walks the operation tree with a callback function.
4452
4453 If op_class is provided, the callback is only invoked on operations
4454 of that type; all other operations are skipped silently.
4455
4456 Args:
4457 callback: A callable that takes an Operation and returns a WalkResult.
4458 walk_order: The order of traversal (PRE_ORDER or POST_ORDER).
4459 op_class: If provided, only operations of this type are passed to the callback.)")
4460 .def(
4461 "has_trait",
4462 [](PyOperationBase &self, nb::type_object &traitCls) {
4463 PyTypeID traitTypeID =
4464 nb::cast<PyTypeID>(traitCls.attr(PyDynamicOpTrait::typeIDAttr));
4465 MlirIdentifier opName =
4466 mlirOperationGetName(self.getOperation().get());
4468 mlirIdentifierStr(opName), traitTypeID.get(),
4469 self.getOperation().getContext()->get());
4470 },
4471 "trait_cls"_a, "Checks if the operation has a given trait.");
4472
4473 nb::class_<PyOperation, PyOperationBase>(m, "Operation")
4474 .def_static(
4475 "create",
4476 [](std::string_view name,
4477 std::optional<std::vector<PyType *>> results,
4478 std::optional<std::vector<PyValue *>> operands,
4479 std::optional<nb::typed<nb::dict, nb::str, PyAttribute>>
4480 attributes,
4481 std::optional<std::vector<PyBlock *>> successors, int regions,
4482 const std::optional<PyLocation> &location,
4483 const nb::object &maybeIp,
4484 bool inferType) -> nb::typed<nb::object, PyOperation> {
4485 // Unpack/validate operands.
4486 std::vector<MlirValue> mlirOperands;
4487 if (operands) {
4488 mlirOperands.reserve(operands->size());
4489 for (PyValue *operand : *operands) {
4490 if (!operand)
4491 throw nb::value_error("operand value cannot be None");
4492 mlirOperands.push_back(operand->get());
4493 }
4494 }
4495
4496 PyLocation pyLoc = maybeGetTracebackLocation(location);
4497 return PyOperation::create(
4498 name, results, mlirOperands.data(), mlirOperands.size(),
4499 attributes, successors, regions, pyLoc, maybeIp, inferType);
4500 },
4501 "name"_a, "results"_a = nb::none(), "operands"_a = nb::none(),
4502 "attributes"_a = nb::none(), "successors"_a = nb::none(),
4503 "regions"_a = 0, "loc"_a = nb::none(), "ip"_a = nb::none(),
4504 "infer_type"_a = false,
4505 R"(
4506 Creates a new operation.
4507
4508 Args:
4509 name: Operation name (e.g. `dialect.operation`).
4510 results: Optional sequence of Type representing op result types.
4511 operands: Optional operands of the operation.
4512 attributes: Optional Dict of {str: Attribute}.
4513 successors: Optional List of Block for the operation's successors.
4514 regions: Number of regions to create (default = 0).
4515 location: Optional Location object (defaults to resolve from context manager).
4516 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).
4517 infer_type: Whether to infer result types (default = False).
4518 Returns:
4519 A new detached Operation object. Detached operations can be added to blocks, which causes them to become attached.)")
4520 .def_static(
4521 "parse",
4522 [](const std::string &sourceStr, const std::string &sourceName,
4524 -> nb::typed<nb::object, PyOpView> {
4525 return PyOperation::parse(context->getRef(), sourceStr, sourceName)
4526 ->createOpView();
4527 },
4528 "source"_a, nb::kw_only(), "source_name"_a = "",
4529 "context"_a = nb::none(),
4530 "Parses an operation. Supports both text assembly format and binary "
4531 "bytecode format.")
4533 "Gets a capsule wrapping the MlirOperation.")
4536 "Creates an Operation from a capsule wrapping MlirOperation.")
4537 .def_prop_ro(
4538 "operation",
4539 [](nb::object self) -> nb::typed<nb::object, PyOperation> {
4540 return self;
4541 },
4542 "Returns self (the operation).")
4543 .def_prop_ro(
4544 "opview",
4545 [](PyOperation &self) -> nb::typed<nb::object, PyOpView> {
4546 return self.createOpView();
4547 },
4548 R"(
4549 Returns an OpView of this operation.
4550
4551 Note:
4552 If the operation has a registered and loaded dialect then this OpView will
4553 be concrete wrapper class.)")
4554 .def_prop_ro("block", &PyOperation::getBlock,
4555 "Returns the block containing this operation.")
4556 .def_prop_ro(
4557 "successors",
4558 [](PyOperationBase &self) {
4559 return PyOpSuccessors(self.getOperation().getRef());
4560 },
4561 "Returns the list of Operation successors.")
4562 .def(
4563 "replace_uses_of_with",
4564 [](PyOperation &self, PyValue &of, PyValue &with) {
4565 mlirOperationReplaceUsesOfWith(self.get(), of.get(), with.get());
4566 },
4567 "of"_a, "with_"_a,
4568 "Replaces uses of the 'of' value with the 'with' value inside the "
4569 "operation.")
4570 .def("_set_invalid", &PyOperation::setInvalid,
4571 "Invalidate the operation.");
4572
4573 auto opViewClass =
4574 nb::class_<PyOpView, PyOperationBase>(m, "OpView")
4575 .def(nb::init<nb::typed<nb::object, PyOperation>>(), "operation"_a)
4576 .def(
4577 "__init__",
4578 [](PyOpView *self, std::string_view name,
4579 std::tuple<int, bool> opRegionSpec,
4580 nb::object operandSegmentSpecObj,
4581 nb::object resultSegmentSpecObj,
4582 std::optional<nb::sequence> resultTypeList,
4583 nb::sequence operandList,
4584 std::optional<nb::typed<nb::dict, nb::str, PyAttribute>>
4585 attributes,
4586 std::optional<std::vector<PyBlock *>> successors,
4587 std::optional<int> regions,
4588 const std::optional<PyLocation> &location,
4589 const nb::object &maybeIp) {
4590 PyLocation pyLoc = maybeGetTracebackLocation(location);
4592 name, opRegionSpec, operandSegmentSpecObj,
4593 resultSegmentSpecObj, resultTypeList, operandList,
4594 attributes, successors, regions, pyLoc, maybeIp));
4595 },
4596 "name"_a, "opRegionSpec"_a,
4597 "operandSegmentSpecObj"_a = nb::none(),
4598 "resultSegmentSpecObj"_a = nb::none(), "results"_a = nb::none(),
4599 "operands"_a = nb::none(), "attributes"_a = nb::none(),
4600 "successors"_a = nb::none(), "regions"_a = nb::none(),
4601 "loc"_a = nb::none(), "ip"_a = nb::none())
4602 .def_prop_ro(
4603 "operation",
4604 [](PyOpView &self) -> nb::typed<nb::object, PyOperation> {
4605 return self.getOperationObject();
4606 })
4607 .def_prop_ro("opview",
4608 [](nb::object self) -> nb::typed<nb::object, PyOpView> {
4609 return self;
4610 })
4611 .def(
4612 "__str__",
4613 [](PyOpView &self) { return nb::str(self.getOperationObject()); })
4614 .def_prop_ro(
4615 "successors",
4616 [](PyOperationBase &self) {
4617 return PyOpSuccessors(self.getOperation().getRef());
4618 },
4619 "Returns the list of Operation successors.")
4620 .def(
4621 "_set_invalid",
4622 [](PyOpView &self) { self.getOperation().setInvalid(); },
4623 "Invalidate the operation.");
4624 opViewClass.attr("_ODS_REGIONS") = nb::make_tuple(0, true);
4625 opViewClass.attr("_ODS_OPERAND_SEGMENTS") = nb::none();
4626 opViewClass.attr("_ODS_RESULT_SEGMENTS") = nb::none();
4627 // It is faster to pass the operation_name, ods_regions, and
4628 // ods_operand_segments/ods_result_segments as arguments to the constructor,
4629 // rather than to access them as attributes.
4630 opViewClass.attr("build_generic") = classmethod(
4631 [](nb::handle cls, std::optional<nb::sequence> resultTypeList,
4632 nb::sequence operandList,
4633 std::optional<nb::typed<nb::dict, nb::str, PyAttribute>> attributes,
4634 std::optional<std::vector<PyBlock *>> successors,
4635 std::optional<int> regions, std::optional<PyLocation> location,
4636 const nb::object &maybeIp) {
4637 std::string name = nb::cast<std::string>(cls.attr("OPERATION_NAME"));
4638 std::tuple<int, bool> opRegionSpec =
4639 nb::cast<std::tuple<int, bool>>(cls.attr("_ODS_REGIONS"));
4640 nb::object operandSegmentSpec = cls.attr("_ODS_OPERAND_SEGMENTS");
4641 nb::object resultSegmentSpec = cls.attr("_ODS_RESULT_SEGMENTS");
4642 PyLocation pyLoc = maybeGetTracebackLocation(location);
4643 return PyOpView::buildGeneric(name, opRegionSpec, operandSegmentSpec,
4644 resultSegmentSpec, resultTypeList,
4645 operandList, attributes, successors,
4646 regions, pyLoc, maybeIp);
4647 },
4648 "cls"_a, "results"_a = nb::none(), "operands"_a = nb::none(),
4649 "attributes"_a = nb::none(), "successors"_a = nb::none(),
4650 "regions"_a = nb::none(), "loc"_a = nb::none(), "ip"_a = nb::none(),
4651 // clang-format off
4652 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"),
4653 // clang-format on
4654 "Builds a specific, generated OpView based on class level attributes.");
4655 opViewClass.attr("parse") = classmethod(
4656 [](const nb::object &cls, const std::string &sourceStr,
4657 const std::string &sourceName,
4658 DefaultingPyMlirContext context) -> nb::typed<nb::object, PyOpView> {
4659 PyOperationRef parsed =
4660 PyOperation::parse(context->getRef(), sourceStr, sourceName);
4661
4662 // Check if the expected operation was parsed, and cast to to the
4663 // appropriate `OpView` subclass if successful.
4664 // NOTE: This accesses attributes that have been automatically added to
4665 // `OpView` subclasses, and is not intended to be used on `OpView`
4666 // directly.
4667 std::string clsOpName =
4668 nb::cast<std::string>(cls.attr("OPERATION_NAME"));
4669 MlirStringRef identifier =
4671 std::string_view parsedOpName(identifier.data, identifier.length);
4672 if (clsOpName != parsedOpName)
4673 throw MLIRError(join("Expected a '", clsOpName, "' op, got: '",
4674 parsedOpName, "'"));
4675 return PyOpView::constructDerived(cls, parsed.getObject());
4676 },
4677 "cls"_a, "source"_a, nb::kw_only(), "source_name"_a = "",
4678 "context"_a = nb::none(),
4679 // clang-format off
4680 nb::sig("def parse(cls, source: str, *, source_name: str = '', context: Context | None = None) -> typing.Self"),
4681 // clang-format on
4682 "Parses a specific, generated OpView based on class level attributes.");
4683 opViewClass.attr("has_trait") = classmethod(
4684 [](nb::object &self, nb::type_object &traitCls,
4685 DefaultingPyMlirContext &context) {
4686 PyTypeID traitTypeID =
4687 nb::cast<PyTypeID>(traitCls.attr(PyDynamicOpTrait::typeIDAttr));
4688 std::string opName = nb::cast<std::string>(self.attr("OPERATION_NAME"));
4690 mlirStringRefCreate(opName.data(), opName.size()),
4691 traitTypeID.get(), context->get());
4692 },
4693 "cls"_a, "trait_cls"_a, "context"_a = nb::none(),
4694 "Checks if the operation has a given trait.");
4695
4697
4698 //----------------------------------------------------------------------------
4699 // Mapping of PyRegion.
4700 //----------------------------------------------------------------------------
4701 nb::class_<PyRegion>(m, "Region")
4702 .def_prop_ro(
4703 "blocks",
4704 [](PyRegion &self) {
4705 return PyBlockList(self.getParentOperation(), self.get());
4706 },
4707 "Returns a forward-optimized sequence of blocks.")
4708 .def_prop_ro(
4709 "owner",
4710 [](PyRegion &self) -> nb::typed<nb::object, PyOpView> {
4711 return self.getParentOperation()->createOpView();
4712 },
4713 "Returns the operation owning this region.")
4714 .def(
4715 "__iter__",
4716 [](PyRegion &self) {
4717 self.checkValid();
4718 MlirBlock firstBlock = mlirRegionGetFirstBlock(self.get());
4719 return PyBlockIterator(self.getParentOperation(), firstBlock);
4720 },
4721 "Iterates over blocks in the region.")
4722 .def(
4723 "__eq__",
4724 [](PyRegion &self, PyRegion &other) {
4725 return self.get().ptr == other.get().ptr;
4726 },
4727 "Compares two regions for pointer equality.")
4728 .def(
4729 "__eq__", [](PyRegion &self, nb::object &other) { return false; },
4730 "Compares region with non-region object (always returns False).");
4731
4732 //----------------------------------------------------------------------------
4733 // Mapping of PyBlock.
4734 //----------------------------------------------------------------------------
4735 nb::class_<PyBlock>(m, "Block")
4737 "Gets a capsule wrapping the MlirBlock.")
4738 .def_prop_ro(
4739 "owner",
4740 [](PyBlock &self) -> nb::typed<nb::object, PyOpView> {
4741 return self.getParentOperation()->createOpView();
4742 },
4743 "Returns the owning operation of this block.")
4744 .def_prop_ro(
4745 "region",
4746 [](PyBlock &self) {
4747 MlirRegion region = mlirBlockGetParentRegion(self.get());
4748 return PyRegion(self.getParentOperation(), region);
4749 },
4750 "Returns the owning region of this block.")
4751 .def_prop_ro(
4752 "arguments",
4753 [](PyBlock &self) {
4754 return PyBlockArgumentList(self.getParentOperation(), self.get());
4755 },
4756 "Returns a list of block arguments.")
4757 .def(
4758 "add_argument",
4759 [](PyBlock &self, const PyType &type, const PyLocation &loc) {
4760 return PyBlockArgument(self.getParentOperation(),
4761 mlirBlockAddArgument(self.get(), type, loc));
4762 },
4763 "type"_a, "loc"_a,
4764 R"(
4765 Appends an argument of the specified type to the block.
4766
4767 Args:
4768 type: The type of the argument to add.
4769 loc: The source location for the argument.
4770
4771 Returns:
4772 The newly added block argument.)")
4773 .def(
4774 "erase_argument",
4775 [](PyBlock &self, unsigned index) {
4776 return mlirBlockEraseArgument(self.get(), index);
4777 },
4778 "index"_a,
4779 R"(
4780 Erases the argument at the specified index.
4781
4782 Args:
4783 index: The index of the argument to erase.)")
4784 .def_prop_ro(
4785 "operations",
4786 [](PyBlock &self) {
4787 return PyOperationList(self.getParentOperation(), self.get());
4788 },
4789 "Returns a forward-optimized sequence of operations.")
4790 .def_static(
4791 "create_at_start",
4792 [](PyRegion &parent, nb::typed<nb::sequence, PyType> pyArgTypes,
4793 const std::optional<nb::typed<nb::sequence, PyLocation>>
4794 &pyArgLocs) {
4795 parent.checkValid();
4796 MlirBlock block = createBlock(pyArgTypes, pyArgLocs);
4797 mlirRegionInsertOwnedBlock(parent, 0, block);
4798 return PyBlock(parent.getParentOperation(), block);
4799 },
4800 "parent"_a, "arg_types"_a = nb::list(), "arg_locs"_a = std::nullopt,
4801 "Creates and returns a new Block at the beginning of the given "
4802 "region (with given argument types and locations).")
4803 .def(
4804 "append_to",
4805 [](PyBlock &self, PyRegion &region) {
4806 MlirBlock b = self.get();
4809 mlirRegionAppendOwnedBlock(region.get(), b);
4810 },
4811 "region"_a,
4812 R"(
4813 Appends this block to a region.
4814
4815 Transfers ownership if the block is currently owned by another region.
4816
4817 Args:
4818 region: The region to append the block to.)")
4819 .def(
4820 "create_before",
4821 [](PyBlock &self, const nb::args &pyArgTypes,
4822 const std::optional<nb::typed<nb::sequence, PyLocation>>
4823 &pyArgLocs) {
4824 self.checkValid();
4825 MlirBlock block =
4826 createBlock(nb::cast<nb::sequence>(pyArgTypes), pyArgLocs);
4827 MlirRegion region = mlirBlockGetParentRegion(self.get());
4828 mlirRegionInsertOwnedBlockBefore(region, self.get(), block);
4829 return PyBlock(self.getParentOperation(), block);
4830 },
4831 "arg_types"_a, nb::kw_only(), "arg_locs"_a = std::nullopt,
4832 "Creates and returns a new Block before this block "
4833 "(with given argument types and locations).")
4834 .def(
4835 "create_after",
4836 [](PyBlock &self, const nb::args &pyArgTypes,
4837 const std::optional<nb::typed<nb::sequence, PyLocation>>
4838 &pyArgLocs) {
4839 self.checkValid();
4840 MlirBlock block =
4841 createBlock(nb::cast<nb::sequence>(pyArgTypes), pyArgLocs);
4842 MlirRegion region = mlirBlockGetParentRegion(self.get());
4843 mlirRegionInsertOwnedBlockAfter(region, self.get(), block);
4844 return PyBlock(self.getParentOperation(), block);
4845 },
4846 "arg_types"_a, nb::kw_only(), "arg_locs"_a = std::nullopt,
4847 "Creates and returns a new Block after this block "
4848 "(with given argument types and locations).")
4849 .def(
4850 "__iter__",
4851 [](PyBlock &self) {
4852 self.checkValid();
4853 MlirOperation firstOperation =
4854 mlirBlockGetFirstOperation(self.get());
4855 return PyOperationIterator(self.getParentOperation(),
4856 firstOperation);
4857 },
4858 "Iterates over operations in the block.")
4859 .def(
4860 "__eq__",
4861 [](PyBlock &self, PyBlock &other) {
4862 return self.get().ptr == other.get().ptr;
4863 },
4864 "Compares two blocks for pointer equality.")
4865 .def(
4866 "__eq__", [](PyBlock &self, nb::object &other) { return false; },
4867 "Compares block with non-block object (always returns False).")
4868 .def(
4869 "__hash__", [](PyBlock &self) { return hash(self.get().ptr); },
4870 "Returns the hash value of the block.")
4871 .def(
4872 "__str__",
4873 [](PyBlock &self) {
4874 self.checkValid();
4875 PyPrintAccumulator printAccum;
4876 mlirBlockPrint(self.get(), printAccum.getCallback(),
4877 printAccum.getUserData());
4878 return printAccum.join();
4879 },
4880 "Returns the assembly form of the block.")
4881 .def(
4882 "append",
4883 [](PyBlock &self, PyOperationBase &operation) {
4884 if (operation.getOperation().isAttached())
4885 operation.getOperation().detachFromParent();
4886
4887 MlirOperation mlirOperation = operation.getOperation().get();
4888 mlirBlockAppendOwnedOperation(self.get(), mlirOperation);
4889 operation.getOperation().setAttached(
4890 self.getParentOperation().getObject());
4891 },
4892 "operation"_a,
4893 R"(
4894 Appends an operation to this block.
4895
4896 If the operation is currently in another block, it will be moved.
4897
4898 Args:
4899 operation: The operation to append to the block.)")
4900 .def_prop_ro(
4901 "successors",
4902 [](PyBlock &self) {
4903 return PyBlockSuccessors(self, self.getParentOperation());
4904 },
4905 "Returns the list of Block successors.")
4906 .def_prop_ro(
4907 "predecessors",
4908 [](PyBlock &self) {
4909 return PyBlockPredecessors(self, self.getParentOperation());
4910 },
4911 "Returns the list of Block predecessors.");
4912
4913 //----------------------------------------------------------------------------
4914 // Mapping of PyInsertionPoint.
4915 //----------------------------------------------------------------------------
4916
4917 nb::class_<PyInsertionPoint>(m, "InsertionPoint")
4918 .def(nb::init<PyBlock &>(), "block"_a,
4919 "Inserts after the last operation but still inside the block.")
4920 .def("__enter__", &PyInsertionPoint::contextEnter,
4921 "Enters the insertion point as a context manager.",
4922 nb::sig("def __enter__(self, /) -> InsertionPoint"))
4923 .def("__exit__", &PyInsertionPoint::contextExit, "exc_type"_a.none(),
4924 "exc_value"_a.none(), "traceback"_a.none(),
4925 "Exits the insertion point context manager.")
4926 .def_prop_ro_static(
4927 "current",
4928 [](nb::object & /*class*/) {
4930 if (!ip)
4931 throw nb::value_error("No current InsertionPoint");
4932 return ip;
4933 },
4934 nb::sig("def current(/) -> InsertionPoint"),
4935 "Gets the InsertionPoint bound to the current thread or raises "
4936 "ValueError if none has been set.")
4937 .def(nb::init<PyOperationBase &>(), "beforeOperation"_a,
4938 "Inserts before a referenced operation.")
4939 .def_static("at_block_begin", &PyInsertionPoint::atBlockBegin, "block"_a,
4940 R"(
4941 Creates an insertion point at the beginning of a block.
4942
4943 Args:
4944 block: The block at whose beginning operations should be inserted.
4945
4946 Returns:
4947 An InsertionPoint at the block's beginning.)")
4948 .def_static("at_block_terminator", &PyInsertionPoint::atBlockTerminator,
4949 "block"_a,
4950 R"(
4951 Creates an insertion point before a block's terminator.
4952
4953 Args:
4954 block: The block whose terminator to insert before.
4955
4956 Returns:
4957 An InsertionPoint before the terminator.
4958
4959 Raises:
4960 ValueError: If the block has no terminator.)")
4961 .def_static("after", &PyInsertionPoint::after, "operation"_a,
4962 R"(
4963 Creates an insertion point immediately after an operation.
4964
4965 Args:
4966 operation: The operation after which to insert.
4967
4968 Returns:
4969 An InsertionPoint after the operation.)")
4970 .def("insert", &PyInsertionPoint::insert, "operation"_a,
4971 R"(
4972 Inserts an operation at this insertion point.
4973
4974 Args:
4975 operation: The operation to insert.)")
4976 .def_prop_ro(
4977 "block", [](PyInsertionPoint &self) { return self.getBlock(); },
4978 "Returns the block that this `InsertionPoint` points to.")
4979 .def_prop_ro(
4980 "ref_operation",
4981 [](PyInsertionPoint &self)
4982 -> std::optional<nb::typed<nb::object, PyOperation>> {
4983 auto refOperation = self.getRefOperation();
4984 if (refOperation)
4985 return refOperation->getObject();
4986 return {};
4987 },
4988 "The reference operation before which new operations are "
4989 "inserted, or None if the insertion point is at the end of "
4990 "the block.");
4991
4992 //----------------------------------------------------------------------------
4993 // Mapping of PyAttribute.
4994 //----------------------------------------------------------------------------
4995 nb::class_<PyAttribute>(m, "Attribute")
4996 // Delegate to the PyAttribute copy constructor, which will also lifetime
4997 // extend the backing context which owns the MlirAttribute.
4998 .def(nb::init<PyAttribute &>(), "cast_from_type"_a,
4999 "Casts the passed attribute to the generic `Attribute`.")
5001 "Gets a capsule wrapping the MlirAttribute.")
5002 .def_static(
5004 "Creates an Attribute from a capsule wrapping `MlirAttribute`.")
5005 .def_static(
5006 "parse",
5007 [](const std::string &attrSpec, DefaultingPyMlirContext context)
5008 -> nb::typed<nb::object, PyAttribute> {
5009 PyMlirContext::ErrorCapture errors(context->getRef());
5010 MlirAttribute attr = mlirAttributeParseGet(
5011 context->get(), toMlirStringRef(attrSpec));
5012 if (mlirAttributeIsNull(attr))
5013 throw MLIRError("Unable to parse attribute", errors.take());
5014 return PyAttribute(context.get()->getRef(), attr).maybeDownCast();
5015 },
5016 "asm"_a, "context"_a = nb::none(),
5017 "Parses an attribute from an assembly form. Raises an `MLIRError` on "
5018 "failure.")
5019 .def_prop_ro(
5020 "context",
5021 [](PyAttribute &self) -> nb::typed<nb::object, PyMlirContext> {
5022 return self.getContext().getObject();
5023 },
5024 "Context that owns the `Attribute`.")
5025 .def_prop_ro(
5026 "type",
5027 [](PyAttribute &self) -> nb::typed<nb::object, PyType> {
5028 return PyType(self.getContext(), mlirAttributeGetType(self))
5029 .maybeDownCast();
5030 },
5031 "Returns the type of the `Attribute`.")
5032 .def(
5033 "get_named",
5034 [](PyAttribute &self, std::string name) {
5035 return PyNamedAttribute(self, std::move(name));
5036 },
5037 nb::keep_alive<0, 1>(),
5038 R"(
5039 Binds a name to the attribute, creating a `NamedAttribute`.
5040
5041 Args:
5042 name: The name to bind to the `Attribute`.
5043
5044 Returns:
5045 A `NamedAttribute` with the given name and this attribute.)")
5046 .def(
5047 "__eq__",
5048 [](PyAttribute &self, PyAttribute &other) { return self == other; },
5049 "Compares two attributes for equality.")
5050 .def(
5051 "__eq__", [](PyAttribute &self, nb::object &other) { return false; },
5052 "Compares attribute with non-attribute object (always returns "
5053 "False).")
5054 .def(
5055 "__hash__", [](PyAttribute &self) { return hash(self.get().ptr); },
5056 "Returns the hash value of the attribute.")
5057 .def(
5058 "dump", [](PyAttribute &self) { mlirAttributeDump(self); },
5060 .def(
5061 "__str__",
5062 [](PyAttribute &self) {
5063 PyPrintAccumulator printAccum;
5064 mlirAttributePrint(self, printAccum.getCallback(),
5065 printAccum.getUserData());
5066 return printAccum.join();
5067 },
5068 "Returns the assembly form of the Attribute.")
5069 .def(
5070 "__repr__",
5071 [](PyAttribute &self) {
5072 // Generally, assembly formats are not printed for __repr__ because
5073 // this can cause exceptionally long debug output and exceptions.
5074 // However, attribute values are generally considered useful and
5075 // are printed. This may need to be re-evaluated if debug dumps end
5076 // up being excessive.
5077 PyPrintAccumulator printAccum;
5078 printAccum.parts.append("Attribute(");
5079 mlirAttributePrint(self, printAccum.getCallback(),
5080 printAccum.getUserData());
5081 printAccum.parts.append(")");
5082 return printAccum.join();
5083 },
5084 "Returns a string representation of the attribute.")
5085 .def_prop_ro(
5086 "typeid",
5087 [](PyAttribute &self) {
5088 MlirTypeID mlirTypeID = mlirAttributeGetTypeID(self);
5089 assert(!mlirTypeIDIsNull(mlirTypeID) &&
5090 "mlirTypeID was expected to be non-null.");
5091 return PyTypeID(mlirTypeID);
5092 },
5093 "Returns the `TypeID` of the attribute.")
5094 .def(
5096 [](PyAttribute &self) -> nb::typed<nb::object, PyAttribute> {
5097 return self.maybeDownCast();
5098 },
5099 "Downcasts the attribute to a more specific attribute if possible.");
5100
5101 //----------------------------------------------------------------------------
5102 // Mapping of PyNamedAttribute
5103 //----------------------------------------------------------------------------
5104 nb::class_<PyNamedAttribute>(m, "NamedAttribute")
5105 .def(
5106 "__repr__",
5107 [](PyNamedAttribute &self) {
5108 PyPrintAccumulator printAccum;
5109 printAccum.parts.append("NamedAttribute(");
5110 printAccum.parts.append(
5111 nb::str(mlirIdentifierStr(self.namedAttr.name).data,
5112 mlirIdentifierStr(self.namedAttr.name).length));
5113 printAccum.parts.append("=");
5114 mlirAttributePrint(self.namedAttr.attribute,
5115 printAccum.getCallback(),
5116 printAccum.getUserData());
5117 printAccum.parts.append(")");
5118 return printAccum.join();
5119 },
5120 "Returns a string representation of the named attribute.")
5121 .def_prop_ro(
5122 "name",
5123 [](PyNamedAttribute &self) {
5124 return mlirIdentifierStr(self.namedAttr.name);
5125 },
5126 "The name of the `NamedAttribute` binding.")
5127 .def_prop_ro(
5128 "attr",
5129 [](PyNamedAttribute &self) { return self.namedAttr.attribute; },
5130 nb::keep_alive<0, 1>(), nb::sig("def attr(self) -> Attribute"),
5131 "The underlying generic attribute of the `NamedAttribute` binding.");
5132
5133 //----------------------------------------------------------------------------
5134 // Mapping of PyType.
5135 //----------------------------------------------------------------------------
5136 nb::class_<PyType>(m, "Type")
5137 // Delegate to the PyType copy constructor, which will also lifetime
5138 // extend the backing context which owns the MlirType.
5139 .def(nb::init<PyType &>(), "cast_from_type"_a,
5140 "Casts the passed type to the generic `Type`.")
5142 "Gets a capsule wrapping the `MlirType`.")
5144 "Creates a Type from a capsule wrapping `MlirType`.")
5145 .def_static(
5146 "parse",
5147 [](std::string typeSpec,
5148 DefaultingPyMlirContext context) -> nb::typed<nb::object, PyType> {
5149 PyMlirContext::ErrorCapture errors(context->getRef());
5150 MlirType type =
5151 mlirTypeParseGet(context->get(), toMlirStringRef(typeSpec));
5152 if (mlirTypeIsNull(type))
5153 throw MLIRError("Unable to parse type", errors.take());
5154 return PyType(context.get()->getRef(), type).maybeDownCast();
5155 },
5156 "asm"_a, "context"_a = nb::none(),
5157 R"(
5158 Parses the assembly form of a type.
5159
5160 Returns a Type object or raises an `MLIRError` if the type cannot be parsed.
5161
5162 See also: https://mlir.llvm.org/docs/LangRef/#type-system)")
5163 .def_prop_ro(
5164 "context",
5165 [](PyType &self) -> nb::typed<nb::object, PyMlirContext> {
5166 return self.getContext().getObject();
5167 },
5168 "Context that owns the `Type`.")
5169 .def(
5170 "__eq__", [](PyType &self, PyType &other) { return self == other; },
5171 "Compares two types for equality.")
5172 .def(
5173 "__eq__", [](PyType &self, nb::object &other) { return false; },
5174 "other"_a.none(),
5175 "Compares type with non-type object (always returns False).")
5176 .def(
5177 "__hash__", [](PyType &self) { return hash(self.get().ptr); },
5178 "Returns the hash value of the `Type`.")
5179 .def(
5180 "dump", [](PyType &self) { mlirTypeDump(self); }, kDumpDocstring)
5181 .def(
5182 "__str__",
5183 [](PyType &self) {
5184 PyPrintAccumulator printAccum;
5185 mlirTypePrint(self, printAccum.getCallback(),
5186 printAccum.getUserData());
5187 return printAccum.join();
5188 },
5189 "Returns the assembly form of the `Type`.")
5190 .def(
5191 "__repr__",
5192 [](PyType &self) {
5193 // Generally, assembly formats are not printed for __repr__ because
5194 // this can cause exceptionally long debug output and exceptions.
5195 // However, types are an exception as they typically have compact
5196 // assembly forms and printing them is useful.
5197 PyPrintAccumulator printAccum;
5198 printAccum.parts.append("Type(");
5199 mlirTypePrint(self, printAccum.getCallback(),
5200 printAccum.getUserData());
5201 printAccum.parts.append(")");
5202 return printAccum.join();
5203 },
5204 "Returns a string representation of the `Type`.")
5205 .def(
5207 [](PyType &self) -> nb::typed<nb::object, PyType> {
5208 return self.maybeDownCast();
5209 },
5210 "Downcasts the Type to a more specific `Type` if possible.")
5211 .def_prop_ro(
5212 "typeid",
5213 [](PyType &self) {
5214 MlirTypeID mlirTypeID = mlirTypeGetTypeID(self);
5215 if (!mlirTypeIDIsNull(mlirTypeID))
5216 return PyTypeID(mlirTypeID);
5217 auto origRepr = nb::cast<std::string>(nb::repr(nb::cast(self)));
5218 throw nb::value_error(join(origRepr, " has no typeid.").c_str());
5219 },
5220 "Returns the `TypeID` of the `Type`, or raises `ValueError` if "
5221 "`Type` has no "
5222 "`TypeID`.");
5223
5224 //----------------------------------------------------------------------------
5225 // Mapping of PyTypeID.
5226 //----------------------------------------------------------------------------
5227 nb::class_<PyTypeID>(m, "TypeID")
5229 "Gets a capsule wrapping the `MlirTypeID`.")
5231 "Creates a `TypeID` from a capsule wrapping `MlirTypeID`.")
5232 // Note, this tests whether the underlying TypeIDs are the same,
5233 // not whether the wrapper MlirTypeIDs are the same, nor whether
5234 // the Python objects are the same (i.e., PyTypeID is a value type).
5235 .def(
5236 "__eq__",
5237 [](PyTypeID &self, PyTypeID &other) { return self == other; },
5238 "Compares two `TypeID`s for equality.")
5239 .def(
5240 "__eq__",
5241 [](PyTypeID &self, const nb::object &other) { return false; },
5242 "Compares TypeID with non-TypeID object (always returns False).")
5243 // Note, this gives the hash value of the underlying TypeID, not the
5244 // hash value of the Python object, nor the hash value of the
5245 // MlirTypeID wrapper.
5246 .def(
5247 "__hash__",
5248 [](PyTypeID &self) {
5249 return static_cast<size_t>(mlirTypeIDHashValue(self));
5250 },
5251 "Returns the hash value of the `TypeID`.");
5252
5253 //----------------------------------------------------------------------------
5254 // Mapping of Value.
5255 //----------------------------------------------------------------------------
5256 m.attr("_T") = nb::type_var("_T", "bound"_a = m.attr("Type"));
5257
5258 nb::class_<PyValue>(m, "Value", nb::is_generic(),
5259 nb::sig("class Value(typing.Generic[_T])"))
5260 .def(nb::init<PyValue &>(), nb::keep_alive<0, 1>(), "value"_a,
5261 "Creates a Value reference from another `Value`.")
5263 "Gets a capsule wrapping the `MlirValue`.")
5265 "Creates a `Value` from a capsule wrapping `MlirValue`.")
5266 .def_prop_ro(
5267 "context",
5268 [](PyValue &self) -> nb::typed<nb::object, PyMlirContext> {
5269 return self.getParentOperation()->getContext().getObject();
5270 },
5271 "Context in which the value lives.")
5272 .def(
5273 "dump", [](PyValue &self) { mlirValueDump(self.get()); },
5275 .def_prop_ro(
5276 "owner",
5277 [](PyValue &self)
5278 -> nb::typed<nb::object, std::variant<PyOpView, PyBlock>> {
5279 MlirValue v = self.get();
5280 if (mlirValueIsAOpResult(v)) {
5281 assert(mlirOperationEqual(self.getParentOperation()->get(),
5282 mlirOpResultGetOwner(self.get())) &&
5283 "expected the owner of the value in Python to match "
5284 "that in "
5285 "the IR");
5286 return self.getParentOperation()->createOpView();
5287 }
5288
5290 MlirBlock block = mlirBlockArgumentGetOwner(self.get());
5291 return nb::cast(PyBlock(self.getParentOperation(), block));
5292 }
5293
5294 assert(false && "Value must be a block argument or an op result");
5295 return nb::none();
5296 },
5297 "Returns the owner of the value (`Operation` for results, `Block` "
5298 "for "
5299 "arguments).")
5300 .def_prop_ro(
5301 "uses",
5302 [](PyValue &self) {
5303 return PyOpOperandIterator(mlirValueGetFirstUse(self.get()));
5304 },
5305 "Returns an iterator over uses of this value.")
5306 .def(
5307 "__eq__",
5308 [](PyValue &self, PyValue &other) {
5309 return self.get().ptr == other.get().ptr;
5310 },
5311 "Compares two values for pointer equality.")
5312 .def(
5313 "__eq__", [](PyValue &self, nb::object other) { return false; },
5314 "Compares value with non-value object (always returns False).")
5315 .def(
5316 "__hash__", [](PyValue &self) { return hash(self.get().ptr); },
5317 "Returns the hash value of the value.")
5318 .def(
5319 "__str__",
5320 [](PyValue &self) {
5321 PyPrintAccumulator printAccum;
5322 printAccum.parts.append("Value(");
5323 mlirValuePrint(self.get(), printAccum.getCallback(),
5324 printAccum.getUserData());
5325 printAccum.parts.append(")");
5326 return printAccum.join();
5327 },
5328 R"(
5329 Returns the string form of the value.
5330
5331 If the value is a block argument, this is the assembly form of its type and the
5332 position in the argument list. If the value is an operation result, this is
5333 equivalent to printing the operation that produced it.
5334 )")
5335 .def(
5336 "get_name",
5337 [](PyValue &self, bool useLocalScope, bool useNameLocAsPrefix) {
5338 PyPrintAccumulator printAccum;
5339 MlirOpPrintingFlags flags = mlirOpPrintingFlagsCreate();
5340 if (useLocalScope)
5342 if (useNameLocAsPrefix)
5344 MlirAsmState valueState =
5345 mlirAsmStateCreateForValue(self.get(), flags);
5346 mlirValuePrintAsOperand(self.get(), valueState,
5347 printAccum.getCallback(),
5348 printAccum.getUserData());
5350 mlirAsmStateDestroy(valueState);
5351 return printAccum.join();
5352 },
5353 "use_local_scope"_a = false, "use_name_loc_as_prefix"_a = false,
5354 R"(
5355 Returns the string form of value as an operand.
5356
5357 Args:
5358 use_local_scope: Whether to use local scope for naming.
5359 use_name_loc_as_prefix: Whether to use the location attribute (NameLoc) as prefix.
5360
5361 Returns:
5362 The value's name as it appears in IR (e.g., `%0`, `%arg0`).)")
5363 .def(
5364 "get_name",
5365 [](PyValue &self, PyAsmState &state) {
5366 PyPrintAccumulator printAccum;
5367 MlirAsmState valueState = state.get();
5368 mlirValuePrintAsOperand(self.get(), valueState,
5369 printAccum.getCallback(),
5370 printAccum.getUserData());
5371 return printAccum.join();
5372 },
5373 "state"_a,
5374 "Returns the string form of value as an operand (i.e., the ValueID).")
5375 .def_prop_ro(
5376 "type",
5377 [](PyValue &self) {
5378 return PyType(self.getParentOperation()->getContext(),
5379 mlirValueGetType(self.get()))
5380 .maybeDownCast();
5381 },
5382 "Returns the type of the value.", nb::sig("def type(self) -> _T"))
5383 .def(
5384 "set_type",
5385 [](PyValue &self, const PyType &type) {
5386 mlirValueSetType(self.get(), type);
5387 },
5388 "type"_a, "Sets the type of the value.",
5389 nb::sig("def set_type(self, type: _T)"))
5390 .def(
5391 "replace_all_uses_with",
5392 [](PyValue &self, PyValue &with) {
5393 mlirValueReplaceAllUsesOfWith(self.get(), with.get());
5394 },
5395 "Replace all uses of value with the new value, updating anything in "
5396 "the IR that uses `self` to use the other value instead.")
5397 .def(
5398 "replace_all_uses_except",
5399 [](PyValue &self, PyValue &with, PyOperation &exception) {
5400 MlirOperation exceptedUser = exception.get();
5401 mlirValueReplaceAllUsesExcept(self, with, 1, &exceptedUser);
5402 },
5403 "with_"_a, "exceptions"_a, kValueReplaceAllUsesExceptDocstring)
5404 .def(
5405 "replace_all_uses_except",
5406 [](PyValue &self, PyValue &with,
5407 std::vector<PyOperation> &exceptions) {
5408 // Convert Python list to a std::vector of MlirOperations
5409 std::vector<MlirOperation> exceptionOps;
5410 for (PyOperation &exception : exceptions)
5411 exceptionOps.push_back(exception);
5413 self, with, static_cast<intptr_t>(exceptionOps.size()),
5414 exceptionOps.data());
5415 },
5416 "with_"_a, "exceptions"_a, kValueReplaceAllUsesExceptDocstring)
5417 .def(
5419 [](PyValue &self) { return self.maybeDownCast(); },
5420 "Downcasts the `Value` to a more specific kind if possible.")
5421 .def_prop_ro(
5422 "location",
5423 [](PyValue self) {
5424 return PyLocation(
5427 .maybeDownCast();
5428 },
5429 "Returns the source location of the value.");
5430
5434
5435 nb::class_<PyAsmState>(m, "AsmState")
5436 .def(nb::init<PyValue &, bool>(), "value"_a, "use_local_scope"_a = false,
5437 R"(
5438 Creates an `AsmState` for consistent SSA value naming.
5439
5440 Args:
5441 value: The value to create state for.
5442 use_local_scope: Whether to use local scope for naming.)")
5443 .def(nb::init<PyOperationBase &, bool>(), "op"_a,
5444 "use_local_scope"_a = false,
5445 R"(
5446 Creates an AsmState for consistent SSA value naming.
5447
5448 Args:
5449 op: The operation to create state for.
5450 use_local_scope: Whether to use local scope for naming.)");
5451
5452 //----------------------------------------------------------------------------
5453 // Mapping of SymbolTable.
5454 //----------------------------------------------------------------------------
5455 nb::class_<PySymbolTable>(m, "SymbolTable")
5456 .def(nb::init<PyOperationBase &>(),
5457 R"(
5458 Creates a symbol table for an operation.
5459
5460 Args:
5461 operation: The `Operation` that defines a symbol table (e.g., a `ModuleOp`).
5462
5463 Raises:
5464 TypeError: If the operation is not a symbol table.)")
5465 .def(
5466 "__getitem__",
5467 [](PySymbolTable &self,
5468 const std::string &name) -> nb::typed<nb::object, PyOpView> {
5469 return self.dunderGetItem(name);
5470 },
5471 R"(
5472 Looks up a symbol by name in the symbol table.
5473
5474 Args:
5475 name: The name of the symbol to look up.
5476
5477 Returns:
5478 The operation defining the symbol.
5479
5480 Raises:
5481 KeyError: If the symbol is not found.)")
5482 .def("insert", &PySymbolTable::insert, "operation"_a,
5483 R"(
5484 Inserts a symbol operation into the symbol table.
5485
5486 Args:
5487 operation: An operation with a symbol name to insert.
5488
5489 Returns:
5490 The symbol name attribute of the inserted operation.
5491
5492 Raises:
5493 ValueError: If the operation does not have a symbol name.)")
5494 .def("erase", &PySymbolTable::erase, "operation"_a,
5495 R"(
5496 Erases a symbol operation from the symbol table.
5497
5498 Args:
5499 operation: The symbol operation to erase.
5500
5501 Note:
5502 The operation is also erased from the IR and invalidated.)")
5503 .def("__delitem__", &PySymbolTable::dunderDel,
5504 "Deletes a symbol by name from the symbol table.")
5505 .def(
5506 "__contains__",
5507 [](PySymbolTable &table, const std::string &name) {
5508 return !mlirOperationIsNull(mlirSymbolTableLookup(
5509 table, mlirStringRefCreate(name.data(), name.length())));
5510 },
5511 "Checks if a symbol with the given name exists in the table.")
5512 // Static helpers.
5513 .def_static("set_symbol_name", &PySymbolTable::setSymbolName, "symbol"_a,
5514 "name"_a, "Sets the symbol name for a symbol operation.")
5515 .def_static("get_symbol_name", &PySymbolTable::getSymbolName, "symbol"_a,
5516 "Gets the symbol name from a symbol operation.")
5517 .def_static("get_visibility", &PySymbolTable::getVisibility, "symbol"_a,
5518 "Gets the visibility attribute of a symbol operation.")
5519 .def_static("set_visibility", &PySymbolTable::setVisibility, "symbol"_a,
5520 "visibility"_a,
5521 "Sets the visibility attribute of a symbol operation.")
5522 .def_static("replace_all_symbol_uses",
5523 &PySymbolTable::replaceAllSymbolUses, "old_symbol"_a,
5524 "new_symbol"_a, "from_op"_a,
5525 "Replaces all uses of a symbol with a new symbol name within "
5526 "the given operation.")
5527 .def_static("walk_symbol_tables", &PySymbolTable::walkSymbolTables,
5528 "from_op"_a, "all_sym_uses_visible"_a, "callback"_a,
5529 "Walks symbol tables starting from an operation with a "
5530 "callback function.");
5531
5532 // Container bindings.
5547
5548 // Debug bindings.
5550
5551 // Attribute builder getter.
5553
5554 // Extensible Dialect
5560
5561 // MLIRError exception.
5562 MLIRError::bind(m);
5563
5564 // Register an atexit handler to clear the thread-local context stack.
5565 // The stack holds nb::object references that prevent Python GC of Contexts.
5566 // At interpreter shutdown, thread_local storage outlives Py_Finalize() on
5567 // the main thread. When the thread_local vector destructs, its nb::object
5568 // members call Py_DECREF through the dead runtime, causing a segfault.
5569 // Clearing the stack in atexit releases references while alive.
5570 nb::module_::import_("atexit").attr("register")(
5571 nb::cpp_function([]() { PyThreadContextEntry::getStack().clear(); }));
5572}
5573} // namespace MLIR_BINDINGS_PYTHON_DOMAIN
5574} // namespace python
5575} // namespace mlir
return success()
void mlirSetGlobalDebugTypes(const char **types, intptr_t n)
Definition Debug.cpp:28
MLIR_CAPI_EXPORTED void mlirSetGlobalDebugType(const char *type)
Sets the current debug type, similarly to -debug-only=type in the command-line tools.
Definition Debug.cpp:20
MLIR_CAPI_EXPORTED bool mlirIsGlobalDebugEnabled()
Retuns true if the global debugging flag is set, false otherwise.
Definition Debug.cpp:18
MLIR_CAPI_EXPORTED void mlirEnableGlobalDebug(bool enable)
Sets the global debugging flag.
Definition Debug.cpp:16
static const char kDumpDocstring[]
Definition IRAffine.cpp:32
static const char kModuleParseDocstring[]
Definition IRCore.cpp:34
static size_t hash(const T &value)
Local helper to compute std::hash for a value.
Definition IRCore.cpp:57
static nb::object createCustomDialectWrapper(const std::string &dialectNamespace, nb::object dialectDescriptor)
Definition IRCore.cpp:62
std::string join(const Ts &...args)
Helper function to concatenate arguments into a std::string.
static const char kValueReplaceAllUsesExceptDocstring[]
Definition IRCore.cpp:45
MlirContext mlirModuleGetContext(MlirModule module)
Definition IR.cpp:471
size_t mlirModuleHashValue(MlirModule mod)
Definition IR.cpp:497
intptr_t mlirBlockGetNumPredecessors(MlirBlock block)
Definition IR.cpp:1161
MlirIdentifier mlirOperationGetName(MlirOperation op)
Definition IR.cpp:719
bool mlirValueIsABlockArgument(MlirValue value)
Definition IR.cpp:1181
intptr_t mlirOperationGetNumRegions(MlirOperation op)
Definition IR.cpp:739
MlirBlock mlirOperationGetBlock(MlirOperation op)
Definition IR.cpp:723
void mlirBlockArgumentSetType(MlirValue value, MlirType type)
Definition IR.cpp:1198
void mlirOperationStateAddAttributes(MlirOperationState *state, intptr_t n, MlirNamedAttribute const *attributes)
Definition IR.cpp:546
MlirValue mlirOperationGetResult(MlirOperation op, intptr_t pos)
Definition IR.cpp:794
MlirModule mlirModuleCreateParseFromFile(MlirContext context, MlirStringRef fileName)
Definition IR.cpp:462
bool mlirOperationNameHasTrait(MlirStringRef opName, MlirTypeID traitTypeID, MlirContext context)
Definition IR.cpp:699
MlirAsmState mlirAsmStateCreateForValue(MlirValue value, MlirOpPrintingFlags flags)
Definition IR.cpp:195
intptr_t mlirOperationGetNumResults(MlirOperation op)
Definition IR.cpp:790
bool mlirOperationIsAncestor(MlirOperation a, MlirOperation b)
Definition IR.cpp:731
void mlirOperationDestroy(MlirOperation op)
Definition IR.cpp:664
MlirContext mlirAttributeGetContext(MlirAttribute attribute)
Definition IR.cpp:1362
MlirType mlirValueGetType(MlirValue value)
Definition IR.cpp:1217
void mlirBlockPrint(MlirBlock block, MlirStringCallback callback, void *userData)
Definition IR.cpp:1147
MlirOpPrintingFlags mlirOpPrintingFlagsCreate()
Definition IR.cpp:219
bool mlirModuleEqual(MlirModule lhs, MlirModule rhs)
Definition IR.cpp:493
void mlirOpPrintingFlagsElideLargeElementsAttrs(MlirOpPrintingFlags flags, intptr_t largeElementLimit)
Definition IR.cpp:227
void mlirOperationSetSuccessor(MlirOperation op, intptr_t pos, MlirBlock block)
Definition IR.cpp:855
MlirOperation mlirOperationGetNextInBlock(MlirOperation op)
Definition IR.cpp:763
void mlirOpPrintingFlagsEnableDebugInfo(MlirOpPrintingFlags flags, bool enable, bool prettyForm)
Definition IR.cpp:237
MlirOperation mlirModuleGetOperation(MlirModule module)
Definition IR.cpp:485
void mlirOpPrintingFlagsElideLargeResourceString(MlirOpPrintingFlags flags, intptr_t largeResourceLimit)
Definition IR.cpp:232
void mlirOpPrintingFlagsUseLocalScope(MlirOpPrintingFlags flags)
Definition IR.cpp:250
intptr_t mlirBlockArgumentGetArgNumber(MlirValue value)
Definition IR.cpp:1193
MlirBlock mlirOperationGetSuccessor(MlirOperation op, intptr_t pos)
Definition IR.cpp:802
bool mlirAttributeEqual(MlirAttribute a1, MlirAttribute a2)
Definition IR.cpp:1381
MlirAsmState mlirAsmStateCreateForOperation(MlirOperation op, MlirOpPrintingFlags flags)
Definition IR.cpp:174
bool mlirOperationEqual(MlirOperation op, MlirOperation other)
Definition IR.cpp:668
void mlirOpPrintingFlagsAssumeVerified(MlirOpPrintingFlags flags)
Definition IR.cpp:254
void mlirBytecodeWriterConfigDestroy(MlirBytecodeWriterConfig config)
Definition IR.cpp:269
MlirBlock mlirBlockGetSuccessor(MlirBlock block, intptr_t pos)
Definition IR.cpp:1157
void mlirModuleDestroy(MlirModule module)
Definition IR.cpp:479
MlirModule mlirModuleCreateEmpty(MlirLocation location)
Definition IR.cpp:450
void mlirOpPrintingFlagsPrintGenericOpForm(MlirOpPrintingFlags flags)
Definition IR.cpp:242
MlirOperation mlirOperationGetParentOperation(MlirOperation op)
Definition IR.cpp:727
void mlirValueSetType(MlirValue value, MlirType type)
Definition IR.cpp:1221
intptr_t mlirOperationGetNumSuccessors(MlirOperation op)
Definition IR.cpp:798
MlirDialect mlirAttributeGetDialect(MlirAttribute attr)
Definition IR.cpp:1377
void mlirLocationPrint(MlirLocation location, MlirStringCallback callback, void *userData)
Definition IR.cpp:440
void mlirOperationSetAttributeByName(MlirOperation op, MlirStringRef name, MlirAttribute attr)
Definition IR.cpp:874
void mlirOperationSetOperand(MlirOperation op, intptr_t pos, MlirValue newValue)
Definition IR.cpp:779
MlirOperation mlirOpResultGetOwner(MlirValue value)
Definition IR.cpp:1208
MlirModule mlirModuleCreateParse(MlirContext context, MlirStringRef module)
Definition IR.cpp:454
size_t mlirOperationHashValue(MlirOperation op)
Definition IR.cpp:672
void mlirOperationStateAddResults(MlirOperationState *state, intptr_t n, MlirType const *results)
Definition IR.cpp:529
MlirOperation mlirOperationClone(MlirOperation op)
Definition IR.cpp:660
MlirBlock mlirBlockArgumentGetOwner(MlirValue value)
Definition IR.cpp:1189
void mlirBlockArgumentSetLocation(MlirValue value, MlirLocation loc)
Definition IR.cpp:1203
MlirValue mlirOperationGetOperand(MlirOperation op, intptr_t pos)
Definition IR.cpp:771
MlirOpOperand mlirOperationGetOpOperand(MlirOperation op, intptr_t pos)
Definition IR.cpp:775
MlirLocation mlirOperationGetLocation(MlirOperation op)
Definition IR.cpp:705
MlirAttribute mlirOperationGetAttributeByName(MlirOperation op, MlirStringRef name)
Definition IR.cpp:869
MlirTypeID mlirAttributeGetTypeID(MlirAttribute attr)
Definition IR.cpp:1373
void mlirOperationStateAddOwnedRegions(MlirOperationState *state, intptr_t n, MlirRegion const *regions)
Definition IR.cpp:538
void mlirOperationSetLocation(MlirOperation op, MlirLocation loc)
Definition IR.cpp:709
MlirType mlirAttributeGetType(MlirAttribute attribute)
Definition IR.cpp:1366
bool mlirOperationRemoveAttributeByName(MlirOperation op, MlirStringRef name)
Definition IR.cpp:879
bool mlirValueIsAOpResult(MlirValue value)
Definition IR.cpp:1185
MlirBlock mlirBlockGetPredecessor(MlirBlock block, intptr_t pos)
Definition IR.cpp:1166
size_t mlirOperationStructuralHashValue(MlirOperation op, uint32_t flags)
Definition IR.cpp:688
MlirRegion mlirOperationGetRegion(MlirOperation op, intptr_t pos)
Definition IR.cpp:743
MlirOperation mlirOperationCreate(MlirOperationState *state)
Definition IR.cpp:614
bool mlirOperationIsStructurallyEquivalent(MlirOperation lhs, MlirOperation rhs, uint32_t flags)
Definition IR.cpp:682
void mlirBytecodeWriterConfigDesiredEmitVersion(MlirBytecodeWriterConfig flags, int64_t version)
Definition IR.cpp:273
MlirAttribute mlirAttributeParseGet(MlirContext context, MlirStringRef attr)
Definition IR.cpp:1358
void mlirOperationRemoveFromParent(MlirOperation op)
Definition IR.cpp:666
intptr_t mlirBlockGetNumSuccessors(MlirBlock block)
Definition IR.cpp:1153
MlirNamedAttribute mlirOperationGetAttribute(MlirOperation op, intptr_t pos)
Definition IR.cpp:864
void mlirOpPrintingFlagsDestroy(MlirOpPrintingFlags flags)
Definition IR.cpp:223
void mlirValueDump(MlirValue value)
Definition IR.cpp:1225
void mlirTypePrint(MlirType type, MlirStringCallback callback, void *userData)
Definition IR.cpp:1344
MlirBlock mlirModuleGetBody(MlirModule module)
Definition IR.cpp:475
MlirOperation mlirOperationCreateParse(MlirContext context, MlirStringRef sourceStr, MlirStringRef sourceName)
Definition IR.cpp:651
void mlirAsmStateDestroy(MlirAsmState state)
Destroys printing flags created with mlirAsmStateCreate.
Definition IR.cpp:213
MlirContext mlirOperationGetContext(MlirOperation op)
Definition IR.cpp:695
intptr_t mlirOpResultGetResultNumber(MlirValue value)
Definition IR.cpp:1212
void mlirOperationStateAddSuccessors(MlirOperationState *state, intptr_t n, MlirBlock const *successors)
Definition IR.cpp:542
MlirBytecodeWriterConfig mlirBytecodeWriterConfigCreate()
Definition IR.cpp:265
void mlirOpPrintingFlagsPrintNameLocAsPrefix(MlirOpPrintingFlags flags)
Definition IR.cpp:246
void mlirOpPrintingFlagsSkipRegions(MlirOpPrintingFlags flags)
Definition IR.cpp:258
void mlirOperationStateAddOperands(MlirOperationState *state, intptr_t n, MlirValue const *operands)
Definition IR.cpp:534
MlirOperationState mlirOperationStateGet(MlirStringRef name, MlirLocation loc)
Definition IR.cpp:505
intptr_t mlirOperationGetNumOperands(MlirOperation op)
Definition IR.cpp:767
bool mlirOperationIsProperAncestor(MlirOperation a, MlirOperation b)
Definition IR.cpp:735
void mlirTypeDump(MlirType type)
Definition IR.cpp:1349
intptr_t mlirOperationGetNumAttributes(MlirOperation op)
Definition IR.cpp:860
static PyObject * mlirPythonTypeIDToCapsule(MlirTypeID typeID)
Creates a capsule object encapsulating the raw C-API MlirTypeID.
Definition Interop.h:348
static PyObject * mlirPythonContextToCapsule(MlirContext context)
Creates a capsule object encapsulating the raw C-API MlirContext.
Definition Interop.h:216
#define MLIR_PYTHON_MAYBE_DOWNCAST_ATTR
Attribute on MLIR Python objects that expose a function for downcasting the corresponding Python obje...
Definition Interop.h:118
static MlirOperation mlirPythonCapsuleToOperation(PyObject *capsule)
Extracts an MlirOperations from a capsule as produced from mlirPythonOperationToCapsule.
Definition Interop.h:338
#define MLIR_PYTHON_CAPI_PTR_ATTR
Attribute on MLIR Python objects that expose their C-API pointer.
Definition Interop.h:97
static MlirAttribute mlirPythonCapsuleToAttribute(PyObject *capsule)
Extracts an MlirAttribute from a capsule as produced from mlirPythonAttributeToCapsule.
Definition Interop.h:189
static PyObject * mlirPythonTypeToCapsule(MlirType type)
Creates a capsule object encapsulating the raw C-API MlirType.
Definition Interop.h:367
static PyObject * mlirPythonOperationToCapsule(MlirOperation operation)
Creates a capsule object encapsulating the raw C-API MlirOperation.
Definition Interop.h:330
static PyObject * mlirPythonAttributeToCapsule(MlirAttribute attribute)
Creates a capsule object encapsulating the raw C-API MlirAttribute.
Definition Interop.h:180
#define MLIR_PYTHON_CAPI_FACTORY_ATTR
Attribute on MLIR Python objects that exposes a factory function for constructing the corresponding P...
Definition Interop.h:110
static MlirModule mlirPythonCapsuleToModule(PyObject *capsule)
Extracts an MlirModule from a capsule as produced from mlirPythonModuleToCapsule.
Definition Interop.h:282
static MlirContext mlirPythonCapsuleToContext(PyObject *capsule)
Extracts a MlirContext from a capsule as produced from mlirPythonContextToCapsule.
Definition Interop.h:224
static MlirTypeID mlirPythonCapsuleToTypeID(PyObject *capsule)
Extracts an MlirTypeID from a capsule as produced from mlirPythonTypeIDToCapsule.
Definition Interop.h:357
#define MLIR_PYTHON_CAPI_VALUE_CASTER_REGISTER_ATTR
Attribute on main C extension module (_mlir) that corresponds to the value caster registration bindin...
Definition Interop.h:142
static PyObject * mlirPythonBlockToCapsule(MlirBlock block)
Creates a capsule object encapsulating the raw C-API MlirBlock.
Definition Interop.h:198
static PyObject * mlirPythonLocationToCapsule(MlirLocation loc)
Creates a capsule object encapsulating the raw C-API MlirLocation.
Definition Interop.h:255
static MlirDialectRegistry mlirPythonCapsuleToDialectRegistry(PyObject *capsule)
Extracts an MlirDialectRegistry from a capsule as produced from mlirPythonDialectRegistryToCapsule.
Definition Interop.h:245
static MlirType mlirPythonCapsuleToType(PyObject *capsule)
Extracts an MlirType from a capsule as produced from mlirPythonTypeToCapsule.
Definition Interop.h:376
static MlirValue mlirPythonCapsuleToValue(PyObject *capsule)
Extracts an MlirValue from a capsule as produced from mlirPythonValueToCapsule.
Definition Interop.h:454
static PyObject * mlirPythonValueToCapsule(MlirValue value)
Creates a capsule object encapsulating the raw C-API MlirValue.
Definition Interop.h:445
static PyObject * mlirPythonModuleToCapsule(MlirModule module)
Creates a capsule object encapsulating the raw C-API MlirModule.
Definition Interop.h:273
static MlirLocation mlirPythonCapsuleToLocation(PyObject *capsule)
Extracts an MlirLocation from a capsule as produced from mlirPythonLocationToCapsule.
Definition Interop.h:264
#define MLIR_PYTHON_CAPI_TYPE_CASTER_REGISTER_ATTR
Attribute on main C extension module (_mlir) that corresponds to the type caster registration binding...
Definition Interop.h:130
static PyObject * mlirPythonDialectRegistryToCapsule(MlirDialectRegistry registry)
Creates a capsule object encapsulating the raw C-API MlirDialectRegistry.
Definition Interop.h:235
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
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...
Sliceable(intptr_t startIndex, intptr_t length, intptr_t step)
ReferrentTy * get() const
PyMlirContextRef & getContext()
Accesses the context reference.
Definition IRCore.h:351
Used in function arguments when None should resolve to the current context manager set instance.
Definition IRCore.h:332
PyAsmState(MlirValue value, bool useLocalScope)
Definition IRCore.cpp:1767
Wrapper around the generic MlirAttribute.
Definition IRCore.h:1104
PyAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
Definition IRCore.h:1106
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirAttribute.
Definition IRCore.cpp:1877
bool operator==(const PyAttribute &other) const
Definition IRCore.cpp:1873
static PyAttribute createFromCapsule(const nanobind::object &capsule)
Creates a PyAttribute from the MlirAttribute wrapped by a capsule.
Definition IRCore.cpp:1881
nanobind::typed< nanobind::object, PyAttribute > maybeDownCast()
Definition IRCore.cpp:1889
PyBlockArgumentList(PyOperationRef operation, MlirBlock block, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:2223
Python wrapper for MlirBlockArgument.
Definition IRCore.h:1844
nanobind::typed< nanobind::object, PyBlock > dunderNext()
Definition IRCore.cpp:217
Blocks are exposed by the C-API as a forward-only linked list.
Definition IRCore.h:1639
PyBlock appendBlock(const nanobind::args &pyArgTypes, const std::optional< nanobind::sequence > &pyArgLocs)
Definition IRCore.cpp:273
PyBlockPredecessors(PyBlock block, PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:2383
PyBlockSuccessors(PyBlock block, PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:2360
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirBlock.
Definition IRCore.cpp:186
Represents a diagnostic handler attached to the context.
Definition IRCore.h:500
void detach()
Detaches the handler. Does nothing if not attached.
Definition IRCore.cpp:731
PyDiagnosticHandler(MlirContext context, nanobind::object callback)
Definition IRCore.cpp:725
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
Definition IRCore.h:512
Python class mirroring the C MlirDiagnostic struct.
Definition IRCore.h:423
nanobind::typed< nanobind::object, PyLocation > getLocation()
Definition IRCore.cpp:755
nanobind::typed< nanobind::tuple, PyDiagnostic > getNotes()
Definition IRCore.cpp:770
Wrapper around an MlirDialectRegistry.
Definition IRCore.h:592
static PyDialectRegistry createFromCapsule(nanobind::object capsule)
Definition IRCore.cpp:815
User-level object for accessing dialects with dotted syntax such as: ctx.dialect.std.
Definition IRCore.h:568
MlirDialect getDialectForKey(const std::string &key, bool attrError)
Definition IRCore.cpp:798
static bool attach(const nanobind::object &opName, const nanobind::object &target, PyMlirContext &context)
Definition IRCore.cpp:2588
static bool attach(const nanobind::object &opName, PyMlirContext &context)
Definition IRCore.cpp:2688
static bool attach(const nanobind::object &opName, PyMlirContext &context)
Definition IRCore.cpp:2642
static bool attach(const nanobind::object &opName, PyMlirContext &context)
Definition IRCore.cpp:2665
static bool attach(const nanobind::object &opName, PyMlirContext &context)
Definition IRCore.cpp:2713
CurrentLocAction
Policy for composing Location.current with the computed location.
Definition Globals.h:141
OnExplicitAction
Policy for handling explicit loc= when loc_tracebacks() is active.
Definition Globals.h:133
Globals that are always accessible once the extension has been initialized.
Definition Globals.h:29
void registerOpAdaptorImpl(const std::string &operationName, nanobind::object pyClass, bool replace=false)
Adds an operation adaptor class.
Definition Globals.cpp:167
std::optional< nanobind::callable > lookupValueCaster(MlirTypeID mlirTypeID, MlirDialect dialect)
Returns the custom value caster for MlirTypeID mlirTypeID.
Definition Globals.cpp:203
bool loadDialectModule(std::string_view dialectNamespace)
Loads a python module corresponding to the given dialect namespace.
Definition Globals.cpp:64
void registerDialectImpl(const std::string &dialectNamespace, nanobind::object pyClass, bool replace=false)
Adds a concrete implementation dialect class.
Definition Globals.cpp:145
static PyGlobals & get()
Most code should get the globals via this static accessor.
Definition Globals.cpp:59
std::optional< nanobind::object > lookupOperationClass(std::string_view operationName)
Looks up a registered operation class (deriving from OpView) by operation name.
Definition Globals.cpp:233
void registerTypeCaster(MlirTypeID mlirTypeID, nanobind::callable typeCaster, bool replace=false)
Adds a user-friendly type caster.
Definition Globals.cpp:125
void registerOperationImpl(const std::string &operationName, nanobind::object pyClass, bool replace=false)
Adds a concrete implementation operation class.
Definition Globals.cpp:156
void setDialectSearchPrefixes(std::vector< std::string > newValues)
Definition Globals.h:43
std::optional< nanobind::callable > lookupTypeCaster(MlirTypeID mlirTypeID, MlirDialect dialect)
Returns the custom type caster for MlirTypeID mlirTypeID.
Definition Globals.cpp:189
void registerValueCaster(MlirTypeID mlirTypeID, nanobind::callable valueCaster, bool replace=false)
Adds a user-friendly value caster.
Definition Globals.cpp:135
std::optional< nanobind::callable > lookupAttributeBuilder(const std::string &attributeKind)
Returns the custom Attribute builder for Attribute kind.
Definition Globals.cpp:179
std::optional< nanobind::object > lookupDialectClass(const std::string &dialectNamespace)
Looks up a registered dialect class by namespace.
Definition Globals.cpp:218
std::vector< std::string > getDialectSearchPrefixes()
Get and set the list of parent modules to search for dialect implementation classes.
Definition Globals.h:39
void registerAttributeBuilder(const std::string &attributeKind, nanobind::callable pyFunc, bool replace=false, bool allow_existing=false)
Adds a user-friendly Attribute builder.
Definition Globals.cpp:99
An insertion point maintains a pointer to a Block and a reference operation.
Definition IRCore.h:935
void insert(PyOperationBase &operationBase)
Inserts an operation.
Definition IRCore.cpp:1798
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
Definition IRCore.cpp:1863
static PyInsertionPoint atBlockTerminator(PyBlock &block)
Shortcut to create an insertion point before the block terminator.
Definition IRCore.cpp:1837
static PyInsertionPoint after(PyOperationBase &op)
Shortcut to create an insertion point to the node after the specified operation.
Definition IRCore.cpp:1846
static PyInsertionPoint atBlockBegin(PyBlock &block)
Shortcut to create an insertion point at the beginning of the block.
Definition IRCore.cpp:1824
PyInsertionPoint(const PyBlock &block)
Creates an insertion point positioned after the last operation in the block, but still inside the blo...
Definition IRCore.cpp:1789
static nanobind::object contextEnter(nanobind::object insertionPoint)
Enter and exit the context manager.
Definition IRCore.cpp:1859
static nanobind::object contextEnter(nanobind::object location)
Enter and exit the context manager.
Definition IRCore.cpp:839
static PyLocation createFromCapsule(nanobind::object capsule)
Creates a PyLocation from the MlirLocation wrapped by a capsule.
Definition IRCore.cpp:831
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirLocation.
Definition IRCore.cpp:827
nanobind::typed< nanobind::object, PyLocation > maybeDownCast()
Returns the most-derived Location subclass registered for this TypeID, or self.
Definition IRCore.cpp:1907
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
Definition IRCore.cpp:843
PyLocation(PyMlirContextRef contextRef, MlirLocation loc)
Definition IRCore.h:360
static PyMlirContextRef forContext(MlirContext context)
Returns a context reference for the singleton PyMlirContext wrapper for the given context.
Definition IRCore.cpp:461
static size_t getLiveCount()
Gets the count of live context objects. Used for testing.
Definition IRCore.cpp:486
static nanobind::object createFromCapsule(nanobind::object capsule)
Creates a PyMlirContext from the MlirContext wrapped by a capsule.
Definition IRCore.cpp:454
bool getRemarksEnabled()
Whether a remark engine is enabled on the context.
void enableRemarks(PyRemarkPolicy policy, const std::optional< std::string > &outputFile, PyRemarkFormat format, const std::string &allFilter, const std::string &passedFilter, const std::string &missedFilter, const std::string &analysisFilter, const std::string &failedFilter, nanobind::object callback, std::optional< bool > printAsEmitRemarks)
Enables the optimization remark engine of the context, streaming to outputFile, to callback,...
Definition IRRemarks.cpp:65
nanobind::object attachDiagnosticHandler(nanobind::object callback)
Attaches a Python callback as a diagnostic handler, returning a registration object (internally a PyD...
Definition IRCore.cpp:501
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
Definition IRCore.cpp:495
MlirContext get()
Accesses the underlying MlirContext.
Definition IRCore.h:245
PyMlirContextRef getRef()
Gets a strong reference to this context, which will ensure it is kept alive for the life of the refer...
Definition IRCore.cpp:446
void setEmitErrorDiagnostics(bool value)
Controls whether error diagnostics should be propagated to diagnostic handlers, instead of being capt...
Definition IRCore.h:299
static nanobind::object contextEnter(nanobind::object context)
Enter and exit the context manager.
Definition IRCore.cpp:491
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirContext.
Definition IRCore.cpp:450
void finalizeRemarks()
Finalizes and removes the remark engine; no-op when none is enabled.
size_t getLiveModuleCount()
Gets the count of live modules associated with this context.
Definition IRCore.cpp:1857
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirModule.
Definition IRCore.cpp:908
MlirModule get()
Gets the backing MlirModule.
Definition IRCore.h:642
static PyModuleRef forModule(MlirModule module)
Returns a PyModule reference for the given MlirModule.
Definition IRCore.cpp:876
static nanobind::object createFromCapsule(nanobind::object capsule)
Creates a PyModule from the MlirModule wrapped by a capsule.
Definition IRCore.cpp:901
Represents a Python MlirNamedAttr, carrying an optional owned name.
Definition IRCore.h:1130
PyNamedAttribute(MlirAttribute attr, std::string ownedName)
Constructs a PyNamedAttr that retains an owned name.
Definition IRCore.cpp:1924
Template for a reference to a concrete type which captures a python reference to its underlying pytho...
Definition IRCore.h:67
nanobind::object releaseObject()
Releases the object held by this instance, returning it.
Definition IRCore.h:105
void dunderSetItem(const std::string &name, const PyAttribute &attr)
Definition IRCore.cpp:2443
nanobind::typed< nanobind::object, PyAttribute > dunderGetItemNamed(const std::string &name)
Definition IRCore.cpp:2410
nanobind::typed< nanobind::object, std::optional< PyAttribute > > get(const std::string &key, nanobind::object defaultValue)
Definition IRCore.cpp:2420
static void forEachAttr(MlirOperation op, std::function< void(MlirStringRef, MlirAttribute)> fn)
Definition IRCore.cpp:2465
PyNamedAttribute dunderGetItemIndexed(intptr_t index)
Definition IRCore.cpp:2428
nanobind::typed< nanobind::object, PyOpOperand > dunderNext()
Definition IRCore.cpp:382
PyOpOperandList(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:2255
void dunderSetItem(intptr_t index, PyValue value)
Definition IRCore.cpp:2263
nanobind::typed< nanobind::object, PyOpView > getOwner() const
Definition IRCore.cpp:363
PyOpOperands(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:2298
Sliceable< PyOpOperandList, PyOpOperand > SliceableT
Definition IRCore.cpp:2296
PyOpResultList(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:1417
PyOpSuccessors(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:2327
void dunderSetItem(intptr_t index, PyBlock block)
Definition IRCore.cpp:2335
A PyOpView is equivalent to the C++ "Op" wrappers: these are the basis for providing more instance-sp...
Definition IRCore.h:837
PyOpView(const nanobind::object &operationObject)
Definition IRCore.cpp:1757
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)
Definition IRCore.cpp:1580
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.
Definition IRCore.cpp:1749
Base class for PyOperation and PyOpView which exposes the primary, user visible methods for manipulat...
Definition IRCore.h:672
bool isBeforeInBlock(PyOperationBase &other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
Definition IRCore.cpp:1165
bool isProperAncestor(PyOperationBase &other)
Return whether the current operation is a proper ancestor of 'other', i.e., whether it contains 'othe...
Definition IRCore.cpp:1181
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)
Definition IRCore.cpp:1119
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.
Definition IRCore.cpp:1018
void writeBytecode(const nanobind::object &fileObject, std::optional< int64_t > bytecodeVersion)
Definition IRCore.cpp:1066
bool isAncestor(PyOperationBase &other)
Return whether the current operation is an ancestor of 'other', i.e., whether it contains 'other' or ...
Definition IRCore.cpp:1173
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.
Definition IRCore.cpp:1147
void walk(std::function< PyWalkResult(MlirOperation)> callback, PyWalkOrder walkOrder)
Definition IRCore.cpp:1087
nanobind::typed< nanobind::object, PyOpView > dunderNext()
Definition IRCore.cpp:294
Operations are exposed by the C-API as a forward-only linked list.
Definition IRCore.h:1680
nanobind::typed< nanobind::object, PyOpView > dunderGetItem(intptr_t index)
Definition IRCore.cpp:333
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.
Definition IRCore.cpp:1245
void setInvalid()
Invalidate the operation.
Definition IRCore.h:804
PyOperation & getOperation() override
Each must provide access to the raw Operation.
Definition IRCore.h:737
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.
Definition IRCore.cpp:975
nanobind::object clone(const nanobind::object &ip)
Clones this operation.
Definition IRCore.cpp:1360
static nanobind::object createFromCapsule(const nanobind::object &capsule)
Creates a PyOperation from the MlirOperation wrapped by a capsule.
Definition IRCore.cpp:1221
std::optional< PyOperationRef > getParentOperation()
Gets the parent operation or raises an exception if the operation has no parent.
Definition IRCore.cpp:1197
nanobind::object createOpView()
Creates an OpView suitable for this operation.
Definition IRCore.cpp:1369
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirOperation.
Definition IRCore.cpp:1216
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.
Definition IRCore.cpp:959
void detachFromParent()
Detaches the operation from its parent block and updates its state accordingly.
Definition IRCore.cpp:987
void erase()
Erases the underlying MlirOperation, removes its pointer from the parent context's live operations ma...
Definition IRCore.cpp:1380
PyBlock getBlock()
Gets the owning block or raises an exception if the operation has no owning block.
Definition IRCore.cpp:1207
static PyOperationRef createDetached(PyMlirContextRef contextRef, MlirOperation operation, nanobind::object parentKeepAlive=nanobind::object())
Creates a detached operation.
Definition IRCore.cpp:966
PyOperation(PyMlirContextRef contextRef, MlirOperation operation)
Definition IRCore.cpp:916
void setAttached(const nanobind::object &parent=nanobind::object())
Definition IRCore.cpp:1002
Regions of an op are fixed length and indexed numerically so are represented with a sequence-like con...
Definition IRCore.h:1600
PyRegionList(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:194
PyStringAttribute insert(PyOperationBase &symbol)
Inserts the given operation into the symbol table.
Definition IRCore.cpp:2076
PySymbolTable(PyOperationBase &operation)
Constructs a symbol table for the given operation.
Definition IRCore.cpp:2040
static PyStringAttribute getVisibility(PyOperationBase &symbol)
Gets and sets the visibility of a symbol op.
Definition IRCore.cpp:2116
void erase(PyOperationBase &symbol)
Removes the given operation from the symbol table and erases it.
Definition IRCore.cpp:2061
static void walkSymbolTables(PyOperationBase &from, bool allSymUsesVisible, nanobind::object callback)
Walks all symbol tables under and including 'from'.
Definition IRCore.cpp:2157
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.
Definition IRCore.cpp:2048
static void replaceAllSymbolUses(const std::string &oldSymbol, const std::string &newSymbol, PyOperationBase &from)
Replaces all symbol uses within an operation.
Definition IRCore.cpp:2145
static PyStringAttribute getSymbolName(PyOperationBase &symbol)
Gets and sets the name of a symbol op.
Definition IRCore.cpp:2088
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 ...
Definition IRCore.cpp:2071
static void setSymbolName(PyOperationBase &symbol, const std::string &name)
Definition IRCore.cpp:2101
static void setVisibility(PyOperationBase &symbol, const std::string &visibility)
Definition IRCore.cpp:2127
Tracks an entry in the thread context stack.
Definition IRCore.h:138
static PyInsertionPoint * getDefaultInsertionPoint()
Gets the top of stack insertion point and return nullptr if not defined.
Definition IRCore.cpp:641
static nanobind::object pushInsertionPoint(nanobind::object insertionPoint)
Definition IRCore.cpp:669
static void popInsertionPoint(PyInsertionPoint &insertionPoint)
Definition IRCore.cpp:681
static PyLocation * getDefaultLocation()
Gets the top of stack location and returns nullptr if not defined.
Definition IRCore.cpp:646
static PyThreadContextEntry * getTopOfStack()
Stack management.
Definition IRCore.cpp:589
static nanobind::object pushLocation(nanobind::object location)
Definition IRCore.cpp:692
static nanobind::object pushContext(nanobind::object context)
Definition IRCore.cpp:651
static PyMlirContext * getDefaultContext()
Gets the top of stack context and return nullptr if not defined.
Definition IRCore.cpp:636
static std::vector< PyThreadContextEntry > & getStack()
Gets the thread local stack.
Definition IRCore.cpp:584
Wrapper around MlirLlvmThreadPool Python object owns the C++ thread pool.
Definition IRCore.h:194
A TypeID provides an efficient and unique identifier for a specific C++ type.
Definition IRCore.h:1003
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirTypeID.
Definition IRCore.cpp:1970
bool operator==(const PyTypeID &other) const
Definition IRCore.cpp:1980
static PyTypeID createFromCapsule(nanobind::object capsule)
Creates a PyTypeID from the MlirTypeID wrapped by a capsule.
Definition IRCore.cpp:1974
Wrapper around the generic MlirType.
Definition IRCore.h:977
PyType(PyMlirContextRef contextRef, MlirType type)
Definition IRCore.h:979
bool operator==(const PyType &other) const
Definition IRCore.cpp:1936
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirType.
Definition IRCore.cpp:1940
static PyType createFromCapsule(nanobind::object capsule)
Creates a PyType from the MlirType wrapped by a capsule.
Definition IRCore.cpp:1944
nanobind::typed< nanobind::object, PyType > maybeDownCast()
Definition IRCore.cpp:1952
nanobind::object getCapsule()
Gets a capsule wrapping the void* within the MlirValue.
Definition IRCore.cpp:1988
PyValue(PyOperationRef parentOperation, MlirValue value)
Definition IRCore.h:1396
nanobind::typed< nanobind::object, std::variant< PyBlockArgument, PyOpResult, PyValue > > maybeDownCast()
Definition IRCore.cpp:2007
static PyValue createFromCapsule(nanobind::object capsule)
Creates a PyValue from the MlirValue wrapped by a capsule.
Definition IRCore.cpp:2028
MLIR_CAPI_EXPORTED void mlirEmitWarning(MlirLocation location, const char *message)
Emits a warning at the given location through the diagnostics engine.
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
Definition Diagnostics.h:29
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.
Definition Diagnostics.h:41
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 MlirDynamicOpTrait mlirDynamicOpTraitIsIsolatedFromAboveCreate(void)
Get the dynamic op trait that indicates regions are isolated from above.
MLIR_CAPI_EXPORTED MlirTypeID mlirDynamicOpTraitRecursiveMemoryEffectsGetTypeID(void)
Get the type ID of the dynamic op trait that indicates memory effects of an operation includes the ef...
MLIR_CAPI_EXPORTED MlirTypeID mlirDynamicOpTraitIsIsolatedFromAboveGetTypeID(void)
Get the type ID of the dynamic op trait that indicates regions are isolated from above.
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 mlirDynamicOpTraitRecursiveMemoryEffectsCreate(void)
Get the dynamic op trait that indicates memory effects of an operation includes the effects of operat...
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.
Definition IR.cpp:282
MlirWalkResult(* MlirOperationWalkCallback)(MlirOperation, void *userData)
Operation walker type.
Definition IR.h:935
MLIR_CAPI_EXPORTED MlirLocation mlirValueGetLocation(MlirValue v)
Gets the location of the value.
Definition IR.cpp:1281
MLIR_CAPI_EXPORTED unsigned mlirContextGetNumThreads(MlirContext context)
Gets the number of threads of the thread pool of the context when multithreading is enabled.
Definition IR.cpp:122
MLIR_CAPI_EXPORTED void mlirOperationWriteBytecode(MlirOperation op, MlirStringCallback callback, void *userData)
Same as mlirOperationPrint but writing the bytecode format.
Definition IR.cpp:904
MLIR_CAPI_EXPORTED MlirLocation mlirLocationFileLineColGet(MlirContext context, MlirStringRef filename, unsigned line, unsigned col)
Creates an File/Line/Column location owned by the given context.
Definition IR.cpp:290
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.
Definition IR.cpp:1469
MLIR_CAPI_EXPORTED MlirStringRef mlirDialectGetNamespace(MlirDialect dialect)
Returns the namespace of the given dialect.
Definition IR.cpp:154
MLIR_CAPI_EXPORTED int mlirLocationFileLineColRangeGetEndColumn(MlirLocation location)
Getter for end_column of FileLineColRange.
Definition IR.cpp:328
MLIR_CAPI_EXPORTED MlirAttribute mlirSymbolTableInsert(MlirSymbolTable symbolTable, MlirOperation operation)
Inserts the given operation into the given symbol table.
Definition IR.cpp:1448
MLIR_CAPI_EXPORTED MlirStringRef mlirSymbolTableGetDefaultVisibilityAttributeName(void)
Returns the name of the attribute used by default to store symbol visibility.
Definition IR.cpp:1429
MlirWalkOrder
Traversal order for operation walk.
Definition IR.h:928
MLIR_CAPI_EXPORTED MlirNamedAttribute mlirNamedAttributeGet(MlirIdentifier name, MlirAttribute attr)
Associates an attribute with the name. Takes ownership of neither.
Definition IR.cpp:1396
MLIR_CAPI_EXPORTED MlirLocation mlirLocationNameGetChildLoc(MlirLocation location)
Getter for childLoc of Name.
Definition IR.cpp:409
MLIR_CAPI_EXPORTED void mlirSymbolTableErase(MlirSymbolTable symbolTable, MlirOperation operation)
Removes the given operation from the symbol table and erases it.
Definition IR.cpp:1453
MLIR_CAPI_EXPORTED void mlirContextAppendDialectRegistry(MlirContext ctx, MlirDialectRegistry registry)
Append the contents of the given dialect registry to the registry associated with the context.
Definition IR.cpp:84
MLIR_CAPI_EXPORTED MlirStringRef mlirIdentifierStr(MlirIdentifier ident)
Gets the string value of the identifier.
Definition IR.cpp:1417
MLIR_CAPI_EXPORTED MlirType mlirTypeParseGet(MlirContext context, MlirStringRef type)
Parses a type. The type is owned by the context.
Definition IR.cpp:1324
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...
Definition IR.cpp:1307
MLIR_CAPI_EXPORTED void mlirContextSetAllowUnregisteredDialects(MlirContext context, bool allow)
Sets whether unregistered dialects are allowed in this context.
Definition IR.cpp:73
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 ...
Definition IR.cpp:1017
MLIR_CAPI_EXPORTED void mlirContextBeginTransientScope(MlirContext context)
Begins a transient scope on the context, freezing the base layer (loaded dialects,...
Definition IR.cpp:130
MLIR_CAPI_EXPORTED unsigned mlirLocationFusedGetNumLocations(MlirLocation location)
Getter for number of locations fused together.
Definition IR.cpp:372
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...
Definition IR.cpp:1253
MLIR_CAPI_EXPORTED void mlirValuePrintAsOperand(MlirValue value, MlirAsmState state, MlirStringCallback callback, void *userData)
Prints a value as an operand (i.e., the ValueID).
Definition IR.cpp:1236
MLIR_CAPI_EXPORTED MlirLocation mlirLocationUnknownGet(MlirContext context)
Creates a location with unknown position owned by the given context.
Definition IR.cpp:420
MLIR_CAPI_EXPORTED MlirOperation mlirOpOperandGetOwner(MlirOpOperand opOperand)
Returns the owner operation of an op operand.
Definition IR.cpp:1295
MLIR_CAPI_EXPORTED MlirIdentifier mlirLocationFileLineColRangeGetFilename(MlirLocation location)
Getter for filename of FileLineColRange.
Definition IR.cpp:306
MLIR_CAPI_EXPORTED void mlirLocationFusedGetLocations(MlirLocation location, MlirLocation *locationsCPtr)
Getter for locations of Fused.
Definition IR.cpp:378
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`...
Definition IR.cpp:1385
MLIR_CAPI_EXPORTED MlirRegion mlirBlockGetParentRegion(MlirBlock block)
Returns the region that contains this block.
Definition IR.cpp:1056
MLIR_CAPI_EXPORTED void mlirOperationMoveBefore(MlirOperation op, MlirOperation other)
Moves the given operation immediately before the other operation in its parent block.
Definition IR.cpp:931
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 '...
Definition IR.cpp:1257
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 ...
Definition IR.cpp:895
MlirWalkResult
Operation walk result.
Definition IR.h:921
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.
Definition IR.cpp:997
static bool mlirTypeIsNull(MlirType type)
Checks whether a type is null.
Definition IR.h:1255
MLIR_CAPI_EXPORTED bool mlirContextIsRegisteredOperation(MlirContext context, MlirStringRef name)
Returns whether the given fully-qualified operation (i.e.
Definition IR.cpp:105
MLIR_CAPI_EXPORTED intptr_t mlirBlockGetNumArguments(MlirBlock block)
Returns the number of arguments of the block.
Definition IR.cpp:1125
MLIR_CAPI_EXPORTED int mlirLocationFileLineColRangeGetStartLine(MlirLocation location)
Getter for start_line of FileLineColRange.
Definition IR.cpp:310
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.
Definition IR.cpp:364
MLIR_CAPI_EXPORTED MlirDialect mlirContextGetLoadedDialect(MlirContext context, MlirStringRef name)
Gets the dialect instance owned by the given context using the dialect namespace to identify it.
Definition IR.cpp:100
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...
Definition IR.cpp:1106
static bool mlirContextIsNull(MlirContext context)
Checks whether a context is null.
Definition IR.h:105
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,...
Definition IR.cpp:95
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...
Definition IR.cpp:1003
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.
Definition IR.cpp:1040
static bool mlirBlockIsNull(MlirBlock block)
Checks whether a block is null.
Definition IR.h:1021
MLIR_CAPI_EXPORTED void mlirBlockAppendOwnedOperation(MlirBlock block, MlirOperation operation)
Takes an operation owned by the caller and appends it to the block.
Definition IR.cpp:1081
MLIR_CAPI_EXPORTED MlirValue mlirBlockGetArgument(MlirBlock block, intptr_t pos)
Returns pos-th argument of the block.
Definition IR.cpp:1143
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...
Definition IR.cpp:1443
MLIR_CAPI_EXPORTED MlirContext mlirTypeGetContext(MlirType type)
Gets the context that a type was created with.
Definition IR.cpp:1328
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.
Definition IR.cpp:298
MLIR_CAPI_EXPORTED bool mlirOpOperandIsNull(MlirOpOperand opOperand)
Returns whether the op operand is null.
Definition IR.cpp:1293
MLIR_CAPI_EXPORTED MlirSymbolTable mlirSymbolTableCreate(MlirOperation operation)
Creates a symbol table for the given operation.
Definition IR.cpp:1433
MLIR_CAPI_EXPORTED bool mlirLocationEqual(MlirLocation l1, MlirLocation l2)
Checks if two locations are equal.
Definition IR.cpp:432
MLIR_CAPI_EXPORTED int mlirLocationFileLineColRangeGetStartColumn(MlirLocation location)
Getter for start_column of FileLineColRange.
Definition IR.cpp:316
MLIR_CAPI_EXPORTED bool mlirContextIsInTransientScope(MlirContext context)
Returns whether the context is currently in a transient scope.
Definition IR.cpp:138
MLIR_CAPI_EXPORTED bool mlirLocationIsAFused(MlirLocation location)
Checks whether the given location is an Fused.
Definition IR.cpp:392
static bool mlirLocationIsNull(MlirLocation location)
Checks if the location is null.
Definition IR.h:398
MLIR_CAPI_EXPORTED MlirValue mlirBlockAddArgument(MlirBlock block, MlirType type, MlirLocation loc)
Appends an argument of the specified type to the block.
Definition IR.cpp:1129
MLIR_CAPI_EXPORTED void mlirOperationPrintWithFlags(MlirOperation op, MlirOpPrintingFlags flags, MlirStringCallback callback, void *userData)
Same as mlirOperationPrint but accepts flags controlling the printing behavior.
Definition IR.cpp:889
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...
Definition IR.cpp:1243
MLIR_CAPI_EXPORTED void mlirContextEndTransientScope(MlirContext context)
Ends the transient scope and resets the context to the base state, pruning transient types,...
Definition IR.cpp:134
MLIR_CAPI_EXPORTED void mlirContextSetThreadPool(MlirContext context, MlirLlvmThreadPool threadPool)
Sets the thread pool of the context explicitly, enabling multithreading in the process.
Definition IR.cpp:117
MLIR_CAPI_EXPORTED bool mlirOperationVerify(MlirOperation op)
Verify the operation and return true if it passes, false if it fails.
Definition IR.cpp:923
MLIR_CAPI_EXPORTED bool mlirTypeEqual(MlirType t1, MlirType t2)
Checks if two types are equal.
Definition IR.cpp:1340
MLIR_CAPI_EXPORTED unsigned mlirOpOperandGetOperandNumber(MlirOpOperand opOperand)
Returns the operand number of an op operand.
Definition IR.cpp:1303
MLIR_CAPI_EXPORTED MlirLocation mlirLocationCallSiteGetCaller(MlirLocation location)
Getter for caller of CallSite.
Definition IR.cpp:351
MLIR_CAPI_EXPORTED MlirOperation mlirBlockGetTerminator(MlirBlock block)
Returns the terminator operation in the block or null if no terminator.
Definition IR.cpp:1071
MLIR_CAPI_EXPORTED MlirIdentifier mlirLocationNameGetName(MlirLocation location)
Getter for name of Name.
Definition IR.cpp:405
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...
Definition IR.cpp:935
MLIR_CAPI_EXPORTED MlirLocation mlirLocationFromAttribute(MlirAttribute attribute)
Creates a location from a location attribute.
Definition IR.cpp:286
MLIR_CAPI_EXPORTED MlirTypeID mlirTypeGetTypeID(MlirType type)
Gets the type ID of the type.
Definition IR.cpp:1332
static bool mlirDialectIsNull(MlirDialect dialect)
Checks if the dialect is null.
Definition IR.h:204
MLIR_CAPI_EXPORTED MlirAttribute mlirLocationFusedGetMetadata(MlirLocation location)
Getter for metadata of Fused.
Definition IR.cpp:386
MLIR_CAPI_EXPORTED MlirBlock mlirBlockGetNextInRegion(MlirBlock block)
Returns the block immediately following the given block in its parent region.
Definition IR.cpp:1060
MLIR_CAPI_EXPORTED MlirLocation mlirLocationCallSiteGet(MlirLocation callee, MlirLocation caller)
Creates a call site location with a callee and a caller.
Definition IR.cpp:342
MLIR_CAPI_EXPORTED bool mlirLocationIsAName(MlirLocation location)
Checks whether the given location is an Name.
Definition IR.cpp:416
static bool mlirDialectRegistryIsNull(MlirDialectRegistry registry)
Checks if the dialect registry is null.
Definition IR.h:266
MLIR_CAPI_EXPORTED void mlirOperationWalk(MlirOperation op, MlirOperationWalkCallback callback, void *userData, MlirWalkOrder walkOrder)
Walks operation op in walkOrder and calls callback on that operation.
Definition IR.cpp:953
MLIR_CAPI_EXPORTED MlirContext mlirContextCreateWithThreading(bool threadingEnabled)
Creates an MLIR context with an explicit setting of the multithreading setting and transfers its owne...
Definition IR.cpp:55
MLIR_CAPI_EXPORTED MlirOperation mlirBlockGetParentOperation(MlirBlock)
Returns the closest surrounding operation that contains this block.
Definition IR.cpp:1052
MLIR_CAPI_EXPORTED MlirContext mlirLocationGetContext(MlirLocation location)
Gets the context that a location was created with.
Definition IR.cpp:436
MLIR_CAPI_EXPORTED void mlirBlockEraseArgument(MlirBlock block, unsigned index)
Erase the argument at 'index' and remove it from the argument list.
Definition IR.cpp:1134
MLIR_CAPI_EXPORTED void mlirAttributeDump(MlirAttribute attr)
Prints the attribute to the standard error stream.
Definition IR.cpp:1391
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...
Definition IR.cpp:1458
MLIR_CAPI_EXPORTED void mlirRegionAppendOwnedBlock(MlirRegion region, MlirBlock block)
Takes a block owned by the caller and appends it to the given region.
Definition IR.cpp:993
MLIR_CAPI_EXPORTED MlirOperation mlirBlockGetFirstOperation(MlirBlock block)
Returns the first operation in the block.
Definition IR.cpp:1064
static bool mlirRegionIsNull(MlirRegion region)
Checks whether a region is null.
Definition IR.h:960
MLIR_CAPI_EXPORTED MlirDialect mlirTypeGetDialect(MlirType type)
Gets the dialect a type belongs to.
Definition IR.cpp:1336
MLIR_CAPI_EXPORTED MlirIdentifier mlirIdentifierGet(MlirContext context, MlirStringRef str)
Gets an identifier with the given string value.
Definition IR.cpp:1405
MLIR_CAPI_EXPORTED void mlirContextLoadAllAvailableDialects(MlirContext context)
Eagerly loads all available dialects registered with a context, making them available for use for IR ...
Definition IR.cpp:113
MLIR_CAPI_EXPORTED MlirLlvmThreadPool mlirContextGetThreadPool(MlirContext context)
Gets the thread pool of the context when enabled multithreading, otherwise an assertion is raised.
Definition IR.cpp:126
MLIR_CAPI_EXPORTED int mlirLocationFileLineColRangeGetEndLine(MlirLocation location)
Getter for end_line of FileLineColRange.
Definition IR.cpp:322
MLIR_CAPI_EXPORTED MlirLocation mlirLocationNameGet(MlirContext context, MlirStringRef name, MlirLocation childLoc)
Creates a name location owned by the given context.
Definition IR.cpp:396
MLIR_CAPI_EXPORTED void mlirContextEnableMultithreading(MlirContext context, bool enable)
Set threading mode (must be set to false to mlir-print-ir-after-all).
Definition IR.cpp:109
MLIR_CAPI_EXPORTED MlirLocation mlirLocationCallSiteGetCallee(MlirLocation location)
Getter for callee of CallSite.
Definition IR.cpp:346
MLIR_CAPI_EXPORTED MlirContext mlirValueGetContext(MlirValue v)
Gets the context that a value was created with.
Definition IR.cpp:1285
MLIR_CAPI_EXPORTED MlirStringRef mlirSymbolTableGetSymbolAttributeName(void)
Returns the name of the attribute used to store symbol names compatible with symbol tables.
Definition IR.cpp:1425
MLIR_CAPI_EXPORTED MlirRegion mlirRegionCreate(void)
Creates a new empty region and transfers ownership to the caller.
Definition IR.cpp:980
MLIR_CAPI_EXPORTED void mlirBlockDetach(MlirBlock block)
Detach a block from the owning region and assume ownership.
Definition IR.cpp:1120
MLIR_CAPI_EXPORTED void mlirOperationDump(MlirOperation op)
Prints an operation to stderr.
Definition IR.cpp:918
static bool mlirSymbolTableIsNull(MlirSymbolTable symbolTable)
Returns true if the symbol table is null.
Definition IR.h:1346
MLIR_CAPI_EXPORTED bool mlirContextGetAllowUnregisteredDialects(MlirContext context)
Returns whether the context allows unregistered dialects.
Definition IR.cpp:77
MLIR_CAPI_EXPORTED void mlirOperationReplaceUsesOfWith(MlirOperation op, MlirValue of, MlirValue with)
Replace uses of 'of' value with the 'with' value inside the 'op' operation.
Definition IR.cpp:971
MLIR_CAPI_EXPORTED void mlirOperationMoveAfter(MlirOperation op, MlirOperation other)
Moves the given operation immediately after the other operation in its parent block.
Definition IR.cpp:927
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`.
Definition IR.cpp:1230
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...
Definition IR.cpp:911
MLIR_CAPI_EXPORTED void mlirContextDestroy(MlirContext context)
Takes an MLIR context owned by the caller and destroys it.
Definition IR.cpp:71
MLIR_CAPI_EXPORTED MlirBlock mlirRegionGetFirstBlock(MlirRegion region)
Gets the first block in the region.
Definition IR.cpp:986
MLIR_CAPI_EXPORTED bool mlirEmitOptimizationRemark(MlirLocation location, MlirRemarkKind kind, MlirStringRef remarkName, MlirStringRef categoryName, MlirStringRef subCategoryName, MlirStringRef functionName, MlirStringRef message, intptr_t numArgs, const MlirStringRef *argKeys, const MlirStringRef *argValues)
Emits a remark of kind at location through the remark engine of the location's context.
Definition Remarks.cpp:228
MlirRemarkKind
The outcome a remark describes (see mlir::remark::RemarkKind).
Definition Remarks.h:38
static MlirStringRef mlirStringRefCreate(const char *str, size_t length)
Constructs a string reference from the pointer and length.
Definition Support.h:87
static MlirLogicalResult mlirLogicalResultFailure(void)
Creates a logical result representing a failure.
Definition Support.h:143
struct MlirLogicalResult MlirLogicalResult
Definition Support.h:124
MLIR_CAPI_EXPORTED int mlirLlvmThreadPoolGetMaxConcurrency(MlirLlvmThreadPool pool)
Returns the maximum number of threads in the thread pool.
Definition Support.cpp:38
MLIR_CAPI_EXPORTED void mlirLlvmThreadPoolDestroy(MlirLlvmThreadPool pool)
Destroy an LLVM thread pool.
Definition Support.cpp:34
MLIR_CAPI_EXPORTED MlirLlvmThreadPool mlirLlvmThreadPoolCreate(void)
Create an LLVM thread pool.
Definition Support.cpp:30
MLIR_CAPI_EXPORTED size_t mlirTypeIDHashValue(MlirTypeID typeID)
Returns the hash value of the type id.
Definition Support.cpp:93
static MlirLogicalResult mlirLogicalResultSuccess(void)
Creates a logical result representing a success.
Definition Support.h:137
struct MlirStringRef MlirStringRef
Definition Support.h:82
static bool mlirLogicalResultIsFailure(MlirLogicalResult res)
Checks if the given logical result represents a failure.
Definition Support.h:132
static bool mlirTypeIDIsNull(MlirTypeID typeID)
Checks whether a type id is null.
Definition Support.h:201
MLIR_CAPI_EXPORTED bool mlirTypeIDEqual(MlirTypeID typeID1, MlirTypeID typeID2)
Checks if two type ids are equal.
Definition Support.cpp:89
void walk(Operation *op, function_ref< void(Region *)> callback, WalkOrder order)
Walk all of the regions, blocks, or operations nested under (and including) the given operation.
Definition Visitors.h:102
InFlightDiagnostic & next(InFlightDiagnostic &diag)
Starts a new message part in an in-flight diagnostic.
MLIR_PYTHON_API_EXPORTED MlirValue getUniqueResult(MlirOperation operation)
Definition IRCore.cpp:1546
static std::string formatMLIRError(const MLIRError &e)
Definition IRCore.cpp:2901
PyOperationEquivalenceFlags
Flags controlling structural operation equivalence and hashing.
Definition IRCore.h:411
MLIR_PYTHON_API_EXPORTED void populateRoot(nanobind::module_ &m)
static void maybeInsertOperation(PyOperationRef &op, const nb::object &maybeIp)
Definition IRCore.cpp:1230
static void populateResultTypes(std::string_view name, nb::sequence resultTypeList, const nb::object &resultSegmentSpecObj, std::vector< int32_t > &resultSegmentLengths, std::vector< PyType * > &resultTypes)
Definition IRCore.cpp:1459
PyObjectRef< PyMlirContext > PyMlirContextRef
Wrapper around MlirContext.
Definition IRCore.h:231
static MlirValue getOpResultOrValue(nb::handle operand)
Definition IRCore.cpp:1561
PyObjectRef< PyOperation > PyOperationRef
Definition IRCore.h:732
MlirStringRef toMlirStringRef(const std::string &s)
Definition IRCore.h:1563
PyRemarkKind
The kinds, emitting policies and file formats of the remark engine (mlir-c/Remarks....
Definition IRCore.h:212
static bool attachOpTrait(const nb::object &opName, MlirDynamicOpTrait trait, PyMlirContext &context)
Definition IRCore.cpp:2573
PyObjectRef< PyModule > PyModuleRef
Definition IRCore.h:631
static MlirLogicalResult verifyTraitByMethod(MlirOperation op, void *userData, const char *methodName)
Definition IRCore.cpp:2562
static PyOperationRef getValueOwnerRef(MlirValue value)
Definition IRCore.cpp:1992
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.
Definition IRCore.cpp:1406
PyWalkOrder
Traversal order for operation walk.
Definition IRCore.h:404
MLIR_PYTHON_API_EXPORTED void populateIRCore(nanobind::module_ &m)
nanobind::object classmethod(Func f, Args... args)
Helper for creating an @classmethod.
Definition IRCore.h:2102
Action
The actions performed by @newSparseTensor.
Definition Enums.h:146
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).
Definition Diagnostics.h:26
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.
Definition Support.h:121
Named MLIR attribute.
Definition IR.h:77
MlirAttribute attribute
Definition IR.h:79
MlirIdentifier name
Definition IR.h:78
A pointer to a sized fragment of a string, not necessarily null-terminated.
Definition Support.h:78
const char * data
Pointer to the first symbol.
Definition Support.h:79
size_t length
Length of the fragment.
Definition Support.h:80
Accumulates into a python string from a method that accepts an MlirStringCallback.
MlirStringCallback getCallback()
Custom exception that allows access to error diagnostic information.
Definition IRCore.h:1545
MLIRError(std::string message, std::vector< PyDiagnostic::DiagnosticInfo > &&errorDiagnostics={})
Definition IRCore.h:1546
std::vector< PyDiagnostic::DiagnosticInfo > errorDiagnostics
Definition IRCore.h:1556
static void bind(nanobind::module_ &m)
Bind the MLIRError exception class to the given module.
Definition IRCore.cpp:2936
static bool dunderContains(const std::string &attributeKind)
Definition IRCore.cpp:146
static nanobind::callable dunderGetItemNamed(const std::string &attributeKind)
Definition IRCore.cpp:151
static void dunderSetItemNamed(const std::string &attributeKind, nanobind::callable func, bool replace, bool allow_existing)
Definition IRCore.cpp:158
static void set(nanobind::object &o, bool enable)
Definition IRCore.cpp:108
RAII object that captures any error diagnostics emitted to the provided context.
Definition IRCore.h:528
std::vector< PyDiagnostic::DiagnosticInfo > take()
Definition IRCore.h:538