| 1 |
//===- IRAttributes.cpp - Exports builtin and standard attributes ---------===// |
| 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 <utility> |
| 10 |
#include <optional> |
| 11 |
|
| 12 |
#include "IRModule.h" |
| 13 |
|
| 14 |
#include "PybindUtils.h" |
| 15 |
|
| 16 |
#include "mlir-c/BuiltinAttributes.h" |
| 17 |
#include "mlir-c/BuiltinTypes.h" |
| 18 |
|
| 19 |
namespace py = pybind11; |
| 20 |
using namespace mlir; |
| 21 |
using namespace mlir::python; |
| 22 |
|
| 23 |
using llvm::SmallVector; |
| 24 |
using llvm::Twine; |
| 25 |
|
| 26 |
//------------------------------------------------------------------------------ |
| 27 |
// Docstrings (trivial, non-duplicated docstrings are included inline). |
| 28 |
//------------------------------------------------------------------------------ |
| 29 |
|
| 30 |
static const char kDenseElementsAttrGetDocstring[] = |
| 31 |
R"(Gets a DenseElementsAttr from a Python buffer or array. |
| 32 |
|
| 33 |
When `type` is not provided, then some limited type inferencing is done based |
| 34 |
on the buffer format. Support presently exists for 8/16/32/64 signed and |
| 35 |
unsigned integers and float16/float32/float64. DenseElementsAttrs of these |
| 36 |
types can also be converted back to a corresponding buffer. |
| 37 |
|
| 38 |
For conversions outside of these types, a `type=` must be explicitly provided |
| 39 |
and the buffer contents must be bit-castable to the MLIR internal |
| 40 |
representation: |
| 41 |
|
| 42 |
* Integer types (except for i1): the buffer must be byte aligned to the |
| 43 |
next byte boundary. |
| 44 |
* Floating point types: Must be bit-castable to the given floating point |
| 45 |
size. |
| 46 |
* i1 (bool): Bit packed into 8bit words where the bit pattern matches a |
| 47 |
row major ordering. An arbitrary Numpy `bool_` array can be bit packed to |
| 48 |
this specification with: `np.packbits(ary, axis=None, bitorder='little')`. |
| 49 |
|
| 50 |
If a single element buffer is passed (or for i1, a single byte with value 0 |
| 51 |
or 255), then a splat will be created. |
| 52 |
|
| 53 |
Args: |
| 54 |
array: The array or buffer to convert. |
| 55 |
signless: If inferring an appropriate MLIR type, use signless types for |
| 56 |
integers (defaults True). |
| 57 |
type: Skips inference of the MLIR element type and uses this instead. The |
| 58 |
storage size must be consistent with the actual contents of the buffer. |
| 59 |
shape: Overrides the shape of the buffer when constructing the MLIR |
| 60 |
shaped type. This is needed when the physical and logical shape differ (as |
| 61 |
for i1). |
| 62 |
context: Explicit context, if not from context manager. |
| 63 |
|
| 64 |
Returns: |
| 65 |
DenseElementsAttr on success. |
| 66 |
|
| 67 |
Raises: |
| 68 |
ValueError: If the type of the buffer or array cannot be matched to an MLIR |
| 69 |
type or if the buffer does not meet expectations. |
| 70 |
)"; |
| 71 |
|
| 72 |
namespace { |
| 73 |
|
| 74 |
static MlirStringRef toMlirStringRef(const std::string &s) { |
| 75 |
return mlirStringRefCreate(s.data(), s.size()); |
| 76 |
} |
| 77 |
|
| 78 |
class PyAffineMapAttribute : public PyConcreteAttribute<PyAffineMapAttribute> { |
| 79 |
public: |
| 80 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAAffineMap; |
| 81 |
static constexpr const char *pyClassName = "AffineMapAttr"; |
| 82 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 83 |
|
| 84 |
static void bindDerived(ClassTy &c) { |
| 85 |
c.def_static( |
| 86 |
"get", |
| 87 |
[](PyAffineMap &affineMap) { |
| 88 |
MlirAttribute attr = mlirAffineMapAttrGet(affineMap.get()); |
| 89 |
return PyAffineMapAttribute(affineMap.getContext(), attr); |
| 90 |
}, |
| 91 |
py::arg("affine_map"), "Gets an attribute wrapping an AffineMap."); |
| 92 |
} |
| 93 |
}; |
| 94 |
|
| 95 |
template <typename T> |
| 96 |
static T pyTryCast(py::handle object) { |
| 97 |
try { |
| 98 |
return object.cast<T>(); |
| 99 |
} catch (py::cast_error &err) { |
| 100 |
std::string msg = |
| 101 |
std::string( |
| 102 |
"Invalid attribute when attempting to create an ArrayAttribute (") + |
| 103 |
err.what() + ")"; |
| 104 |
throw py::cast_error(msg); |
| 105 |
} catch (py::reference_cast_error &err) { |
| 106 |
std::string msg = std::string("Invalid attribute (None?) when attempting " |
| 107 |
"to create an ArrayAttribute (") + |
| 108 |
err.what() + ")"; |
| 109 |
throw py::cast_error(msg); |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
/// A python-wrapped dense array attribute with an element type and a derived |
| 114 |
/// implementation class. |
| 115 |
template <typename EltTy, typename DerivedT> |
| 116 |
class PyDenseArrayAttribute : public PyConcreteAttribute<DerivedT> { |
| 117 |
public: |
| 118 |
using PyConcreteAttribute<DerivedT>::PyConcreteAttribute; |
| 119 |
|
| 120 |
/// Iterator over the integer elements of a dense array. |
| 121 |
class PyDenseArrayIterator { |
| 122 |
public: |
| 123 |
PyDenseArrayIterator(PyAttribute attr) : attr(std::move(attr)) {} |
| 124 |
|
| 125 |
/// Return a copy of the iterator. |
| 126 |
PyDenseArrayIterator dunderIter() { return *this; } |
| 127 |
|
| 128 |
/// Return the next element. |
| 129 |
EltTy dunderNext() { |
| 130 |
// Throw if the index has reached the end. |
| 131 |
if (nextIndex >= mlirDenseArrayGetNumElements(attr.get())) |
| 132 |
throw py::stop_iteration(); |
| 133 |
return DerivedT::getElement(attr.get(), nextIndex++); |
| 134 |
} |
| 135 |
|
| 136 |
/// Bind the iterator class. |
| 137 |
static void bind(py::module &m) { |
| 138 |
py::class_<PyDenseArrayIterator>(m, DerivedT::pyIteratorName, |
| 139 |
py::module_local()) |
| 140 |
.def("__iter__", &PyDenseArrayIterator::dunderIter) |
| 141 |
.def("__next__", &PyDenseArrayIterator::dunderNext); |
| 142 |
} |
| 143 |
|
| 144 |
private: |
| 145 |
/// The referenced dense array attribute. |
| 146 |
PyAttribute attr; |
| 147 |
/// The next index to read. |
| 148 |
int nextIndex = 0; |
| 149 |
}; |
| 150 |
|
| 151 |
/// Get the element at the given index. |
| 152 |
EltTy getItem(intptr_t i) { return DerivedT::getElement(*this, i); } |
| 153 |
|
| 154 |
/// Bind the attribute class. |
| 155 |
static void bindDerived(typename PyConcreteAttribute<DerivedT>::ClassTy &c) { |
| 156 |
// Bind the constructor. |
| 157 |
c.def_static( |
| 158 |
"get", |
| 159 |
[](const std::vector<EltTy> &values, DefaultingPyMlirContext ctx) { |
| 160 |
MlirAttribute attr = |
| 161 |
DerivedT::getAttribute(ctx->get(), values.size(), values.data()); |
| 162 |
return DerivedT(ctx->getRef(), attr); |
| 163 |
}, |
| 164 |
py::arg("values"), py::arg("context") = py::none(), |
| 165 |
"Gets a uniqued dense array attribute"); |
| 166 |
// Bind the array methods. |
| 167 |
c.def("__getitem__", [](DerivedT &arr, intptr_t i) { |
| 168 |
if (i >= mlirDenseArrayGetNumElements(arr)) |
| 169 |
throw py::index_error("DenseArray index out of range"); |
| 170 |
return arr.getItem(i); |
| 171 |
}); |
| 172 |
c.def("__len__", [](const DerivedT &arr) { |
| 173 |
return mlirDenseArrayGetNumElements(arr); |
| 174 |
}); |
| 175 |
c.def("__iter__", |
| 176 |
[](const DerivedT &arr) { return PyDenseArrayIterator(arr); }); |
| 177 |
c.def("__add__", [](DerivedT &arr, const py::list &extras) { |
| 178 |
std::vector<EltTy> values; |
| 179 |
intptr_t numOldElements = mlirDenseArrayGetNumElements(arr); |
| 180 |
values.reserve(numOldElements + py::len(extras)); |
| 181 |
for (intptr_t i = 0; i < numOldElements; ++i) |
| 182 |
values.push_back(arr.getItem(i)); |
| 183 |
for (py::handle attr : extras) |
| 184 |
values.push_back(pyTryCast<EltTy>(attr)); |
| 185 |
MlirAttribute attr = DerivedT::getAttribute(arr.getContext()->get(), |
| 186 |
values.size(), values.data()); |
| 187 |
return DerivedT(arr.getContext(), attr); |
| 188 |
}); |
| 189 |
} |
| 190 |
}; |
| 191 |
|
| 192 |
/// Instantiate the python dense array classes. |
| 193 |
struct PyDenseBoolArrayAttribute |
| 194 |
: public PyDenseArrayAttribute<int, PyDenseBoolArrayAttribute> { |
| 195 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseBoolArray; |
| 196 |
static constexpr auto getAttribute = mlirDenseBoolArrayGet; |
| 197 |
static constexpr auto getElement = mlirDenseBoolArrayGetElement; |
| 198 |
static constexpr const char *pyClassName = "DenseBoolArrayAttr"; |
| 199 |
static constexpr const char *pyIteratorName = "DenseBoolArrayIterator"; |
| 200 |
using PyDenseArrayAttribute::PyDenseArrayAttribute; |
| 201 |
}; |
| 202 |
struct PyDenseI8ArrayAttribute |
| 203 |
: public PyDenseArrayAttribute<int8_t, PyDenseI8ArrayAttribute> { |
| 204 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseI8Array; |
| 205 |
static constexpr auto getAttribute = mlirDenseI8ArrayGet; |
| 206 |
static constexpr auto getElement = mlirDenseI8ArrayGetElement; |
| 207 |
static constexpr const char *pyClassName = "DenseI8ArrayAttr"; |
| 208 |
static constexpr const char *pyIteratorName = "DenseI8ArrayIterator"; |
| 209 |
using PyDenseArrayAttribute::PyDenseArrayAttribute; |
| 210 |
}; |
| 211 |
struct PyDenseI16ArrayAttribute |
| 212 |
: public PyDenseArrayAttribute<int16_t, PyDenseI16ArrayAttribute> { |
| 213 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseI16Array; |
| 214 |
static constexpr auto getAttribute = mlirDenseI16ArrayGet; |
| 215 |
static constexpr auto getElement = mlirDenseI16ArrayGetElement; |
| 216 |
static constexpr const char *pyClassName = "DenseI16ArrayAttr"; |
| 217 |
static constexpr const char *pyIteratorName = "DenseI16ArrayIterator"; |
| 218 |
using PyDenseArrayAttribute::PyDenseArrayAttribute; |
| 219 |
}; |
| 220 |
struct PyDenseI32ArrayAttribute |
| 221 |
: public PyDenseArrayAttribute<int32_t, PyDenseI32ArrayAttribute> { |
| 222 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseI32Array; |
| 223 |
static constexpr auto getAttribute = mlirDenseI32ArrayGet; |
| 224 |
static constexpr auto getElement = mlirDenseI32ArrayGetElement; |
| 225 |
static constexpr const char *pyClassName = "DenseI32ArrayAttr"; |
| 226 |
static constexpr const char *pyIteratorName = "DenseI32ArrayIterator"; |
| 227 |
using PyDenseArrayAttribute::PyDenseArrayAttribute; |
| 228 |
}; |
| 229 |
struct PyDenseI64ArrayAttribute |
| 230 |
: public PyDenseArrayAttribute<int64_t, PyDenseI64ArrayAttribute> { |
| 231 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseI64Array; |
| 232 |
static constexpr auto getAttribute = mlirDenseI64ArrayGet; |
| 233 |
static constexpr auto getElement = mlirDenseI64ArrayGetElement; |
| 234 |
static constexpr const char *pyClassName = "DenseI64ArrayAttr"; |
| 235 |
static constexpr const char *pyIteratorName = "DenseI64ArrayIterator"; |
| 236 |
using PyDenseArrayAttribute::PyDenseArrayAttribute; |
| 237 |
}; |
| 238 |
struct PyDenseF32ArrayAttribute |
| 239 |
: public PyDenseArrayAttribute<float, PyDenseF32ArrayAttribute> { |
| 240 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseF32Array; |
| 241 |
static constexpr auto getAttribute = mlirDenseF32ArrayGet; |
| 242 |
static constexpr auto getElement = mlirDenseF32ArrayGetElement; |
| 243 |
static constexpr const char *pyClassName = "DenseF32ArrayAttr"; |
| 244 |
static constexpr const char *pyIteratorName = "DenseF32ArrayIterator"; |
| 245 |
using PyDenseArrayAttribute::PyDenseArrayAttribute; |
| 246 |
}; |
| 247 |
struct PyDenseF64ArrayAttribute |
| 248 |
: public PyDenseArrayAttribute<double, PyDenseF64ArrayAttribute> { |
| 249 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseF64Array; |
| 250 |
static constexpr auto getAttribute = mlirDenseF64ArrayGet; |
| 251 |
static constexpr auto getElement = mlirDenseF64ArrayGetElement; |
| 252 |
static constexpr const char *pyClassName = "DenseF64ArrayAttr"; |
| 253 |
static constexpr const char *pyIteratorName = "DenseF64ArrayIterator"; |
| 254 |
using PyDenseArrayAttribute::PyDenseArrayAttribute; |
| 255 |
}; |
| 256 |
|
| 257 |
class PyArrayAttribute : public PyConcreteAttribute<PyArrayAttribute> { |
| 258 |
public: |
| 259 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAArray; |
| 260 |
static constexpr const char *pyClassName = "ArrayAttr"; |
| 261 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 262 |
|
| 263 |
class PyArrayAttributeIterator { |
| 264 |
public: |
| 265 |
PyArrayAttributeIterator(PyAttribute attr) : attr(std::move(attr)) {} |
| 266 |
|
| 267 |
PyArrayAttributeIterator &dunderIter() { return *this; } |
| 268 |
|
| 269 |
PyAttribute dunderNext() { |
| 270 |
// TODO: Throw is an inefficient way to stop iteration. |
| 271 |
if (nextIndex >= mlirArrayAttrGetNumElements(attr.get())) |
| 272 |
throw py::stop_iteration(); |
| 273 |
return PyAttribute(attr.getContext(), |
| 274 |
mlirArrayAttrGetElement(attr.get(), nextIndex++)); |
| 275 |
} |
| 276 |
|
| 277 |
static void bind(py::module &m) { |
| 278 |
py::class_<PyArrayAttributeIterator>(m, "ArrayAttributeIterator", |
| 279 |
py::module_local()) |
| 280 |
.def("__iter__", &PyArrayAttributeIterator::dunderIter) |
| 281 |
.def("__next__", &PyArrayAttributeIterator::dunderNext); |
| 282 |
} |
| 283 |
|
| 284 |
private: |
| 285 |
PyAttribute attr; |
| 286 |
int nextIndex = 0; |
| 287 |
}; |
| 288 |
|
| 289 |
PyAttribute getItem(intptr_t i) { |
| 290 |
return PyAttribute(getContext(), mlirArrayAttrGetElement(*this, i)); |
| 291 |
} |
| 292 |
|
| 293 |
static void bindDerived(ClassTy &c) { |
| 294 |
c.def_static( |
| 295 |
"get", |
| 296 |
[](py::list attributes, DefaultingPyMlirContext context) { |
| 297 |
SmallVector<MlirAttribute> mlirAttributes; |
| 298 |
mlirAttributes.reserve(py::len(attributes)); |
| 299 |
for (auto attribute : attributes) { |
| 300 |
mlirAttributes.push_back(pyTryCast<PyAttribute>(attribute)); |
| 301 |
} |
| 302 |
MlirAttribute attr = mlirArrayAttrGet( |
| 303 |
context->get(), mlirAttributes.size(), mlirAttributes.data()); |
| 304 |
return PyArrayAttribute(context->getRef(), attr); |
| 305 |
}, |
| 306 |
py::arg("attributes"), py::arg("context") = py::none(), |
| 307 |
"Gets a uniqued Array attribute"); |
| 308 |
c.def("__getitem__", |
| 309 |
[](PyArrayAttribute &arr, intptr_t i) { |
| 310 |
if (i >= mlirArrayAttrGetNumElements(arr)) |
| 311 |
throw py::index_error("ArrayAttribute index out of range"); |
| 312 |
return arr.getItem(i); |
| 313 |
}) |
| 314 |
.def("__len__", |
| 315 |
[](const PyArrayAttribute &arr) { |
| 316 |
return mlirArrayAttrGetNumElements(arr); |
| 317 |
}) |
| 318 |
.def("__iter__", [](const PyArrayAttribute &arr) { |
| 319 |
return PyArrayAttributeIterator(arr); |
| 320 |
}); |
| 321 |
c.def("__add__", [](PyArrayAttribute arr, py::list extras) { |
| 322 |
std::vector<MlirAttribute> attributes; |
| 323 |
intptr_t numOldElements = mlirArrayAttrGetNumElements(arr); |
| 324 |
attributes.reserve(numOldElements + py::len(extras)); |
| 325 |
for (intptr_t i = 0; i < numOldElements; ++i) |
| 326 |
attributes.push_back(arr.getItem(i)); |
| 327 |
for (py::handle attr : extras) |
| 328 |
attributes.push_back(pyTryCast<PyAttribute>(attr)); |
| 329 |
MlirAttribute arrayAttr = mlirArrayAttrGet( |
| 330 |
arr.getContext()->get(), attributes.size(), attributes.data()); |
| 331 |
return PyArrayAttribute(arr.getContext(), arrayAttr); |
| 332 |
}); |
| 333 |
} |
| 334 |
}; |
| 335 |
|
| 336 |
/// Float Point Attribute subclass - FloatAttr. |
| 337 |
class PyFloatAttribute : public PyConcreteAttribute<PyFloatAttribute> { |
| 338 |
public: |
| 339 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAFloat; |
| 340 |
static constexpr const char *pyClassName = "FloatAttr"; |
| 341 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 342 |
|
| 343 |
static void bindDerived(ClassTy &c) { |
| 344 |
c.def_static( |
| 345 |
"get", |
| 346 |
[](PyType &type, double value, DefaultingPyLocation loc) { |
| 347 |
MlirAttribute attr = mlirFloatAttrDoubleGetChecked(loc, type, value); |
| 348 |
// TODO: Rework error reporting once diagnostic engine is exposed |
| 349 |
// in C API. |
| 350 |
if (mlirAttributeIsNull(attr)) { |
| 351 |
throw SetPyError(PyExc_ValueError, |
| 352 |
Twine("invalid '") + |
| 353 |
py::repr(py::cast(type)).cast<std::string>() + |
| 354 |
"' and expected floating point type."); |
| 355 |
} |
| 356 |
return PyFloatAttribute(type.getContext(), attr); |
| 357 |
}, |
| 358 |
py::arg("type"), py::arg("value"), py::arg("loc") = py::none(), |
| 359 |
"Gets an uniqued float point attribute associated to a type"); |
| 360 |
c.def_static( |
| 361 |
"get_f32", |
| 362 |
[](double value, DefaultingPyMlirContext context) { |
| 363 |
MlirAttribute attr = mlirFloatAttrDoubleGet( |
| 364 |
context->get(), mlirF32TypeGet(context->get()), value); |
| 365 |
return PyFloatAttribute(context->getRef(), attr); |
| 366 |
}, |
| 367 |
py::arg("value"), py::arg("context") = py::none(), |
| 368 |
"Gets an uniqued float point attribute associated to a f32 type"); |
| 369 |
c.def_static( |
| 370 |
"get_f64", |
| 371 |
[](double value, DefaultingPyMlirContext context) { |
| 372 |
MlirAttribute attr = mlirFloatAttrDoubleGet( |
| 373 |
context->get(), mlirF64TypeGet(context->get()), value); |
| 374 |
return PyFloatAttribute(context->getRef(), attr); |
| 375 |
}, |
| 376 |
py::arg("value"), py::arg("context") = py::none(), |
| 377 |
"Gets an uniqued float point attribute associated to a f64 type"); |
| 378 |
c.def_property_readonly( |
| 379 |
"value", |
| 380 |
[](PyFloatAttribute &self) { |
| 381 |
return mlirFloatAttrGetValueDouble(self); |
| 382 |
}, |
| 383 |
"Returns the value of the float point attribute"); |
| 384 |
} |
| 385 |
}; |
| 386 |
|
| 387 |
/// Integer Attribute subclass - IntegerAttr. |
| 388 |
class PyIntegerAttribute : public PyConcreteAttribute<PyIntegerAttribute> { |
| 389 |
public: |
| 390 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAInteger; |
| 391 |
static constexpr const char *pyClassName = "IntegerAttr"; |
| 392 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 393 |
|
| 394 |
static void bindDerived(ClassTy &c) { |
| 395 |
c.def_static( |
| 396 |
"get", |
| 397 |
[](PyType &type, int64_t value) { |
| 398 |
MlirAttribute attr = mlirIntegerAttrGet(type, value); |
| 399 |
return PyIntegerAttribute(type.getContext(), attr); |
| 400 |
}, |
| 401 |
py::arg("type"), py::arg("value"), |
| 402 |
"Gets an uniqued integer attribute associated to a type"); |
| 403 |
c.def_property_readonly( |
| 404 |
"value", |
| 405 |
[](PyIntegerAttribute &self) -> py::int_ { |
| 406 |
MlirType type = mlirAttributeGetType(self); |
| 407 |
if (mlirTypeIsAIndex(type) || mlirIntegerTypeIsSignless(type)) |
| 408 |
return mlirIntegerAttrGetValueInt(self); |
| 409 |
if (mlirIntegerTypeIsSigned(type)) |
| 410 |
return mlirIntegerAttrGetValueSInt(self); |
| 411 |
return mlirIntegerAttrGetValueUInt(self); |
| 412 |
}, |
| 413 |
"Returns the value of the integer attribute"); |
| 414 |
} |
| 415 |
}; |
| 416 |
|
| 417 |
/// Bool Attribute subclass - BoolAttr. |
| 418 |
class PyBoolAttribute : public PyConcreteAttribute<PyBoolAttribute> { |
| 419 |
public: |
| 420 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsABool; |
| 421 |
static constexpr const char *pyClassName = "BoolAttr"; |
| 422 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 423 |
|
| 424 |
static void bindDerived(ClassTy &c) { |
| 425 |
c.def_static( |
| 426 |
"get", |
| 427 |
[](bool value, DefaultingPyMlirContext context) { |
| 428 |
MlirAttribute attr = mlirBoolAttrGet(context->get(), value); |
| 429 |
return PyBoolAttribute(context->getRef(), attr); |
| 430 |
}, |
| 431 |
py::arg("value"), py::arg("context") = py::none(), |
| 432 |
"Gets an uniqued bool attribute"); |
| 433 |
c.def_property_readonly( |
| 434 |
"value", |
| 435 |
[](PyBoolAttribute &self) { return mlirBoolAttrGetValue(self); }, |
| 436 |
"Returns the value of the bool attribute"); |
| 437 |
} |
| 438 |
}; |
| 439 |
|
| 440 |
class PyFlatSymbolRefAttribute |
| 441 |
: public PyConcreteAttribute<PyFlatSymbolRefAttribute> { |
| 442 |
public: |
| 443 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAFlatSymbolRef; |
| 444 |
static constexpr const char *pyClassName = "FlatSymbolRefAttr"; |
| 445 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 446 |
|
| 447 |
static void bindDerived(ClassTy &c) { |
| 448 |
c.def_static( |
| 449 |
"get", |
| 450 |
[](std::string value, DefaultingPyMlirContext context) { |
| 451 |
MlirAttribute attr = |
| 452 |
mlirFlatSymbolRefAttrGet(context->get(), toMlirStringRef(value)); |
| 453 |
return PyFlatSymbolRefAttribute(context->getRef(), attr); |
| 454 |
}, |
| 455 |
py::arg("value"), py::arg("context") = py::none(), |
| 456 |
"Gets a uniqued FlatSymbolRef attribute"); |
| 457 |
c.def_property_readonly( |
| 458 |
"value", |
| 459 |
[](PyFlatSymbolRefAttribute &self) { |
| 460 |
MlirStringRef stringRef = mlirFlatSymbolRefAttrGetValue(self); |
| 461 |
return py::str(stringRef.data, stringRef.length); |
| 462 |
}, |
| 463 |
"Returns the value of the FlatSymbolRef attribute as a string"); |
| 464 |
} |
| 465 |
}; |
| 466 |
|
| 467 |
class PyOpaqueAttribute : public PyConcreteAttribute<PyOpaqueAttribute> { |
| 468 |
public: |
| 469 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAOpaque; |
| 470 |
static constexpr const char *pyClassName = "OpaqueAttr"; |
| 471 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 472 |
|
| 473 |
static void bindDerived(ClassTy &c) { |
| 474 |
c.def_static( |
| 475 |
"get", |
| 476 |
[](std::string dialectNamespace, py::buffer buffer, PyType &type, |
| 477 |
DefaultingPyMlirContext context) { |
| 478 |
const py::buffer_info bufferInfo = buffer.request(); |
| 479 |
intptr_t bufferSize = bufferInfo.size; |
| 480 |
MlirAttribute attr = mlirOpaqueAttrGet( |
| 481 |
context->get(), toMlirStringRef(dialectNamespace), bufferSize, |
| 482 |
static_cast<char *>(bufferInfo.ptr), type); |
| 483 |
return PyOpaqueAttribute(context->getRef(), attr); |
| 484 |
}, |
| 485 |
py::arg("dialect_namespace"), py::arg("buffer"), py::arg("type"), |
| 486 |
py::arg("context") = py::none(), "Gets an Opaque attribute."); |
| 487 |
c.def_property_readonly( |
| 488 |
"dialect_namespace", |
| 489 |
[](PyOpaqueAttribute &self) { |
| 490 |
MlirStringRef stringRef = mlirOpaqueAttrGetDialectNamespace(self); |
| 491 |
return py::str(stringRef.data, stringRef.length); |
| 492 |
}, |
| 493 |
"Returns the dialect namespace for the Opaque attribute as a string"); |
| 494 |
c.def_property_readonly( |
| 495 |
"data", |
| 496 |
[](PyOpaqueAttribute &self) { |
| 497 |
MlirStringRef stringRef = mlirOpaqueAttrGetData(self); |
| 498 |
return py::str(stringRef.data, stringRef.length); |
| 499 |
}, |
| 500 |
"Returns the data for the Opaqued attributes as a string"); |
| 501 |
} |
| 502 |
}; |
| 503 |
|
| 504 |
class PyStringAttribute : public PyConcreteAttribute<PyStringAttribute> { |
| 505 |
public: |
| 506 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAString; |
| 507 |
static constexpr const char *pyClassName = "StringAttr"; |
| 508 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 509 |
|
| 510 |
static void bindDerived(ClassTy &c) { |
| 511 |
c.def_static( |
| 512 |
"get", |
| 513 |
[](std::string value, DefaultingPyMlirContext context) { |
| 514 |
MlirAttribute attr = |
| 515 |
mlirStringAttrGet(context->get(), toMlirStringRef(value)); |
| 516 |
return PyStringAttribute(context->getRef(), attr); |
| 517 |
}, |
| 518 |
py::arg("value"), py::arg("context") = py::none(), |
| 519 |
"Gets a uniqued string attribute"); |
| 520 |
c.def_static( |
| 521 |
"get_typed", |
| 522 |
[](PyType &type, std::string value) { |
| 523 |
MlirAttribute attr = |
| 524 |
mlirStringAttrTypedGet(type, toMlirStringRef(value)); |
| 525 |
return PyStringAttribute(type.getContext(), attr); |
| 526 |
}, |
| 527 |
py::arg("type"), py::arg("value"), |
| 528 |
"Gets a uniqued string attribute associated to a type"); |
| 529 |
c.def_property_readonly( |
| 530 |
"value", |
| 531 |
[](PyStringAttribute &self) { |
| 532 |
MlirStringRef stringRef = mlirStringAttrGetValue(self); |
| 533 |
return py::str(stringRef.data, stringRef.length); |
| 534 |
}, |
| 535 |
"Returns the value of the string attribute"); |
| 536 |
} |
| 537 |
}; |
| 538 |
|
| 539 |
// TODO: Support construction of string elements. |
| 540 |
class PyDenseElementsAttribute |
| 541 |
: public PyConcreteAttribute<PyDenseElementsAttribute> { |
| 542 |
public: |
| 543 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseElements; |
| 544 |
static constexpr const char *pyClassName = "DenseElementsAttr"; |
| 545 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 546 |
|
| 547 |
static PyDenseElementsAttribute |
| 548 |
getFromBuffer(py::buffer array, bool signless, |
| 549 |
std::optional<PyType> explicitType, |
| 550 |
std::optional<std::vector<int64_t>> explicitShape, |
| 551 |
DefaultingPyMlirContext contextWrapper) { |
| 552 |
// Request a contiguous view. In exotic cases, this will cause a copy. |
| 553 |
int flags = PyBUF_C_CONTIGUOUS | PyBUF_FORMAT; |
| 554 |
Py_buffer *view = new Py_buffer(); |
| 555 |
if (PyObject_GetBuffer(array.ptr(), view, flags) != 0) { |
| 556 |
delete view; |
| 557 |
throw py::error_already_set(); |
| 558 |
} |
| 559 |
py::buffer_info arrayInfo(view); |
| 560 |
SmallVector<int64_t> shape; |
| 561 |
if (explicitShape) { |
| 562 |
shape.append(explicitShape->begin(), explicitShape->end()); |
| 563 |
} else { |
| 564 |
shape.append(arrayInfo.shape.begin(), |
| 565 |
arrayInfo.shape.begin() + arrayInfo.ndim); |
| 566 |
} |
| 567 |
|
| 568 |
MlirAttribute encodingAttr = mlirAttributeGetNull(); |
| 569 |
MlirContext context = contextWrapper->get(); |
| 570 |
|
| 571 |
// Detect format codes that are suitable for bulk loading. This includes |
| 572 |
// all byte aligned integer and floating point types up to 8 bytes. |
| 573 |
// Notably, this excludes, bool (which needs to be bit-packed) and |
| 574 |
// other exotics which do not have a direct representation in the buffer |
| 575 |
// protocol (i.e. complex, etc). |
| 576 |
std::optional<MlirType> bulkLoadElementType; |
| 577 |
if (explicitType) { |
| 578 |
bulkLoadElementType = *explicitType; |
| 579 |
} else if (arrayInfo.format == "f") { |
| 580 |
// f32 |
| 581 |
assert(arrayInfo.itemsize == 4 && "mismatched array itemsize"); |
| 582 |
bulkLoadElementType = mlirF32TypeGet(context); |
| 583 |
} else if (arrayInfo.format == "d") { |
| 584 |
// f64 |
| 585 |
assert(arrayInfo.itemsize == 8 && "mismatched array itemsize"); |
| 586 |
bulkLoadElementType = mlirF64TypeGet(context); |
| 587 |
} else if (arrayInfo.format == "e") { |
| 588 |
// f16 |
| 589 |
assert(arrayInfo.itemsize == 2 && "mismatched array itemsize"); |
| 590 |
bulkLoadElementType = mlirF16TypeGet(context); |
| 591 |
} else if (isSignedIntegerFormat(arrayInfo.format)) { |
| 592 |
if (arrayInfo.itemsize == 4) { |
| 593 |
// i32 |
| 594 |
bulkLoadElementType = signless ? mlirIntegerTypeGet(context, 32) |
| 595 |
: mlirIntegerTypeSignedGet(context, 32); |
| 596 |
} else if (arrayInfo.itemsize == 8) { |
| 597 |
// i64 |
| 598 |
bulkLoadElementType = signless ? mlirIntegerTypeGet(context, 64) |
| 599 |
: mlirIntegerTypeSignedGet(context, 64); |
| 600 |
} else if (arrayInfo.itemsize == 1) { |
| 601 |
// i8 |
| 602 |
bulkLoadElementType = signless ? mlirIntegerTypeGet(context, 8) |
| 603 |
: mlirIntegerTypeSignedGet(context, 8); |
| 604 |
} else if (arrayInfo.itemsize == 2) { |
| 605 |
// i16 |
| 606 |
bulkLoadElementType = signless ? mlirIntegerTypeGet(context, 16) |
| 607 |
: mlirIntegerTypeSignedGet(context, 16); |
| 608 |
} |
| 609 |
} else if (isUnsignedIntegerFormat(arrayInfo.format)) { |
| 610 |
if (arrayInfo.itemsize == 4) { |
| 611 |
// unsigned i32 |
| 612 |
bulkLoadElementType = signless |
| 613 |
? mlirIntegerTypeGet(context, 32) |
| 614 |
: mlirIntegerTypeUnsignedGet(context, 32); |
| 615 |
} else if (arrayInfo.itemsize == 8) { |
| 616 |
// unsigned i64 |
| 617 |
bulkLoadElementType = signless |
| 618 |
? mlirIntegerTypeGet(context, 64) |
| 619 |
: mlirIntegerTypeUnsignedGet(context, 64); |
| 620 |
} else if (arrayInfo.itemsize == 1) { |
| 621 |
// i8 |
| 622 |
bulkLoadElementType = signless ? mlirIntegerTypeGet(context, 8) |
| 623 |
: mlirIntegerTypeUnsignedGet(context, 8); |
| 624 |
} else if (arrayInfo.itemsize == 2) { |
| 625 |
// i16 |
| 626 |
bulkLoadElementType = signless |
| 627 |
? mlirIntegerTypeGet(context, 16) |
| 628 |
: mlirIntegerTypeUnsignedGet(context, 16); |
| 629 |
} |
| 630 |
} |
| 631 |
if (bulkLoadElementType) { |
| 632 |
auto shapedType = mlirRankedTensorTypeGet( |
| 633 |
shape.size(), shape.data(), *bulkLoadElementType, encodingAttr); |
| 634 |
size_t rawBufferSize = arrayInfo.size * arrayInfo.itemsize; |
| 635 |
MlirAttribute attr = mlirDenseElementsAttrRawBufferGet( |
| 636 |
shapedType, rawBufferSize, arrayInfo.ptr); |
| 637 |
if (mlirAttributeIsNull(attr)) { |
| 638 |
throw std::invalid_argument( |
| 639 |
"DenseElementsAttr could not be constructed from the given buffer. " |
| 640 |
"This may mean that the Python buffer layout does not match that " |
| 641 |
"MLIR expected layout and is a bug."); |
| 642 |
} |
| 643 |
return PyDenseElementsAttribute(contextWrapper->getRef(), attr); |
| 644 |
} |
| 645 |
|
| 646 |
throw std::invalid_argument( |
| 647 |
std::string("unimplemented array format conversion from format: ") + |
| 648 |
arrayInfo.format); |
| 649 |
} |
| 650 |
|
| 651 |
static PyDenseElementsAttribute getSplat(const PyType &shapedType, |
| 652 |
PyAttribute &elementAttr) { |
| 653 |
auto contextWrapper = |
| 654 |
PyMlirContext::forContext(mlirTypeGetContext(shapedType)); |
| 655 |
if (!mlirAttributeIsAInteger(elementAttr) && |
| 656 |
!mlirAttributeIsAFloat(elementAttr)) { |
| 657 |
std::string message = "Illegal element type for DenseElementsAttr: "; |
| 658 |
message.append(py::repr(py::cast(elementAttr))); |
| 659 |
throw SetPyError(PyExc_ValueError, message); |
| 660 |
} |
| 661 |
if (!mlirTypeIsAShaped(shapedType) || |
| 662 |
!mlirShapedTypeHasStaticShape(shapedType)) { |
| 663 |
std::string message = |
| 664 |
"Expected a static ShapedType for the shaped_type parameter: "; |
| 665 |
message.append(py::repr(py::cast(shapedType))); |
| 666 |
throw SetPyError(PyExc_ValueError, message); |
| 667 |
} |
| 668 |
MlirType shapedElementType = mlirShapedTypeGetElementType(shapedType); |
| 669 |
MlirType attrType = mlirAttributeGetType(elementAttr); |
| 670 |
if (!mlirTypeEqual(shapedElementType, attrType)) { |
| 671 |
std::string message = |
| 672 |
"Shaped element type and attribute type must be equal: shaped="; |
| 673 |
message.append(py::repr(py::cast(shapedType))); |
| 674 |
message.append(", element="); |
| 675 |
message.append(py::repr(py::cast(elementAttr))); |
| 676 |
throw SetPyError(PyExc_ValueError, message); |
| 677 |
} |
| 678 |
|
| 679 |
MlirAttribute elements = |
| 680 |
mlirDenseElementsAttrSplatGet(shapedType, elementAttr); |
| 681 |
return PyDenseElementsAttribute(contextWrapper->getRef(), elements); |
| 682 |
} |
| 683 |
|
| 684 |
intptr_t dunderLen() { return mlirElementsAttrGetNumElements(*this); } |
| 685 |
|
| 686 |
py::buffer_info accessBuffer() { |
| 687 |
if (mlirDenseElementsAttrIsSplat(*this)) { |
| 688 |
// TODO: Currently crashes the program. |
| 689 |
// Reported as https://github.com/pybind/pybind11/issues/3336 |
| 690 |
throw std::invalid_argument( |
| 691 |
"unsupported data type for conversion to Python buffer"); |
| 692 |
} |
| 693 |
|
| 694 |
MlirType shapedType = mlirAttributeGetType(*this); |
| 695 |
MlirType elementType = mlirShapedTypeGetElementType(shapedType); |
| 696 |
std::string format; |
| 697 |
|
| 698 |
if (mlirTypeIsAF32(elementType)) { |
| 699 |
// f32 |
| 700 |
return bufferInfo<float>(shapedType); |
| 701 |
} |
| 702 |
if (mlirTypeIsAF64(elementType)) { |
| 703 |
// f64 |
| 704 |
return bufferInfo<double>(shapedType); |
| 705 |
} |
| 706 |
if (mlirTypeIsAF16(elementType)) { |
| 707 |
// f16 |
| 708 |
return bufferInfo<uint16_t>(shapedType, "e"); |
| 709 |
} |
| 710 |
if (mlirTypeIsAInteger(elementType) && |
| 711 |
mlirIntegerTypeGetWidth(elementType) == 32) { |
| 712 |
if (mlirIntegerTypeIsSignless(elementType) || |
| 713 |
mlirIntegerTypeIsSigned(elementType)) { |
| 714 |
// i32 |
| 715 |
return bufferInfo<int32_t>(shapedType); |
| 716 |
} |
| 717 |
if (mlirIntegerTypeIsUnsigned(elementType)) { |
| 718 |
// unsigned i32 |
| 719 |
return bufferInfo<uint32_t>(shapedType); |
| 720 |
} |
| 721 |
} else if (mlirTypeIsAInteger(elementType) && |
| 722 |
mlirIntegerTypeGetWidth(elementType) == 64) { |
| 723 |
if (mlirIntegerTypeIsSignless(elementType) || |
| 724 |
mlirIntegerTypeIsSigned(elementType)) { |
| 725 |
// i64 |
| 726 |
return bufferInfo<int64_t>(shapedType); |
| 727 |
} |
| 728 |
if (mlirIntegerTypeIsUnsigned(elementType)) { |
| 729 |
// unsigned i64 |
| 730 |
return bufferInfo<uint64_t>(shapedType); |
| 731 |
} |
| 732 |
} else if (mlirTypeIsAInteger(elementType) && |
| 733 |
mlirIntegerTypeGetWidth(elementType) == 8) { |
| 734 |
if (mlirIntegerTypeIsSignless(elementType) || |
| 735 |
mlirIntegerTypeIsSigned(elementType)) { |
| 736 |
// i8 |
| 737 |
return bufferInfo<int8_t>(shapedType); |
| 738 |
} |
| 739 |
if (mlirIntegerTypeIsUnsigned(elementType)) { |
| 740 |
// unsigned i8 |
| 741 |
return bufferInfo<uint8_t>(shapedType); |
| 742 |
} |
| 743 |
} else if (mlirTypeIsAInteger(elementType) && |
| 744 |
mlirIntegerTypeGetWidth(elementType) == 16) { |
| 745 |
if (mlirIntegerTypeIsSignless(elementType) || |
| 746 |
mlirIntegerTypeIsSigned(elementType)) { |
| 747 |
// i16 |
| 748 |
return bufferInfo<int16_t>(shapedType); |
| 749 |
} |
| 750 |
if (mlirIntegerTypeIsUnsigned(elementType)) { |
| 751 |
// unsigned i16 |
| 752 |
return bufferInfo<uint16_t>(shapedType); |
| 753 |
} |
| 754 |
} |
| 755 |
|
| 756 |
// TODO: Currently crashes the program. |
| 757 |
// Reported as https://github.com/pybind/pybind11/issues/3336 |
| 758 |
throw std::invalid_argument( |
| 759 |
"unsupported data type for conversion to Python buffer"); |
| 760 |
} |
| 761 |
|
| 762 |
static void bindDerived(ClassTy &c) { |
| 763 |
c.def("__len__", &PyDenseElementsAttribute::dunderLen) |
| 764 |
.def_static("get", PyDenseElementsAttribute::getFromBuffer, |
| 765 |
py::arg("array"), py::arg("signless") = true, |
| 766 |
py::arg("type") = py::none(), py::arg("shape") = py::none(), |
| 767 |
py::arg("context") = py::none(), |
| 768 |
kDenseElementsAttrGetDocstring) |
| 769 |
.def_static("get_splat", PyDenseElementsAttribute::getSplat, |
| 770 |
py::arg("shaped_type"), py::arg("element_attr"), |
| 771 |
"Gets a DenseElementsAttr where all values are the same") |
| 772 |
.def_property_readonly("is_splat", |
| 773 |
[](PyDenseElementsAttribute &self) -> bool { |
| 774 |
return mlirDenseElementsAttrIsSplat(self); |
| 775 |
}) |
| 776 |
.def_buffer(&PyDenseElementsAttribute::accessBuffer); |
| 777 |
} |
| 778 |
|
| 779 |
private: |
| 780 |
static bool isUnsignedIntegerFormat(const std::string &format) { |
| 781 |
if (format.empty()) |
| 782 |
return false; |
| 783 |
char code = format[0]; |
| 784 |
return code == 'I' || code == 'B' || code == 'H' || code == 'L' || |
| 785 |
code == 'Q'; |
| 786 |
} |
| 787 |
|
| 788 |
static bool isSignedIntegerFormat(const std::string &format) { |
| 789 |
if (format.empty()) |
| 790 |
return false; |
| 791 |
char code = format[0]; |
| 792 |
return code == 'i' || code == 'b' || code == 'h' || code == 'l' || |
| 793 |
code == 'q'; |
| 794 |
} |
| 795 |
|
| 796 |
template <typename Type> |
| 797 |
py::buffer_info bufferInfo(MlirType shapedType, |
| 798 |
const char *explicitFormat = nullptr) { |
| 799 |
intptr_t rank = mlirShapedTypeGetRank(shapedType); |
| 800 |
// Prepare the data for the buffer_info. |
| 801 |
// Buffer is configured for read-only access below. |
| 802 |
Type *data = static_cast<Type *>( |
| 803 |
const_cast<void *>(mlirDenseElementsAttrGetRawData(*this))); |
| 804 |
// Prepare the shape for the buffer_info. |
| 805 |
SmallVector<intptr_t, 4> shape; |
| 806 |
for (intptr_t i = 0; i < rank; ++i) |
| 807 |
shape.push_back(mlirShapedTypeGetDimSize(shapedType, i)); |
| 808 |
// Prepare the strides for the buffer_info. |
| 809 |
SmallVector<intptr_t, 4> strides; |
| 810 |
intptr_t strideFactor = 1; |
| 811 |
for (intptr_t i = 1; i < rank; ++i) { |
| 812 |
strideFactor = 1; |
| 813 |
for (intptr_t j = i; j < rank; ++j) { |
| 814 |
strideFactor *= mlirShapedTypeGetDimSize(shapedType, j); |
| 815 |
} |
| 816 |
strides.push_back(sizeof(Type) * strideFactor); |
| 817 |
} |
| 818 |
strides.push_back(sizeof(Type)); |
| 819 |
std::string format; |
| 820 |
if (explicitFormat) { |
| 821 |
format = explicitFormat; |
| 822 |
} else { |
| 823 |
format = py::format_descriptor<Type>::format(); |
| 824 |
} |
| 825 |
return py::buffer_info(data, sizeof(Type), format, rank, shape, strides, |
| 826 |
/*readonly=*/true); |
| 827 |
} |
| 828 |
}; // namespace |
| 829 |
|
| 830 |
/// Refinement of the PyDenseElementsAttribute for attributes containing integer |
| 831 |
/// (and boolean) values. Supports element access. |
| 832 |
class PyDenseIntElementsAttribute |
| 833 |
: public PyConcreteAttribute<PyDenseIntElementsAttribute, |
| 834 |
PyDenseElementsAttribute> { |
| 835 |
public: |
| 836 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseIntElements; |
| 837 |
static constexpr const char *pyClassName = "DenseIntElementsAttr"; |
| 838 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 839 |
|
| 840 |
/// Returns the element at the given linear position. Asserts if the index is |
| 841 |
/// out of range. |
| 842 |
py::int_ dunderGetItem(intptr_t pos) { |
| 843 |
if (pos < 0 || pos >= dunderLen()) { |
| 844 |
throw SetPyError(PyExc_IndexError, |
| 845 |
"attempt to access out of bounds element"); |
| 846 |
} |
| 847 |
|
| 848 |
MlirType type = mlirAttributeGetType(*this); |
| 849 |
type = mlirShapedTypeGetElementType(type); |
| 850 |
assert(mlirTypeIsAInteger(type) && |
| 851 |
"expected integer element type in dense int elements attribute"); |
| 852 |
// Dispatch element extraction to an appropriate C function based on the |
| 853 |
// elemental type of the attribute. py::int_ is implicitly constructible |
| 854 |
// from any C++ integral type and handles bitwidth correctly. |
| 855 |
// TODO: consider caching the type properties in the constructor to avoid |
| 856 |
// querying them on each element access. |
| 857 |
unsigned width = mlirIntegerTypeGetWidth(type); |
| 858 |
bool isUnsigned = mlirIntegerTypeIsUnsigned(type); |
| 859 |
if (isUnsigned) { |
| 860 |
if (width == 1) { |
| 861 |
return mlirDenseElementsAttrGetBoolValue(*this, pos); |
| 862 |
} |
| 863 |
if (width == 8) { |
| 864 |
return mlirDenseElementsAttrGetUInt8Value(*this, pos); |
| 865 |
} |
| 866 |
if (width == 16) { |
| 867 |
return mlirDenseElementsAttrGetUInt16Value(*this, pos); |
| 868 |
} |
| 869 |
if (width == 32) { |
| 870 |
return mlirDenseElementsAttrGetUInt32Value(*this, pos); |
| 871 |
} |
| 872 |
if (width == 64) { |
| 873 |
return mlirDenseElementsAttrGetUInt64Value(*this, pos); |
| 874 |
} |
| 875 |
} else { |
| 876 |
if (width == 1) { |
| 877 |
return mlirDenseElementsAttrGetBoolValue(*this, pos); |
| 878 |
} |
| 879 |
if (width == 8) { |
| 880 |
return mlirDenseElementsAttrGetInt8Value(*this, pos); |
| 881 |
} |
| 882 |
if (width == 16) { |
| 883 |
return mlirDenseElementsAttrGetInt16Value(*this, pos); |
| 884 |
} |
| 885 |
if (width == 32) { |
| 886 |
return mlirDenseElementsAttrGetInt32Value(*this, pos); |
| 887 |
} |
| 888 |
if (width == 64) { |
| 889 |
return mlirDenseElementsAttrGetInt64Value(*this, pos); |
| 890 |
} |
| 891 |
} |
| 892 |
throw SetPyError(PyExc_TypeError, "Unsupported integer type"); |
| 893 |
} |
| 894 |
|
| 895 |
static void bindDerived(ClassTy &c) { |
| 896 |
c.def("__getitem__", &PyDenseIntElementsAttribute::dunderGetItem); |
| 897 |
} |
| 898 |
}; |
| 899 |
|
| 900 |
class PyDictAttribute : public PyConcreteAttribute<PyDictAttribute> { |
| 901 |
public: |
| 902 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADictionary; |
| 903 |
static constexpr const char *pyClassName = "DictAttr"; |
| 904 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 905 |
|
| 906 |
intptr_t dunderLen() { return mlirDictionaryAttrGetNumElements(*this); } |
| 907 |
|
| 908 |
bool dunderContains(const std::string &name) { |
| 909 |
return !mlirAttributeIsNull( |
| 910 |
mlirDictionaryAttrGetElementByName(*this, toMlirStringRef(name))); |
| 911 |
} |
| 912 |
|
| 913 |
static void bindDerived(ClassTy &c) { |
| 914 |
c.def("__contains__", &PyDictAttribute::dunderContains); |
| 915 |
c.def("__len__", &PyDictAttribute::dunderLen); |
| 916 |
c.def_static( |
| 917 |
"get", |
| 918 |
[](py::dict attributes, DefaultingPyMlirContext context) { |
| 919 |
SmallVector<MlirNamedAttribute> mlirNamedAttributes; |
| 920 |
mlirNamedAttributes.reserve(attributes.size()); |
| 921 |
for (auto &it : attributes) { |
| 922 |
auto &mlirAttr = it.second.cast<PyAttribute &>(); |
| 923 |
auto name = it.first.cast<std::string>(); |
| 924 |
mlirNamedAttributes.push_back(mlirNamedAttributeGet( |
| 925 |
mlirIdentifierGet(mlirAttributeGetContext(mlirAttr), |
| 926 |
toMlirStringRef(name)), |
| 927 |
mlirAttr)); |
| 928 |
} |
| 929 |
MlirAttribute attr = |
| 930 |
mlirDictionaryAttrGet(context->get(), mlirNamedAttributes.size(), |
| 931 |
mlirNamedAttributes.data()); |
| 932 |
return PyDictAttribute(context->getRef(), attr); |
| 933 |
}, |
| 934 |
py::arg("value") = py::dict(), py::arg("context") = py::none(), |
| 935 |
"Gets an uniqued dict attribute"); |
| 936 |
c.def("__getitem__", [](PyDictAttribute &self, const std::string &name) { |
| 937 |
MlirAttribute attr = |
| 938 |
mlirDictionaryAttrGetElementByName(self, toMlirStringRef(name)); |
| 939 |
if (mlirAttributeIsNull(attr)) { |
| 940 |
throw SetPyError(PyExc_KeyError, |
| 941 |
"attempt to access a non-existent attribute"); |
| 942 |
} |
| 943 |
return PyAttribute(self.getContext(), attr); |
| 944 |
}); |
| 945 |
c.def("__getitem__", [](PyDictAttribute &self, intptr_t index) { |
| 946 |
if (index < 0 || index >= self.dunderLen()) { |
| 947 |
throw SetPyError(PyExc_IndexError, |
| 948 |
"attempt to access out of bounds attribute"); |
| 949 |
} |
| 950 |
MlirNamedAttribute namedAttr = mlirDictionaryAttrGetElement(self, index); |
| 951 |
return PyNamedAttribute( |
| 952 |
namedAttr.attribute, |
| 953 |
std::string(mlirIdentifierStr(namedAttr.name).data)); |
| 954 |
}); |
| 955 |
} |
| 956 |
}; |
| 957 |
|
| 958 |
/// Refinement of PyDenseElementsAttribute for attributes containing |
| 959 |
/// floating-point values. Supports element access. |
| 960 |
class PyDenseFPElementsAttribute |
| 961 |
: public PyConcreteAttribute<PyDenseFPElementsAttribute, |
| 962 |
PyDenseElementsAttribute> { |
| 963 |
public: |
| 964 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseFPElements; |
| 965 |
static constexpr const char *pyClassName = "DenseFPElementsAttr"; |
| 966 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 967 |
|
| 968 |
py::float_ dunderGetItem(intptr_t pos) { |
| 969 |
if (pos < 0 || pos >= dunderLen()) { |
| 970 |
throw SetPyError(PyExc_IndexError, |
| 971 |
"attempt to access out of bounds element"); |
| 972 |
} |
| 973 |
|
| 974 |
MlirType type = mlirAttributeGetType(*this); |
| 975 |
type = mlirShapedTypeGetElementType(type); |
| 976 |
// Dispatch element extraction to an appropriate C function based on the |
| 977 |
// elemental type of the attribute. py::float_ is implicitly constructible |
| 978 |
// from float and double. |
| 979 |
// TODO: consider caching the type properties in the constructor to avoid |
| 980 |
// querying them on each element access. |
| 981 |
if (mlirTypeIsAF32(type)) { |
| 982 |
return mlirDenseElementsAttrGetFloatValue(*this, pos); |
| 983 |
} |
| 984 |
if (mlirTypeIsAF64(type)) { |
| 985 |
return mlirDenseElementsAttrGetDoubleValue(*this, pos); |
| 986 |
} |
| 987 |
throw SetPyError(PyExc_TypeError, "Unsupported floating-point type"); |
| 988 |
} |
| 989 |
|
| 990 |
static void bindDerived(ClassTy &c) { |
| 991 |
c.def("__getitem__", &PyDenseFPElementsAttribute::dunderGetItem); |
| 992 |
} |
| 993 |
}; |
| 994 |
|
| 995 |
class PyTypeAttribute : public PyConcreteAttribute<PyTypeAttribute> { |
| 996 |
public: |
| 997 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAType; |
| 998 |
static constexpr const char *pyClassName = "TypeAttr"; |
| 999 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 1000 |
|
| 1001 |
static void bindDerived(ClassTy &c) { |
| 1002 |
c.def_static( |
| 1003 |
"get", |
| 1004 |
[](PyType value, DefaultingPyMlirContext context) { |
| 1005 |
MlirAttribute attr = mlirTypeAttrGet(value.get()); |
| 1006 |
return PyTypeAttribute(context->getRef(), attr); |
| 1007 |
}, |
| 1008 |
py::arg("value"), py::arg("context") = py::none(), |
| 1009 |
"Gets a uniqued Type attribute"); |
| 1010 |
c.def_property_readonly("value", [](PyTypeAttribute &self) { |
| 1011 |
return PyType(self.getContext()->getRef(), |
| 1012 |
mlirTypeAttrGetValue(self.get())); |
| 1013 |
}); |
| 1014 |
} |
| 1015 |
}; |
| 1016 |
|
| 1017 |
/// Unit Attribute subclass. Unit attributes don't have values. |
| 1018 |
class PyUnitAttribute : public PyConcreteAttribute<PyUnitAttribute> { |
| 1019 |
public: |
| 1020 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAUnit; |
| 1021 |
static constexpr const char *pyClassName = "UnitAttr"; |
| 1022 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 1023 |
|
| 1024 |
static void bindDerived(ClassTy &c) { |
| 1025 |
c.def_static( |
| 1026 |
"get", |
| 1027 |
[](DefaultingPyMlirContext context) { |
| 1028 |
return PyUnitAttribute(context->getRef(), |
| 1029 |
mlirUnitAttrGet(context->get())); |
| 1030 |
}, |
| 1031 |
py::arg("context") = py::none(), "Create a Unit attribute."); |
| 1032 |
} |
| 1033 |
}; |
| 1034 |
|
| 1035 |
/// Strided layout attribute subclass. |
| 1036 |
class PyStridedLayoutAttribute |
| 1037 |
: public PyConcreteAttribute<PyStridedLayoutAttribute> { |
| 1038 |
public: |
| 1039 |
static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAStridedLayout; |
| 1040 |
static constexpr const char *pyClassName = "StridedLayoutAttr"; |
| 1041 |
using PyConcreteAttribute::PyConcreteAttribute; |
| 1042 |
|
| 1043 |
static void bindDerived(ClassTy &c) { |
| 1044 |
c.def_static( |
| 1045 |
"get", |
| 1046 |
[](int64_t offset, const std::vector<int64_t> strides, |
| 1047 |
DefaultingPyMlirContext ctx) { |
| 1048 |
MlirAttribute attr = mlirStridedLayoutAttrGet( |
| 1049 |
ctx->get(), offset, strides.size(), strides.data()); |
| 1050 |
return PyStridedLayoutAttribute(ctx->getRef(), attr); |
| 1051 |
}, |
| 1052 |
py::arg("offset"), py::arg("strides"), py::arg("context") = py::none(), |
| 1053 |
"Gets a strided layout attribute."); |
| 1054 |
c.def_static( |
| 1055 |
"get_fully_dynamic", |
| 1056 |
[](int64_t rank, DefaultingPyMlirContext ctx) { |
| 1057 |
auto dynamic = mlirShapedTypeGetDynamicStrideOrOffset(); |
| 1058 |
std::vector<int64_t> strides(rank); |
| 1059 |
std::fill(strides.begin(), strides.end(), dynamic); |
| 1060 |
MlirAttribute attr = mlirStridedLayoutAttrGet( |
| 1061 |
ctx->get(), dynamic, strides.size(), strides.data()); |
| 1062 |
return PyStridedLayoutAttribute(ctx->getRef(), attr); |
| 1063 |
}, |
| 1064 |
py::arg("rank"), py::arg("context") = py::none(), |
| 1065 |
"Gets a strided layout attribute with dynamic offset and strides of a " |
| 1066 |
"given rank."); |
| 1067 |
c.def_property_readonly( |
| 1068 |
"offset", |
| 1069 |
[](PyStridedLayoutAttribute &self) { |
| 1070 |
return mlirStridedLayoutAttrGetOffset(self); |
| 1071 |
}, |
| 1072 |
"Returns the value of the float point attribute"); |
| 1073 |
c.def_property_readonly( |
| 1074 |
"strides", |
| 1075 |
[](PyStridedLayoutAttribute &self) { |
| 1076 |
intptr_t size = mlirStridedLayoutAttrGetNumStrides(self); |
| 1077 |
std::vector<int64_t> strides(size); |
| 1078 |
for (intptr_t i = 0; i < size; i++) { |
| 1079 |
strides[i] = mlirStridedLayoutAttrGetStride(self, i); |
| 1080 |
} |
| 1081 |
return strides; |
| 1082 |
}, |
| 1083 |
"Returns the value of the float point attribute"); |
| 1084 |
} |
| 1085 |
}; |
| 1086 |
|
| 1087 |
} // namespace |
| 1088 |
|
| 1089 |
void mlir::python::populateIRAttributes(py::module &m) { |
| 1090 |
PyAffineMapAttribute::bind(m); |
| 1091 |
|
| 1092 |
PyDenseBoolArrayAttribute::bind(m); |
| 1093 |
PyDenseBoolArrayAttribute::PyDenseArrayIterator::bind(m); |
| 1094 |
PyDenseI8ArrayAttribute::bind(m); |
| 1095 |
PyDenseI8ArrayAttribute::PyDenseArrayIterator::bind(m); |
| 1096 |
PyDenseI16ArrayAttribute::bind(m); |
| 1097 |
PyDenseI16ArrayAttribute::PyDenseArrayIterator::bind(m); |
| 1098 |
PyDenseI32ArrayAttribute::bind(m); |
| 1099 |
PyDenseI32ArrayAttribute::PyDenseArrayIterator::bind(m); |
| 1100 |
PyDenseI64ArrayAttribute::bind(m); |
| 1101 |
PyDenseI64ArrayAttribute::PyDenseArrayIterator::bind(m); |
| 1102 |
PyDenseF32ArrayAttribute::bind(m); |
| 1103 |
PyDenseF32ArrayAttribute::PyDenseArrayIterator::bind(m); |
| 1104 |
PyDenseF64ArrayAttribute::bind(m); |
| 1105 |
PyDenseF64ArrayAttribute::PyDenseArrayIterator::bind(m); |
| 1106 |
|
| 1107 |
PyArrayAttribute::bind(m); |
| 1108 |
PyArrayAttribute::PyArrayAttributeIterator::bind(m); |
| 1109 |
PyBoolAttribute::bind(m); |
| 1110 |
PyDenseElementsAttribute::bind(m); |
| 1111 |
PyDenseFPElementsAttribute::bind(m); |
| 1112 |
PyDenseIntElementsAttribute::bind(m); |
| 1113 |
PyDictAttribute::bind(m); |
| 1114 |
PyFlatSymbolRefAttribute::bind(m); |
| 1115 |
PyOpaqueAttribute::bind(m); |
| 1116 |
PyFloatAttribute::bind(m); |
| 1117 |
PyIntegerAttribute::bind(m); |
| 1118 |
PyStringAttribute::bind(m); |
| 1119 |
PyTypeAttribute::bind(m); |
| 1120 |
PyUnitAttribute::bind(m); |
| 1121 |
|
| 1122 |
PyStridedLayoutAttribute::bind(m); |
| 1123 |
} |