Commit Graph

88 Commits

Author SHA1 Message Date
zhanghb97 a2914e0c15 [mlir][Python] Fix comments of 'getCapsule' and 'createFromCapsule'
The `getCapsule` and `createFromCapsule` comments incorrectly state the `PyMlirContext` and `MlirContext` in `PyLocation`, `PyAttribute`, and `PyType` classes.

Differential Revision: https://reviews.llvm.org/D95413
2021-01-26 12:53:21 +08:00
Stella Laurenzo fd226c9b02 [mlir][Python] Roll up of python API fixes.
* As discussed, fixes the ordering or (operands, results) -> (results, operands) in various `create` like methods.
* Fixes a syntax error in an ODS accessor method.
* Removes the linalg example in favor of a test case that exercises the same.
* Fixes FuncOp visibility to properly use None instead of the empty string and defaults it to None.
* Implements what was documented for requiring that trailing __init__ args `loc` and `ip` are keyword only.
* Adds a check to `InsertionPoint.insert` so that if attempting to insert past the terminator, an exception is raised telling you what to do instead. Previously, this would crash downstream (i.e. when trying to print the resultant module).
* Renames `_ods_build_default` -> `build_generic` and documents it.
* Removes `result` from the list of prohibited words and for single-result ops, defaults to naming the result `result`, thereby matching expectations and what is already implemented on the base class.
* This was intended to be a relatively small set of changes to be inlined with the broader support for ODS generating the most specific builder, but it spidered out once actually testing various combinations, so rolling up separately.

Differential Revision: https://reviews.llvm.org/D95320
2021-01-24 19:02:59 -08:00
Mehdi Amini 922b26cde4 Add Python bindings for the builtin dialect
This includes some minor customization for FuncOp and ModuleOp.

Differential Revision: https://reviews.llvm.org/D95022
2021-01-21 22:44:44 +00:00
Stella Laurenzo b62c7e0474 [mlir][python] Swap shape and element_type order for MemRefType.
* Matches how all of the other shaped types are declared.
* No super principled reason fro this ordering beyond that it makes the one that was different be like the rest.
* Also matches ordering of things like ndarray, et al.

Reviewed By: ftynse, nicolasvasilache

Differential Revision: https://reviews.llvm.org/D94812
2021-01-19 16:03:19 -08:00
Stella Laurenzo 894d88a759 [mlir][python] Add facility for extending generated python ODS.
* This isn't exclusive with other mechanisms for more ODS centric op definitions, but based on discussions, we feel that we will always benefit from a python escape hatch, and that is the most natural way to write things that don't fit the mold.
* I suspect this facility needs further tweaking, and once it settles, I'll document it and add more tests.
* Added extensions for linalg, since it is unusable without them and continued to evolve my e2e example.

Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D94752
2021-01-19 13:20:26 -08:00
Stella Laurenzo 71b6b010e6 [mlir][python] Factor out standalone OpView._ods_build_default class method.
* This allows us to hoist trait level information for regions and sized-variadic to class level attributes (_ODS_REGIONS, _ODS_OPERAND_SEGMENTS, _ODS_RESULT_SEGMENTS).
* Eliminates some splicey python generated code in favor of a native helper for it.
* Makes it possible to implement custom, variadic and region based builders with one line of python, without needing to manually code access to the segment attributes.
* Needs follow-on work for region based callbacks and support for SingleBlockImplicitTerminator.
* A follow-up will actually add ODS support for generating custom Python builders that delegate to this new method.
* Also includes the start of an e2e sample for constructing linalg ops where this limitation was discovered (working progressively through this example and cleaning up as I go).

