MLIR 24.0.0git
IRInterfaces.cpp
Go to the documentation of this file.
1//===- IRInterfaces.cpp - MLIR IR interfaces pybind -----------------------===//
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#include <cstdint>
10#include <optional>
11#include <string>
12#include <utility>
13#include <vector>
14
16#include "mlir-c/IR.h"
17#include "mlir-c/Interfaces.h"
18#include "mlir-c/Support.h"
21
22namespace nb = nanobind;
23
24namespace mlir {
25namespace python {
27constexpr static const char *inferReturnTypesDoc =
28 R"(Given the arguments required to build an operation, attempts to infer
29its return types. Raises ValueError on failure.)";
30
31constexpr static const char *inferReturnTypeComponentsDoc =
32 R"(Given the arguments required to build an operation, attempts to infer
33its return shaped type components. Raises ValueError on failure.)";
34
35namespace {
36
37MlirAttribute unwrapOptionalAttribute(const nb::object &attribute) {
38 if (attribute.is_none())
39 return mlirAttributeGetNull();
40
41 PyAttribute *pyAttribute = nullptr;
42 if (!nb::try_cast<PyAttribute *>(attribute, pyAttribute) || !pyAttribute)
43 throw nb::type_error("parameters must be an Attribute or None");
44 return pyAttribute->get();
45}
46
47void appendMemoryEffectInstance(PyMemoryEffectsInstanceList &effects,
48 const PyMemoryEffect &effect,
49 const nb::object &target,
50 const nb::object &parameters, int stage,
51 bool effectOnFullRegion,
52 const PySideEffectResource &resource) {
53 MlirMemoryEffectInstancesList list = effects.get();
54 MlirAttribute unwrappedParameters = unwrapOptionalAttribute(parameters);
55
56 MlirMemoryEffectInstance rawInstance{nullptr};
57 if (target.is_none()) {
58 rawInstance =
59 mlirMemoryEffectInstanceCreate(effect.get(), unwrappedParameters, stage,
60 effectOnFullRegion, resource.get());
61 } else {
62 PyOpOperand *opOperand = nullptr;
63 PyValue *value = nullptr;
64 PyAttribute *attribute = nullptr;
65 if (nb::try_cast<PyOpOperand *>(target, opOperand) && opOperand) {
67 effect.get(), *opOperand, unwrappedParameters, stage,
68 effectOnFullRegion, resource.get());
69 } else if (nb::try_cast<PyValue *>(target, value) && value) {
70 MlirValue mlirValue = value->get();
71 if (mlirValueIsAOpResult(mlirValue)) {
73 effect.get(), mlirValue, unwrappedParameters, stage,
74 effectOnFullRegion, resource.get());
75 } else if (mlirValueIsABlockArgument(mlirValue)) {
77 effect.get(), mlirValue, unwrappedParameters, stage,
78 effectOnFullRegion, resource.get());
79 } else {
80 throw nb::type_error(
81 "target Value must be an OpResult or BlockArgument");
82 }
83 } else if (nb::try_cast<PyAttribute *>(target, attribute) && attribute) {
84 MlirAttribute symbol = attribute->get();
85 if (!mlirAttributeIsASymbolRef(symbol))
86 throw nb::type_error("target Attribute must be a SymbolRefAttr");
88 effect.get(), symbol, unwrappedParameters, stage, effectOnFullRegion,
89 resource.get());
90 } else {
91 throw nb::type_error(
92 "target must be an OpOperand, OpResult, BlockArgument, "
93 "SymbolRefAttr, or None");
94 }
95 }
96
97 PyMemoryEffectInstance instance(rawInstance);
99}
100
101/// Takes in an optional ist of operands and converts them into a std::vector
102/// of MlirVlaues. Returns an empty std::vector if the list is empty.
103std::vector<MlirValue> wrapOperands(std::optional<nb::sequence> operandList) {
104 std::vector<MlirValue> mlirOperands;
105
106 if (!operandList || nb::len(*operandList) == 0) {
107 return mlirOperands;
108 }
109
110 // Note: as the list may contain other lists this may not be final size.
111 mlirOperands.reserve(nb::len(*operandList));
112 for (size_t i = 0, e = nb::len(*operandList); i < e; ++i) {
113 nb::handle operand = (*operandList)[i];
114 intptr_t index = static_cast<intptr_t>(i);
115 if (operand.is_none())
116 continue;
117
118 PyValue *val;
119 try {
120 val = nb::cast<PyValue *>(operand);
121 if (!val)
122 throw nb::cast_error();
123 mlirOperands.push_back(val->get());
124 continue;
125 } catch (nb::cast_error &err) {
126 // Intentionally unhandled to try sequence below first.
127 (void)err;
128 }
129
130 try {
131 auto vals = nb::cast<nb::sequence>(operand);
132 for (nb::handle v : vals) {
133 try {
134 val = nb::cast<PyValue *>(v);
135 if (!val)
136 throw nb::cast_error();
137 mlirOperands.push_back(val->get());
138 } catch (nb::cast_error &err) {
139 throw nb::value_error(
140 nanobind::detail::join("Operand ", index,
141 " must be a Value or Sequence of Values (",
142 err.what(), ")")
143 .c_str());
144 }
145 }
146 continue;
147 } catch (nb::cast_error &err) {
148 throw nb::value_error(
149 nanobind::detail::join("Operand ", index,
150 " must be a Value or Sequence of Values (",
151 err.what(), ")")
152 .c_str());
153 }
154
155 throw nb::cast_error();
156 }
157
158 return mlirOperands;
159}
160
161/// Takes in an optional vector of PyRegions and returns a std::vector of
162/// MlirRegion. Returns an empty std::vector if the list is empty.
163std::vector<MlirRegion>
164wrapRegions(std::optional<std::vector<PyRegion>> regions) {
165 std::vector<MlirRegion> mlirRegions;
166
167 if (regions) {
168 mlirRegions.reserve(regions->size());
169 for (PyRegion &region : *regions) {
170 mlirRegions.push_back(region);
171 }
172 }
173
174 return mlirRegions;
175}
176
177} // namespace
178
179/// Python wrapper for InferTypeOpInterface. This interface has only static
180/// methods.
182 : public PyConcreteOpInterface<PyInferTypeOpInterface> {
183public:
185
186 constexpr static const char *pyClassName = "InferTypeOpInterface";
189
190 /// C-style user-data structure for type appending callback.
195
196 /// Appends the types provided as the two first arguments to the user-data
197 /// structure (expects AppendResultsCallbackData).
198 static void appendResultsCallback(intptr_t nTypes, MlirType *types,
199 void *userData) {
200 auto *data = static_cast<AppendResultsCallbackData *>(userData);
201 data->inferredTypes.reserve(data->inferredTypes.size() + nTypes);
202 for (intptr_t i = 0; i < nTypes; ++i) {
203 data->inferredTypes.emplace_back(data->pyMlirContext.getRef(), types[i]);
204 }
205 }
206
207 /// Given the arguments required to build an operation, attempts to infer its
208 /// return types. Throws value_error on failure.
209 std::vector<PyType>
210 inferReturnTypes(std::optional<nb::sequence> operandList,
211 std::optional<PyAttribute> attributes, void *properties,
212 std::optional<std::vector<PyRegion>> regions,
214 DefaultingPyLocation location) {
215 std::vector<MlirValue> mlirOperands = wrapOperands(std::move(operandList));
216 std::vector<MlirRegion> mlirRegions = wrapRegions(std::move(regions));
217
218 std::vector<PyType> inferredTypes;
219 PyMlirContext &pyContext = context.resolve();
220 AppendResultsCallbackData data{inferredTypes, pyContext};
221 MlirStringRef opNameRef =
222 mlirStringRefCreate(getOpName().data(), getOpName().length());
223 MlirAttribute attributeDict =
224 attributes ? attributes->get() : mlirAttributeGetNull();
225
227 opNameRef, pyContext.get(), location.resolve(), mlirOperands.size(),
228 mlirOperands.data(), attributeDict, properties, mlirRegions.size(),
229 mlirRegions.data(), &appendResultsCallback, &data);
230
232 throw nb::value_error("Failed to infer result types");
233 }
234
235 return inferredTypes;
236 }
237
238 static void bindDerived(ClassTy &cls) {
239 cls.def("inferReturnTypes", &PyInferTypeOpInterface::inferReturnTypes,
240 nb::arg("operands") = nb::none(),
241 nb::arg("attributes") = nb::none(),
242 nb::arg("properties") = nb::none(), nb::arg("regions") = nb::none(),
243 nb::arg("context") = nb::none(), nb::arg("loc") = nb::none(),
245 }
246};
247
248/// Wrapper around an shaped type components.
250public:
251 PyShapedTypeComponents(MlirType elementType) : elementType(elementType) {}
252 PyShapedTypeComponents(nb::list shape, MlirType elementType)
253 : shape(std::move(shape)), elementType(elementType), ranked(true) {}
254 PyShapedTypeComponents(nb::list shape, MlirType elementType,
255 MlirAttribute attribute)
256 : shape(std::move(shape)), elementType(elementType), attribute(attribute),
257 ranked(true) {}
260 : shape(other.shape), elementType(other.elementType),
261 attribute(other.attribute), ranked(other.ranked) {}
262
263 static void bind(nb::module_ &m) {
264 nb::class_<PyShapedTypeComponents>(m, "ShapedTypeComponents")
265 .def_prop_ro(
266 "element_type",
267 [](PyShapedTypeComponents &self) { return self.elementType; },
268 nb::sig("def element_type(self) -> Type"),
269 "Returns the element type of the shaped type components.")
270 .def_static(
271 "get",
272 [](PyType &elementType) {
273 return PyShapedTypeComponents(elementType);
274 },
275 nb::arg("element_type"),
276 "Create an shaped type components object with only the element "
277 "type.")
278 .def_static(
279 "get",
280 [](nb::typed<nb::list, nb::int_> shape, PyType &elementType) {
281 return PyShapedTypeComponents(std::move(shape), elementType);
282 },
283 nb::arg("shape"), nb::arg("element_type"),
284 "Create a ranked shaped type components object.")
285 .def_static(
286 "get",
287 [](nb::typed<nb::list, nb::int_> shape, PyType &elementType,
288 PyAttribute &attribute) {
289 return PyShapedTypeComponents(std::move(shape), elementType,
290 attribute);
291 },
292 nb::arg("shape"), nb::arg("element_type"), nb::arg("attribute"),
293 "Create a ranked shaped type components object with attribute.")
294 .def_prop_ro(
295 "has_rank",
296 [](PyShapedTypeComponents &self) -> bool { return self.ranked; },
297 "Returns whether the given shaped type component is ranked.")
298 .def_prop_ro(
299 "rank",
300 [](PyShapedTypeComponents &self) -> std::optional<nb::int_> {
301 if (!self.ranked)
302 return {};
303 return nb::int_(self.shape.size());
304 },
305 "Returns the rank of the given ranked shaped type components. If "
306 "the shaped type components does not have a rank, None is "
307 "returned.")
308 .def_prop_ro(
309 "shape",
310 [](PyShapedTypeComponents &self) -> std::optional<nb::list> {
311 if (!self.ranked)
312 return {};
313 return nb::list(self.shape);
314 },
315 "Returns the shape of the ranked shaped type components as a list "
316 "of integers. Returns none if the shaped type component does not "
317 "have a rank.");
318 }
319
320 nb::object getCapsule();
321 static PyShapedTypeComponents createFromCapsule(nb::object capsule);
322
323private:
324 nb::list shape;
325 MlirType elementType;
326 MlirAttribute attribute;
327 bool ranked{false};
328};
329
330/// Python wrapper for InferShapedTypeOpInterface. This interface has only
331/// static methods.
333 : public PyConcreteOpInterface<PyInferShapedTypeOpInterface> {
334public:
337
338 constexpr static const char *pyClassName = "InferShapedTypeOpInterface";
341
342 /// C-style user-data structure for type appending callback.
344 std::vector<PyShapedTypeComponents> &inferredShapedTypeComponents;
345 };
346
347 /// Appends the shaped type components provided as unpacked shape, element
348 /// type, attribute to the user-data.
349 static void appendResultsCallback(bool hasRank, intptr_t rank,
350 const int64_t *shape, MlirType elementType,
351 MlirAttribute attribute, void *userData) {
352 auto *data = static_cast<AppendResultsCallbackData *>(userData);
353 if (!hasRank) {
354 data->inferredShapedTypeComponents.emplace_back(elementType);
355 } else {
356 nb::list shapeList;
357 for (intptr_t i = 0; i < rank; ++i) {
358 shapeList.append(shape[i]);
359 }
360 data->inferredShapedTypeComponents.emplace_back(shapeList, elementType,
361 attribute);
362 }
363 }
364
365 /// Given the arguments required to build an operation, attempts to infer the
366 /// shaped type components. Throws value_error on failure.
367 std::vector<PyShapedTypeComponents> inferReturnTypeComponents(
368 std::optional<nb::sequence> operandList,
369 std::optional<PyAttribute> attributes, void *properties,
370 std::optional<std::vector<PyRegion>> regions,
372 std::vector<MlirValue> mlirOperands = wrapOperands(std::move(operandList));
373 std::vector<MlirRegion> mlirRegions = wrapRegions(std::move(regions));
374
375 std::vector<PyShapedTypeComponents> inferredShapedTypeComponents;
376 PyMlirContext &pyContext = context.resolve();
377 AppendResultsCallbackData data{inferredShapedTypeComponents};
378 MlirStringRef opNameRef =
379 mlirStringRefCreate(getOpName().data(), getOpName().length());
380 MlirAttribute attributeDict =
381 attributes ? attributes->get() : mlirAttributeGetNull();
382
384 opNameRef, pyContext.get(), location.resolve(), mlirOperands.size(),
385 mlirOperands.data(), attributeDict, properties, mlirRegions.size(),
386 mlirRegions.data(), &appendResultsCallback, &data);
387
389 throw nb::value_error("Failed to infer result shape type components");
390 }
391
392 return inferredShapedTypeComponents;
393 }
394
395 static void bindDerived(ClassTy &cls) {
396 cls.def("inferReturnTypeComponents",
398 nb::arg("operands") = nb::none(),
399 nb::arg("attributes") = nb::none(), nb::arg("regions") = nb::none(),
400 nb::arg("properties") = nb::none(), nb::arg("context") = nb::none(),
401 nb::arg("loc") = nb::none(), inferReturnTypeComponentsDoc);
402 }
403};
404
405/// Wrapper around the ConditionallySpeculatable interface.
407 : public PyConcreteOpInterface<PyConditionallySpeculatableOpInterface> {
408public:
411
412 constexpr static const char *pyClassName = "ConditionallySpeculatable";
415
416 /// Attach a new ConditionallySpeculatable FallbackModel to the named
417 /// operation. The FallbackModel acts as a trampoline for callbacks on the
418 /// Python class.
419 static void attach(nb::object &target, const std::string &opName,
422 callbacks.userData = target.ptr();
423 nb::handle(static_cast<PyObject *>(callbacks.userData)).inc_ref();
424 callbacks.construct = nullptr;
425 callbacks.destruct = [](void *userData) {
426 nb::handle(static_cast<PyObject *>(userData)).dec_ref();
427 };
428 callbacks.getSpeculatability = [](MlirOperation op, void *userData) {
429 nb::handle pyClass(static_cast<PyObject *>(userData));
430
431 auto pyGetSpeculatability =
432 nb::cast<nb::callable>(nb::getattr(pyClass, "get_speculatability"));
433
434 PyMlirContextRef context =
436 auto opview = PyOperation::forOperation(context, op)->createOpView();
437
438 return nb::cast<MlirSpeculatability>(pyGetSpeculatability(opview));
439 };
440
442 ctx->get(), mlirStringRefCreate(opName.c_str(), opName.size()),
443 callbacks);
444 }
445
446 static void bindDerived(ClassTy &cls) {
447 cls.def(
448 "getSpeculatability",
450 if (self.isStatic())
451 throw nb::type_error(
452 "Cannot query speculatability on a static interface");
453 auto operation = self.getOperationObject();
454 auto *pyOperation = nb::cast<PyOperation *>(operation);
456 pyOperation->get());
457 },
458 "Returns the speculatability of the given operation.");
459 cls.attr("attach") = classmethod(
460 [](const nb::object &cls, const nb::object &opName, nb::object target,
461 DefaultingPyMlirContext context) {
462 if (target.is_none())
463 target = cls;
464 return attach(target, nb::cast<std::string>(opName), context);
465 },
466 nb::arg("cls"), nb::arg("op_name"), nb::kw_only(),
467 nb::arg("target").none() = nb::none(),
468 nb::arg("context").none() = nb::none(),
469 "Attach the interface subclass to the given operation name.");
470 }
471};
472
473/// Wrapper around the MemoryEffectsOpInterface.
475 : public PyConcreteOpInterface<PyMemoryEffectsOpInterface> {
476public:
479
480 constexpr static const char *pyClassName = "MemoryEffectsOpInterface";
483
484 /// Attach a new MemoryEffectsOpInterface FallbackModel to the named
485 /// operation. The FallbackModel acts as a trampoline for callbacks on the
486 /// Python class.
487 static void attach(nb::object &target, const std::string &opName,
490 callbacks.userData = target.ptr();
491 nb::handle(static_cast<PyObject *>(callbacks.userData)).inc_ref();
492 callbacks.construct = nullptr;
493 callbacks.destruct = [](void *userData) {
494 nb::handle(static_cast<PyObject *>(userData)).dec_ref();
495 };
496 callbacks.getEffects = [](MlirOperation op,
497 MlirMemoryEffectInstancesList effects,
498 void *userData) {
499 nb::handle pyClass(static_cast<PyObject *>(userData));
500
501 // Get the 'get_effects' method from the Python class.
502 auto pyGetEffects =
503 nb::cast<nb::callable>(nb::getattr(pyClass, "get_effects"));
504
505 PyMemoryEffectsInstanceList effectsWrapper{effects};
506
507 PyMlirContextRef context =
509 auto opview = PyOperation::forOperation(context, op)->createOpView();
510
511 // Invoke `pyClass.get_effects(op, effects)`.
512 pyGetEffects(opview, effectsWrapper);
513 };
514
516 ctx->get(), mlirStringRefCreate(opName.c_str(), opName.size()),
517 callbacks);
518 }
519
520 static void bindDerived(ClassTy &cls) {
521 cls.attr("attach") = classmethod(
522 [](const nb::object &cls, const nb::object &opName, nb::object target,
523 DefaultingPyMlirContext context) {
524 if (target.is_none())
525 target = cls;
526 return attach(target, nb::cast<std::string>(opName), context);
527 },
528 nb::arg("cls"), nb::arg("op_name"), nb::kw_only(),
529 nb::arg("target").none() = nb::none(),
530 nb::arg("context").none() = nb::none(),
531 "Attach the interface subclass to the given operation name.");
532 }
533};
534
535void populateIRInterfaces(nb::module_ &m) {
536 nb::enum_<MlirSpeculatability>(m, "Speculatability")
537 .value("NotSpeculatable", MlirSpeculatabilityNotSpeculatable)
538 .value("Speculatable", MlirSpeculatabilitySpeculatable)
539 .value("RecursivelySpeculatable",
541 nb::class_<PyMemoryEffect>(m, "MemoryEffect", "A memory effect.")
542 .def_prop_ro_static("Allocate",
543 [](nb::object & /*class*/) {
544 return PyMemoryEffect(
546 })
547 .def_prop_ro_static("Free",
548 [](nb::object & /*class*/) {
550 })
551 .def_prop_ro_static("Read",
552 [](nb::object & /*class*/) {
554 })
555 .def_prop_ro_static("Write", [](nb::object & /*class*/) {
557 });
558
559 nb::class_<PySideEffectResource>(m, "SideEffectResource",
560 "A side effect resource.")
561 .def_prop_ro_static("Default", [](nb::object & /*class*/) {
563 });
564
565 nb::class_<PyMemoryEffectsInstanceList>(
566 m, "MemoryEffectInstancesList",
567 "A memory effect list that is valid only during get_effects.")
568 .def("append", &appendMemoryEffectInstance, nb::arg("effect"),
569 nb::arg("target").none() = nb::none(), nb::kw_only(),
570 nb::arg("parameters").none() = nb::none(), nb::arg("stage") = 0,
571 nb::arg("effect_on_full_region") = false,
572 nb::arg("resource") =
574 nb::sig("def append(self, effect: MemoryEffect, target: OpOperand | "
575 "OpResult | BlockArgument | SymbolRefAttr | None = None, *, "
576 "parameters: Attribute | None = None, stage: int = 0, "
577 "effect_on_full_region: bool = False, resource: "
578 "SideEffectResource = ...) -> None"),
579 "Append a memory effect instance. The target may be an OpOperand, "
580 "OpResult, BlockArgument, SymbolRefAttr, or None.");
581
587}
588} // namespace MLIR_BINDINGS_PYTHON_DOMAIN
589} // namespace python
590} // namespace mlir
true
Given two iterators into the same block, return "true" if a is before `b.
bool mlirValueIsABlockArgument(MlirValue value)
Definition IR.cpp:1158
bool mlirValueIsAOpResult(MlirValue value)
Definition IR.cpp:1162
MlirContext mlirOperationGetContext(MlirOperation op)
Definition IR.cpp:683
ReferrentTy * get() const
Used in function arguments when None should resolve to the current context manager set instance.
Definition IRCore.h:541
Used in function arguments when None should resolve to the current context manager set instance.
Definition IRCore.h:291
Wrapper around the generic MlirAttribute.
Definition IRCore.h:1018
PyConcreteOpInterface(nanobind::object object, DefaultingPyMlirContext context)
nanobind::typed< nanobind::object, PyOperation > getOperationObject()
Returns the operation instance from which this object was constructed.
bool isStatic()
Returns true if this object was constructed from a subclass of OpView rather than from an operation i...
static void attach(nb::object &target, const std::string &opName, DefaultingPyMlirContext ctx)
Attach a new ConditionallySpeculatable FallbackModel to the named operation.
static void appendResultsCallback(bool hasRank, intptr_t rank, const int64_t *shape, MlirType elementType, MlirAttribute attribute, void *userData)
Appends the shaped type components provided as unpacked shape, element type, attribute to the user-da...
std::vector< PyShapedTypeComponents > inferReturnTypeComponents(std::optional< nb::sequence > operandList, std::optional< PyAttribute > attributes, void *properties, std::optional< std::vector< PyRegion > > regions, DefaultingPyMlirContext context, DefaultingPyLocation location)
Given the arguments required to build an operation, attempts to infer the shaped type components.
std::vector< PyType > inferReturnTypes(std::optional< nb::sequence > operandList, std::optional< PyAttribute > attributes, void *properties, std::optional< std::vector< PyRegion > > regions, DefaultingPyMlirContext context, DefaultingPyLocation location)
Given the arguments required to build an operation, attempts to infer its return types.
static void appendResultsCallback(intptr_t nTypes, MlirType *types, void *userData)
Appends the types provided as the two first arguments to the user-data structure (expects AppendResul...
A callback-scoped view of a list of memory effect instances.
static void attach(nb::object &target, const std::string &opName, DefaultingPyMlirContext ctx)
Attach a new MemoryEffectsOpInterface FallbackModel to the named operation.
static PyMlirContextRef forContext(MlirContext context)
Returns a context reference for the singleton PyMlirContext wrapper for the given context.
Definition IRCore.cpp:461
MlirContext get()
Accesses the underlying MlirContext.
Definition IRCore.h:224
nanobind::object createOpView()
Creates an OpView suitable for this operation.
Definition IRCore.cpp:1352
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:958
PyShapedTypeComponents(nb::list shape, MlirType elementType, MlirAttribute attribute)
static PyShapedTypeComponents createFromCapsule(nb::object capsule)
PyShapedTypeComponents(PyShapedTypeComponents &&other) noexcept
Wrapper around the generic MlirType.
Definition IRCore.h:891
MLIR_CAPI_EXPORTED MlirAttribute mlirAttributeGetNull(void)
Returns an empty attribute.
MLIR_CAPI_EXPORTED bool mlirAttributeIsASymbolRef(MlirAttribute attr)
Checks whether the given attribute is a symbol reference attribute.
MLIR_CAPI_EXPORTED MlirLogicalResult mlirInferShapedTypeOpInterfaceInferReturnTypes(MlirStringRef opName, MlirContext context, MlirLocation location, intptr_t nOperands, MlirValue *operands, MlirAttribute attributes, void *properties, intptr_t nRegions, MlirRegion *regions, MlirShapedTypeComponentsCallback callback, void *userData)
Infers the return shaped type components of the operation.
MLIR_CAPI_EXPORTED MlirSpeculatability mlirConditionallySpeculatableOpInterfaceGetSpeculatability(MlirOperation operation)
Returns the speculatability of the given operation.
MLIR_CAPI_EXPORTED MlirTypeID mlirInferTypeOpInterfaceTypeID(void)
Returns the interface TypeID of the InferTypeOpInterface.
MLIR_CAPI_EXPORTED MlirMemoryEffectInstance mlirMemoryEffectInstanceCreateForOpOperand(MlirMemoryEffect effect, MlirOpOperand opOperand, MlirAttribute parameters, int stage, bool effectOnFullRegion, MlirSideEffectResource resource)
Creates a memory effect instance associated with an operation operand.
MLIR_CAPI_EXPORTED MlirTypeID mlirConditionallySpeculatableOpInterfaceTypeID(void)
Returns the interface TypeID of the ConditionallySpeculatable interface.
MLIR_CAPI_EXPORTED void mlirConditionallySpeculatableOpInterfaceAttachFallbackModel(MlirContext ctx, MlirStringRef opName, MlirConditionallySpeculatableOpInterfaceCallbacks callbacks)
Attach a new FallbackModel for the ConditionallySpeculatable interface to the named operation.
@ MlirSpeculatabilityRecursivelySpeculatable
The operation is speculatable if all nested operations are speculatable.
Definition Interfaces.h:114
@ MlirSpeculatabilitySpeculatable
The operation is speculatable.
Definition Interfaces.h:112
@ MlirSpeculatabilityNotSpeculatable
The operation is not speculatable.
Definition Interfaces.h:110
MLIR_CAPI_EXPORTED MlirMemoryEffect mlirMemoryEffectsReadGet(void)
Returns the borrowed singleton instance of the read memory effect.
MLIR_CAPI_EXPORTED MlirSideEffectResource mlirSideEffectsDefaultResourceGet(void)
Returns the borrowed singleton instance of the default side effect resource.
MLIR_CAPI_EXPORTED MlirMemoryEffectInstance mlirMemoryEffectInstanceCreate(MlirMemoryEffect effect, MlirAttribute parameters, int stage, bool effectOnFullRegion, MlirSideEffectResource resource)
Creates a memory effect instance without an associated IR entity.
MLIR_CAPI_EXPORTED MlirLogicalResult mlirInferTypeOpInterfaceInferReturnTypes(MlirStringRef opName, MlirContext context, MlirLocation location, intptr_t nOperands, MlirValue *operands, MlirAttribute attributes, void *properties, intptr_t nRegions, MlirRegion *regions, MlirTypesCallback callback, void *userData)
Infers the return types of the operation identified by its canonical given the arguments that will be...
MLIR_CAPI_EXPORTED MlirMemoryEffectInstance mlirMemoryEffectInstanceCreateForOpResult(MlirMemoryEffect effect, MlirValue result, MlirAttribute parameters, int stage, bool effectOnFullRegion, MlirSideEffectResource resource)
Creates a memory effect instance associated with an operation result.
MLIR_CAPI_EXPORTED MlirMemoryEffect mlirMemoryEffectsFreeGet(void)
Returns the borrowed singleton instance of the free memory effect.
MLIR_CAPI_EXPORTED MlirMemoryEffect mlirMemoryEffectsWriteGet(void)
Returns the borrowed singleton instance of the write memory effect.
MLIR_CAPI_EXPORTED MlirTypeID mlirMemoryEffectsOpInterfaceTypeID(void)
Returns the interface TypeID of the MemoryEffectsOpInterface.
MLIR_CAPI_EXPORTED MlirTypeID mlirInferShapedTypeOpInterfaceTypeID(void)
Returns the interface TypeID of the InferShapedTypeOpInterface.
MLIR_CAPI_EXPORTED void mlirMemoryEffectsOpInterfaceAttachFallbackModel(MlirContext ctx, MlirStringRef opName, MlirMemoryEffectsOpInterfaceCallbacks callbacks)
Attach a new FallbackModel for the MemoryEffectsOpInterface to the named operation.
MLIR_CAPI_EXPORTED MlirMemoryEffect mlirMemoryEffectsAllocateGet(void)
Returns the borrowed singleton instance of the allocate memory effect.
MLIR_CAPI_EXPORTED MlirMemoryEffectInstance mlirMemoryEffectInstanceCreateForSymbol(MlirMemoryEffect effect, MlirAttribute symbol, MlirAttribute parameters, int stage, bool effectOnFullRegion, MlirSideEffectResource resource)
Creates a memory effect instance associated with a symbol.
MLIR_CAPI_EXPORTED void mlirMemoryEffectInstancesListAppend(MlirMemoryEffectInstancesList list, MlirMemoryEffectInstance instance)
Appends a copy of instance to the given list.
MLIR_CAPI_EXPORTED MlirMemoryEffectInstance mlirMemoryEffectInstanceCreateForBlockArgument(MlirMemoryEffect effect, MlirValue blockArgument, MlirAttribute parameters, int stage, bool effectOnFullRegion, MlirSideEffectResource resource)
Creates a memory effect instance associated with a block argument.
static MlirStringRef mlirStringRefCreate(const char *str, size_t length)
Constructs a string reference from the pointer and length.
Definition Support.h:87
static bool mlirLogicalResultIsFailure(MlirLogicalResult res)
Checks if the given logical result represents a failure.
Definition Support.h:132
PyObjectRef< PyMlirContext > PyMlirContextRef
Wrapper around MlirContext.
Definition IRCore.h:210
static constexpr const char * inferReturnTypesDoc
static constexpr const char * inferReturnTypeComponentsDoc
nanobind::object classmethod(Func f, Args... args)
Helper for creating an @classmethod.
Definition IRCore.h:2008
Include the generated interface declarations.
std::string join(const Ts &...args)
Helper function to concatenate arguments into a std::string.
Callbacks for implementing ConditionallySpeculatable from external code.
Definition Interfaces.h:122
void(* destruct)(void *userData)
Optional destructor for user data. Set to nullptr to disable it.
Definition Interfaces.h:126
void(* construct)(void *userData)
Optional constructor for user data. Set to nullptr to disable it.
Definition Interfaces.h:124
MlirSpeculatability(* getSpeculatability)(MlirOperation op, void *userData)
Returns the speculatability of the given operation.
Definition Interfaces.h:128
A logical result value, essentially a boolean with named states.
Definition Support.h:121
Callbacks for implementing MemoryEffectsOpInterface from external code.
Definition Interfaces.h:229
void(* construct)(void *userData)
Optional constructor for user data. Set to nullptr to disable it.
Definition Interfaces.h:231
void(* getEffects)(MlirOperation op, MlirMemoryEffectInstancesList effects, void *userData)
Get memory effects callback.
Definition Interfaces.h:235
void(* destruct)(void *userData)
Optional destructor for user data. Set to nullptr to disable it.
Definition Interfaces.h:233
A pointer to a sized fragment of a string, not necessarily null-terminated.
Definition Support.h:78