Differential Revision: https://reviews.llvm.org/D94738
2021-01-19 09:29:57 -08:00
zhanghb97 c0f3ea8a08 [mlir][Python] Add checking process before create an AffineMap from a permutation.
An invalid permutation will trigger a C++ assertion when attempting to create an AffineMap from the permutation.
This patch adds an `isPermutation` function to check the given permutation before creating the AffineMap.

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D94492
2021-01-13 09:32:32 +08:00
Stella Laurenzo 53c866c286 Enable python bindings for tensor, shape and linalg dialects.
* We've got significant missing features in order to use most of these effectively (i.e. custom builders, region-based builders).
* We presently also lack a mechanism for actually registering these dialects but they can be use with contexts that allow unregistered dialects for further prototyping.

Differential Revision: https://reviews.llvm.org/D94368
2021-01-11 12:35:49 -08:00
Alex Zinenko 547e3eef14 [mlir] Expose MemRef layout in Python bindings
This wasn't possible before because there was no support for affine expressions
as maps. Now that this support is available, provide the mechanism for
constructing maps with a layout and inspecting it.

Rework the `get` method on MemRefType in Python to avoid needing an explicit
memory space or layout map. Remove the `get_num_maps`, it is too low-level,
using the length of the now-avaiable pseudo-list of layout maps is more
pythonic.

Depends On D94297

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D94302
2021-01-11 19:57:16 +01:00
Alex Zinenko e79bd0b4f2 [mlir] More Python bindings for AffineMap
Now that the bindings for AffineExpr have been added, add more bindings for
constructing and inspecting AffineMap that consists of AffineExprs.

Depends On D94225

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D94297
2021-01-11 19:57:15 +01:00
Alex Zinenko 74628c4305 [mlir] Add Python bindings for AffineExpr
This adds the Python bindings for AffineExpr and a couple of utility functions
to the C API. AffineExpr is a top-level context-owned object and is modeled
similarly to attributes and types. It is required, e.g., to build layout maps
of the built-in memref type.

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D94225
2021-01-11 19:57:13 +01:00
Kazuaki Ishizaki f88fab5006 [mlir] NFC: fix trivial typos
fix typo under include and lib directories

Reviewed By: antiagainst

Differential Revision: https://reviews.llvm.org/D94220
2021-01-08 02:10:12 +09:00
Stella Laurenzo 42c57dcc35 [mlir][python] Tweaks to make python extensions packagable/distributable.
* Works in tandem with prototype packaging scripts here: https://github.com/stellaraccident/mlir-py-release
* The `mlir` top-level now differentiates between in-tree builds where all packages are co-located and distribution mode where all native components are under a top-level `_mlir_libs` package.
* Also fixes the generated dialect python installation again. Hopefully the last tweak.
* With this, I am able to install and generate archives with the above setup script on Linux. Archive size=31M with just host codegen and headers/shared-libraries. Will need more linker tweaks when wiring up the next dependent project.

Differential Revision: https://reviews.llvm.org/D93936
2020-12-30 23:35:46 -08:00
zhanghb97 abb4cd3e74 [mlir][Python] Initial Affine Map Python Bindings.
- Add `PyAffineMap` to wrap around `MlirAffineMap`.
- Add `mlirPythonAffineMapToCapsule` and `mlirPythonCapsuleToAffineMap` to interoperate with python capsule.
- Add and test some simple bindings of `PyAffineMap`.

Differential Revision: https://reviews.llvm.org/D93200
2020-12-30 17:36:39 +08:00
Stella Laurenzo 11f41cd445 [mlir][python] Install generated dialect sources.
Differential Revision: https://reviews.llvm.org/D93928
2020-12-29 20:15:07 -08:00
Siddharth Krishna 14056c88d6 [mlir][Python] Add an Operation.name property
Reviewed By: stellaraccident, mehdi_amini

Differential Revision: https://reviews.llvm.org/D93474
2020-12-29 14:14:32 -08:00
Stella Laurenzo f5665a2486 [mlir][python] Add Operation.verify().
Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D93913
2020-12-29 14:10:31 -08:00
Stella Laurenzo df7ddeea66 [mlir][python] Add FlatSymbolRef attribute.
Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D93909
2020-12-29 12:24:28 -08:00
kweisamx c84b53ca9b [mlir] Add Python binding for MLIR Dict Attribute
Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D93004
2020-12-13 04:30:35 +00:00
Mehdi Amini aadcb26ee1 Store a MlirIdentifier instead of a MlirStringRef in MlirNameAttribute
This mirror the C++ API for NamedAttribute, and has the advantage or
internalizing earlier in the Context and not requiring the caller to
keep the StringRef alive beyong this call.

Differential Revision: https://reviews.llvm.org/D93133
2020-12-11 22:38:48 +00:00
Mehdi Amini 285c0aa262 Add MLIR Python binding for Array Attribute
Differential Revision: https://reviews.llvm.org/D92948
2020-12-10 20:51:34 +00:00
Mehdi Amini ac6ada4d3e Fix MLIR Python bindings build after changes to the C API to use StringRef (NFC) 2020-12-09 03:27:37 +00:00
Mehdi Amini e56f398dd3 Add Python binding for MLIR Type Attribute
Differential Revision: https://reviews.llvm.org/D92711
2020-12-07 23:06:58 +00:00
Mehdi Amini e15ae454b4 Customize exception thrown from mlir.Operation.create() python bindings
The default exception handling isn't very user friendly and does not
point accurately to the issue. Instead we can indicate which of the
operands isn't valid and provide contextual information in the error
message.

Differential Revision: https://reviews.llvm.org/D92710
2020-12-07 23:06:58 +00:00
River Riddle c7cae0e4fa [mlir][Attributes][NFC] Move all builtin Attribute classes to BuiltinAttributes.h
This mirrors the file structure of Types.

Differential Revision: https://reviews.llvm.org/D92499
2020-12-03 18:02:11 -08:00
River Riddle 09f7a55fad [mlir][Types][NFC] Move all of the builtin Type classes to BuiltinTypes.h
This is part of a larger refactoring the better congregates the builtin structures under the BuiltinDialect. This also removes the problematic "standard" naming that clashes with the "standard" dialect, which is not defined within IR/. A temporary forward is placed in StandardTypes.h to allow time for downstream users to replaced references.

Differential Revision: https://reviews.llvm.org/D92435
2020-12-03 18:02:10 -08:00
Mehdi Amini 1c2159494d Use the generic form when printing from the python bindings and the verifier fails
This reduces the chances of segfault. While it is a good practice to ensure
robust custom printers, it is unfortunately common to have them crash on
invalid input.

Reviewed By: stellaraccident

Differential Revision: https://reviews.llvm.org/D92536
2020-12-03 18:45:00 +00:00
Stella Laurenzo 62195b7548 [mlir][CAPI] Convert the rest of the API int -> bool.
* Follows on https://reviews.llvm.org/D92193
* I had a mid-air collision with some additional occurrences and then noticed that there were a lot more. Think I got them all.

Differential Revision: https://reviews.llvm.org/D92292
2020-11-29 20:36:42 -08:00
Stella Laurenzo ba0fe76b7e [mlir][Python] Add an Operation.result property.
* If ODS redefines this, it is fine, but I have found this accessor to be universally useful in the old npcomp bindings and I'm closing gaps that will let me switch.

Differential Revision: https://reviews.llvm.org/D92287
2020-11-29 18:09:07 -08:00
Stella Laurenzo bd2083c2fa [mlir][Python] Python API cleanups and additions found during code audit.
* Add capsule get/create for Attribute and Type, which already had capsule interop defined.
* Add capsule interop and get/create for Location.
* Add Location __eq__.
* Use get() and implicit cast to go from PyAttribute, PyType, PyLocation to MlirAttribute, MlirType, MlirLocation (bundled with this change because I didn't want to continue the pattern one more time).

Differential Revision: https://reviews.llvm.org/D92283
2020-11-29 18:09:07 -08:00
zhanghb97 5f0c1e3806 [mlir][Python] Sync Python bindings with C API MlirStringRef modification.
MLIR C API use the `MlirStringRef` instead of `const char *` for the string type now. This patch sync the Python bindings with the C API modification.

Differential Revision: https://reviews.llvm.org/D92007
2020-11-24 19:33:48 +00:00
Alex Zinenko ee6255d207 [mlir] move lib/Bindings/Python/Attributes.td to include/mlir/Bindings/Python
This file is intended to be included by other files, including
out-of-tree dialects, and makes more sense in `include` than in `lib`.

Depends On D91652

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D91961
2020-11-24 09:19:01 +01:00
Alex Zinenko 029e199dbf [mlir] Make attributes mutable in Python bindings
Attributes represent additional data about an operation and are intended to be
modifiable during the lifetime of the operation. In the dialect-specific Python
bindings, attributes are exposed as properties on the operation class. Allow
for assigning values to these properties. Also support creating new and
deleting existing attributes through the generic "attributes" property of an
operation. Any validity checking must be performed by the op verifier after the
mutation, similarly to C++. Operations are not invalidated in the process: no
dangling pointers can be created as all attributes are owned by the context and
will remain live even if they are not used in any operation.

Introduce a Python Test dialect by analogy with the Test dialect and to avoid
polluting the latter with Python-specific constructs. Use this dialect to
implement a test for the attribute access and mutation API.

Reviewed By: stellaraccident, mehdi_amini

Differential Revision: https://reviews.llvm.org/D91652
2020-11-24 09:16:25 +01:00
zhanghb97 77133b29b9 [mlir] Get array from the dense elements attribute with buffer protocol.
- Add `mlirElementsAttrGetType` C API.
- Add `def_buffer` binding to PyDenseElementsAttribute.
- Implement the protocol to access the buffer.

Differential Revision: https://reviews.llvm.org/D91021
2020-11-18 15:50:59 +08:00
Stella Laurenzo 989b194429 [mlir][Python] Make DenseElementsAttr loading be int size agnostic.
* I had missed the note about "Standard size" in the docs. On Windows, the 'l' types are 32bit.
* This fixes the only failing MLIR-Python test on Windows.

Differential Revision: https://reviews.llvm.org/D91283
2020-11-17 21:50:44 -08:00
Alex Zinenko f3dab16dc7 [mlir] Add a _get_default_loc_context utility to Python bindings
This utility function is helpful for dialect-specific builders that need
to access the context through location, and the location itself may be
either provided as an argument or expected to be recovered from the
implicit location stack.

Reviewed By: stellaraccident

Differential Revision: https://reviews.llvm.org/D91623
2020-11-17 17:55:47 +01:00
Alex Zinenko c5a6712f8c [mlir] Add basic support for attributes in ODS-generated Python bindings
In ODS, attributes of an operation can be provided as a part of the "arguments"
field, together with operands. Such attributes are accepted by the op builder
and have accessors generated.

Implement similar functionality for ODS-generated op-specific Python bindings:
the `__init__` method now accepts arguments together with operands, in the same
order as in the ODS `arguments` field; the instance properties are introduced
to OpView classes to access the attributes.

This initial implementation accepts and returns instances of the corresponding
attribute class, and not the underlying values since the mapping scheme of the
value types between C++, C and Python is not yet clear. Default-valued
attributes are not supported as that would require Python to be able to parse
C++ literals.

Since attributes in ODS are tightely related to the actual C++ type system,
provide a separate Tablegen file with the mapping between ODS storage type for
attributes (typically, the underlying C++ attribute class), and the
corresponding class name. So far, this might look unnecessary since all names
match exactly, but this is not necessarily the cases for non-standard,
out-of-tree attributes, which may also be placed in non-default namespaces or
Python modules. This also allows out-of-tree users to generate Python bindings
without having to modify the bindings generator itself. Storage type was
preferred over the Tablegen "def" of the attribute class because ODS
essentially encodes attribute _constraints_ rather than classes, e.g. there may
be many Tablegen "def"s in the ODS that correspond to the same attribute type
with additional constraints

The presence of the explicit mapping requires the change in the .td file
structure: instead of just calling the bindings generator directly on the main
ODS file of the dialect, it becomes necessary to create a new file that
includes the main ODS file of the dialect and provides the mapping for
attribute types. Arguably, this approach offers better separability of the
Python bindings in the build system as the main dialect no longer needs to know
that it is being processed by the bindings generator.

Reviewed By: stellaraccident

Differential Revision: https://reviews.llvm.org/D91542
2020-11-17 11:47:37 +01:00
Stella Laurenzo 4726a402a3 [mlir][Python] Fix 'unreferenced local variable' warning on MSVC.
Differential Revision: https://reviews.llvm.org/D91282
2020-11-12 13:34:57 -08:00
Stella Laurenzo 5fef6ce0cc [mlir][Python] Allow PassManager to interop with the capsule APIs.
* Used in npcomp to cast Python objects via the C-API.

Differential Revision: https://reviews.llvm.org/D91232
2020-11-11 10:37:21 -08:00
Stella Laurenzo 99b1c42fd3 [mlir][Python] Add Windows DLL loader to get python extensions working there.
Differential Revision: https://reviews.llvm.org/D90958
2020-11-11 09:54:47 -08:00
Mehdi Amini 6cb1c0cae0 Add Python binding to run a PassManager on a MLIR Module
Reviewed By: ftynse, stellaraccident

Differential Revision: https://reviews.llvm.org/D90823
2020-11-10 20:06:23 +00:00
Mehdi Amini dc43f78565 Add basic Python bindings for the PassManager and bind libTransforms
This only exposes the ability to round-trip a textual pipeline at the
moment.
To exercise it, we also bind the libTransforms in a new Python extension. This
does not include any interesting bindings, but it includes all the
mechanism to add separate native extensions and load them dynamically.
As such passes in libTransforms are only registered after `import
mlir.transforms`.
To support this global registration, the TableGen backend is also
extended to bind to the C API the group registration for passes.

Reviewed By: stellaraccident

Differential Revision: https://reviews.llvm.org/D90819
2020-11-10 19:55:21 +00:00
Alex Zinenko fd407e1f1e [mlir] ODS-backed python binding generator for custom op classes
Introduce an ODS/Tablegen backend producing Op wrappers for Python bindings
based on the ODS operation definition. Usage:

  mlir-tblgen -gen-python-op-bindings -Iinclude <path/to/Ops.td> \
              -bind-dialect=<dialect-name>

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D90960
2020-11-10 10:58:29 +01:00
Alex Zinenko 6c7e6b2c9a [mlir] Support slicing for operands in results in Python bindings
Slicing, that is element access with `[being🔚step]` structure, is
a common Python idiom for sequence-like containers. It is also necessary
to support custom accessor for operations with variadic operands and
results (an operation an return a slice of its operands that correspond
to the given variadic group).

Add generic utility to support slicing in Python bindings and use it
for operation operands and results.

Depends On D90923

Reviewed By: stellaraccident, mehdi_amini

Differential Revision: https://reviews.llvm.org/D90936
2020-11-10 10:46:21 +01:00
Alex Zinenko 4669ea3bd8 [mlir] Add initial Python bindings for DenseInt/FPElementsAttr
Enumerating elements in these classes is necessary to enable custom
operand accessors for variadic operands.

Depends On D90919

Reviewed By: stellaraccident

Differential Revision: https://reviews.llvm.org/D90923
2020-11-09 15:23:54 +01:00
Alex Zinenko c3a6e7c9b7 [mlir] Expose operation attributes to Python bindings
Operations in a MLIR have a dictionary of attributes attached. Expose
those to Python bindings through a pseudo-container that can be indexed
either by attribute name, producing a PyAttribute, or by a contiguous
index for enumeration purposes, producing a PyNamedAttribute.

Depends On D90917

Reviewed By: stellaraccident

Differential Revision: https://reviews.llvm.org/D90919
2020-11-09 14:59:56 +01:00
Stella Laurenzo 08c1a0dda4 [mlir][CAPI] Proposal: Always building a libMLIRPublicAPI.so (re-apply).
Re-applies the reverted https://reviews.llvm.org/D90824 now that the link issue on BFD has been resolved.

This reverts commit bb9b5d3971.

Differential Revision: https://reviews.llvm.org/D91044
2020-11-08 16:57:51 -08:00
Alex Zinenko b9c353fabb [mlir] Use PyValue instead of PyOpResult in Python operand container
The PyOpOperands container was erroneously constructing objects for
individual operands as PyOpResult. Operands in fact are just values,
which may or may not be results of another operation. The code would
eventually crash if the operand was a block argument. Add a test that
exercises the behavior that previously led to crashes.

Reviewed By: stellaraccident

Differential Revision: https://reviews.llvm.org/D90917
2020-11-06 19:02:35 +01:00
Alex Zinenko bb9b5d3971 Revert "[mlir][CAPI] Proposal: Always building a libMLIRPublicAPI.so."
This reverts commit 80fe2f61fa.

Broke linkage with GNU ld. See original review thread for more details.
2020-11-06 18:59:58 +01:00
Stella Laurenzo 80fe2f61fa [mlir][CAPI] Proposal: Always building a libMLIRPublicAPI.so.
We were discussing on discord regarding the need for extension-based systems like Python to dynamically link against MLIR (or else you can only have one extension that depends on it). Currently, when I set that up, I piggy-backed off of the flag that enables build libLLVM.so and libMLIR.so and depended on libMLIR.so from the python extension if shared library building was enabled. However, this is less than ideal.

In the current setup, libMLIR.so exports both all symbols from the C++ API and the C-API. The former is a kitchen sink and the latter is curated. We should be splitting them and for things that are properly factored to depend on the C-API, they should have the option to *only* depend on the C-API, and we should build that shared library no matter what. Its presence isn't just an optimization: it is a key part of the system.

To do this right, I needed to:

* Introduce visibility macros into mlir-c/Support.h. These should work on both *nix and windows as-is.
* Create a new libMLIRPublicAPI.so with just the mlir-c object files.
* Compile the C-API with -fvisibility=hidden.
* Conditionally depend on the libMLIR.so from libMLIRPublicAPI.so if building libMLIR.so (otherwise, also links against the static libs and will produce a mondo libMLIRPublicAPI.so).
* Disable re-exporting of static library symbols that come in as transitive deps.

This gives us a dynamic linked C-API layer that is minimal and should work as-is on all platforms. Since we don't support libMLIR.so building on Windows yet (and it is not very DLL friendly), this will fall back to a mondo build of libMLIRPublicAPI.so, which has its uses (it is also the most size conscious way to go if you happen to know exactly what you need).

Sizes (release/stripped, Ubuntu 20.04):

Shared library build:
	libMLIRPublicAPI.so: 121Kb
	_mlir.cpython-38-x86_64-linux-gnu.so: 1.4Mb
	mlir-capi-ir-test: 135Kb
	libMLIR.so: 21Mb

Static build:
	libMLIRPublicAPI.so: 5.5Mb (since this is a "static" build, this includes the MLIR implementation as non-exported code).
	_mlir.cpython-38-x86_64-linux-gnu.so: 1.4Mb
	mlir-capi-ir-test: 44Kb

Things like npcomp and circt which bring their own dialects/transforms/etc would still need the shared library build and code that links against libMLIR.so (since it is all C++ interop stuff), but hopefully things that only depend on the public C-API can just have the one narrow dep.

I spot checked everything with nm, and it looks good in terms of what is exporting/importing from each layer.

I'm not in a hurry to land this, but if it is controversial, I'll probably split off the Support.h and API visibility macro changes, since we should set that pattern regardless.

Reviewed By: mehdi_amini, benvanik

Differential Revision: https://reviews.llvm.org/D90824
2020-11-06 09:00:56 -08:00