Commit Graph

88 Commits

Author SHA1 Message Date
Mehdi Amini 72dcd902e7 Add a custom MLIRBindingsPythonExtension cmake target to group all Python bindings (NFC)
This target will depend on each individual extension and represent "all"
Python bindings in the repo. User projects can get a finer grain control by
depending directly on some individual targets as needed.
2020-11-05 20:06:08 +00:00
Mehdi Amini 7f977086eb Fix MLIR Python bindings build (remove inexistant source from CMake list, NFC) 2020-11-05 20:06:07 +00:00
Mehdi Amini 24b3b2cd74 Refactor MLIR python extension CMake boilerplate in a reusable function (NFC)
Differential Revision: https://reviews.llvm.org/D90816
2020-11-05 19:57:12 +00:00
Mehdi Amini a1229c9518 Always link the MLIR python bindings native extension to libMLIR.so
The Python bindings now require -DLLVM_BUILD_LLVM_DYLIB=ON to build.
This change is needed to be able to build multiple Python native
extension without having each of them embedding a copy of MLIR, which
would make them incompatible with each other. Instead they should all
link to the same copy of MLIR.

Differential Revision: https://reviews.llvm.org/D90813
2020-11-05 19:57:11 +00:00
Mehdi Amini 5b29d26b21 Refactor PyPrintAccumulatorm, PyFileAccumulator, and PySinglePartStringAccumulator from IRModules.cpp to PybindUtils.h
These are reusable utilities across bindings.

Differential Revision: https://reviews.llvm.org/D90737
2020-11-04 18:46:36 +00:00
Stella Laurenzo 8260db752c [mlir][Python] Return and accept OpView for all functions.
* All functions that return an Operation now return an OpView.
* All functions that accept an Operation now accept an _OperationBase, which both Operation and OpView extend and can resolve to the backing Operation.
* Moves user-facing instance methods from Operation -> _OperationBase so that both can have the same API.
* Concretely, this means that if there are custom op classes defined (i.e. in Python), any iteration or creation will return the appropriate instance (i.e. if you get/create an std.addf, you will get an instance of the mlir.dialects.std.AddFOp class, getting full access to any custom API it exposes).
* Refactors all __eq__ methods after realizing the proper way to do this for _OperationBase.

Differential Revision: https://reviews.llvm.org/D90584
2020-11-03 22:48:34 -08:00
Stella Laurenzo af66cd173f [mlir][Python] Context managers for Context, InsertionPoint, Location.
* Finishes support for Context, InsertionPoint and Location to be carried by the thread using context managers.
* Introduces type casters and utilities so that DefaultPyMlirContext and DefaultPyLocation in method signatures does the right thing (allows explicit or gets from the thread context).
* Extend the rules for the thread context stack to handle nesting, appropriately inheriting and clearing depending on whether the context is the same.
* Refactors all method signatures to follow the new convention on trailing parameters for defaulting parameters (loc, ip, context). When the objects are carried in the thread context, this allows most explicit uses of these values to be elided.
* Removes the style guide section on putting accessors to construct global objects on the PyMlirContext: this style fails to make good use of the new facility since it is often the only thing remaining needing an MlirContext.
* Moves Module parse/creation from mlir.ir.Context to static methods on mlir.ir.Module.
* Moves Context.create_operation to a static Operation.create method.
* Moves Type parsing from mlir.ir.Context to static methods on mlir.ir.Type.
* Moves Attribute parsing from mlir.ir.Context to static methods on mlir.ir.Attribute.
* Move Location factory methods from mlir.ir.Context to static methods on mlir.ir.Location.
* Refactors the std dialect fake "ODS" generated code to take advantage of the new scheme.

Differential Revision: https://reviews.llvm.org/D90547
2020-11-01 19:00:39 -08:00
Stella Laurenzo c645ea5e29 Add InsertionPoint and context managers to the Python API.
* Removes index based insertion. All insertion now happens through the insertion point.
* Introduces thread local context managers for implicit creation relative to an insertion point.
* Introduces (but does not yet use) binding the Context to the thread local context stack. Intent is to refactor all methods to take context optionally and have them use the default if available.
* Adds C APIs for mlirOperationGetParentOperation(), mlirOperationGetBlock() and mlirBlockGetTerminator().
* Removes an assert in PyOperation creation that was incorrectly constraining. There is already a TODO to rework the keepAlive field that it was guarding and without the assert, it is no worse than the current state.

Differential Revision: https://reviews.llvm.org/D90368
2020-10-29 17:50:13 -07:00
Kazuaki Ishizaki 41b09f4eff [mlir] NFC: fix trivial typos
fix typos in comments and documents

Reviewed By: jpienaar

Differential Revision: https://reviews.llvm.org/D90089
2020-10-29 04:05:22 +09:00
Mehdi Amini 72023442c1 Add a `mlirModuleGetBody()` accessor to the C API and bind it in Python
Getting the body of a Module is a common need which justifies a
dedicated accessor instead of forcing users to go through the
region->blocks->front unwrapping manually.

Differential Revision: https://reviews.llvm.org/D90287
2020-10-28 17:53:52 +00:00
Stella Laurenzo 013b9322de [mlir][Python] Custom python op view wrappers for building and traversing.
* Still rough edges that need more sugar but the bones are there. Notes left in the test case for things that can be improved.
* Does not actually yield custom OpViews yet for traversing. Will rework that in a followup.

Differential Revision: https://reviews.llvm.org/D89932
2020-10-27 12:23:34 -07:00
Stella Laurenzo 74a58ec9c2 [mlir][CAPI][Python] Plumb OpPrintingFlags to C and Python APIs.
* Adds a new MlirOpPrintingFlags type and supporting accessors.
* Adds a new mlirOperationPrintWithFlags function.
* Adds a full featured python Operation.print method with all options and the ability to print directly to files/stdout in text or binary.
* Adds an Operation.get_asm which delegates to print and returns a str or bytes.
* Reworks Operation.__str__ to be based on get_asm.

Differential Revision: https://reviews.llvm.org/D89848
2020-10-21 12:14:06 -07:00
Alex Zinenko f6f27115e6 [mlir] Fix copy-pasted docstrings in Python bindings
Docstrings for `__str__` method in many classes was recycling the constant
string defined for `Type`, without being types themselves. Use proper
docstrings instead. Since they are succint, use string literals instead of
top-level constants to avoid further mistakes.

Differential Revision: https://reviews.llvm.org/D89780
2020-10-21 09:49:23 +02:00
Alex Zinenko 31782cd219 [mlir] Use the correct base class for Attributes in Python bindings
The pybind class typedef for concrete attribute classes was erroneously
deriving all of them from PyAttribute instead of the provided base class. This
has not been triggering any error because only one level of the hierarchy is
currently exposed.

Differential Revision: https://reviews.llvm.org/D89779
2020-10-21 09:49:23 +02:00
Alex Zinenko 580915d6a2 [mlir] Expose Value hierarchy to Python bindings
Values are ubiquitous in the IR, in particular block argument and operation
results are Values. Define Python classes for BlockArgument, OpResult and their
common ancestor Value. Define pseudo-container classes for lists of block
arguments and operation results, and use these containers to access the
corresponding values in blocks and operations.

Differential Revision: https://reviews.llvm.org/D89778
2020-10-21 09:49:22 +02:00
Stella Laurenzo 0e6beb2996 [mlir][Python] Add python binding to create DenseElementsAttribute.
* Interops with Python buffers/numpy arrays to create.
* Also cleans up 'get' factory methods on some types to be consistent.
* Adds mlirAttributeGetType() to C-API to facilitate error handling and other uses.
* Punts on a lot of features of the ElementsAttribute hierarchy for now.
* Does not yet support bool or string attributes.

Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D89363
2020-10-19 22:29:35 -07:00
Stella Laurenzo ad958f648e [mlir][Python] Add missing capsule->module and Context.create_module.
* Extends Context/Operation interning to cover Module as well.
* Implements Module.context, Attribute.context, Type.context, and Location.context back-references (facilitated testing and also on the TODO list).
* Adds method to create an empty Module.
* Discovered missing in npcomp.

Differential Revision: https://reviews.llvm.org/D89294
2020-10-13 13:10:33 -07:00
Stella Laurenzo 75ae846de6 [mlir] Make Python bindings installable.
* Links against libMLIR.so if the project is built for DYLIBs.
* Puts things in the right place in build and install time python/ trees so that RPaths line up.
* Adds install actions to install both the extension and sources.
* Copies py source files to the build directory to match (consistent layout between build/install time and one place to point a PYTHONPATH for tests and interactive use).
* Finally, "import mlir" from an installed LLVM just works.

Differential Revision: https://reviews.llvm.org/D89167
2020-10-12 15:17:03 -07:00
zhanghb97 2fc0d4a8e8 [mlir] Add Float Attribute, Integer Attribute and Bool Attribute subclasses to python bindings.
Based on PyAttribute and PyConcreteAttribute classes, this patch implements the bindings of Float Attribute, Integer Attribute and Bool Attribute subclasses.
This patch also defines the `mlirFloatAttrDoubleGetChecked` C API which is bound with the `FloatAttr.get_typed` python method.

Differential Revision: https://reviews.llvm.org/D88531
2020-10-03 00:32:51 +08:00
Stella Laurenzo 543922cd36 Adds MLIR C-API for marshaling Python capsules.
* Providing stable, C-accessible definitions for bridging MLIR Python<->C APIs, we eliminate inter-extension dependencies (i.e. they can all share a diamond dependency on the MLIR C-API).
* Just provides accessors for context and module right now.
* Needed in NPComp in ~a week or so for high level Torch APIs.

Differential Revision: https://reviews.llvm.org/D88426
2020-09-29 10:48:53 -07:00
Stella Laurenzo 76753a597b Add FunctionType to MLIR C and Python bindings.
Differential Revision: https://reviews.llvm.org/D88416
2020-09-28 09:56:48 -07:00
Stella Laurenzo b522f09d96 Remove MLIR C-API explicit registration of standard ops.
* Added mlirRegisterAllDialects() to the python API until a more complete registration design emerges for it.

Differential Revision: https://reviews.llvm.org/D88155
2020-09-23 09:23:11 -07:00
Stella Laurenzo c1ded6a759 Add mlir python APIs for creating operations, regions and blocks.
* The API is a bit more verbose than I feel like it needs to be. In a follow-up I'd like to abbreviate some things and look in to creating aliases for common accessors.
* There is a lingering lifetime hazard between the module and newly added operations. We have the facilities now to solve for this but I will do that in a follow-up.
* We may need to craft a more limited API for safely referencing successors when creating operations. We need more facilities to really prove that out and should defer for now.

Differential Revision: https://reviews.llvm.org/D87996
2020-09-23 07:57:50 -07:00
Stella Laurenzo 4cf754c4bc Implement python iteration over the operation/region/block hierarchy.
* Removes the half-completed prior attempt at region/block mutation in favor of new approach to ownership.
* Will re-add mutation more correctly in a follow-on.
* Eliminates the detached state on blocks and regions, simplifying the ownership hierarchy.
* Adds both iterator and index based access at each level.

Differential Revision: https://reviews.llvm.org/D87982
2020-09-23 07:57:50 -07:00
Stella Laurenzo 7abb0ff7e0 Add Operation to python bindings.
* Fixes a rather egregious bug with respect to the inability to return arbitrary objects from py::init (was causing aliasing of multiple py::object -> native instance).
* Makes Modules and Operations referencable types so that they can be reliably depended on.
* Uniques python operation instances within a context. Opens the door for further accounting.
* Next I will retrofit region and block to be dependent on the operation, and I will attempt to model the API to avoid detached regions/blocks, which will simplify things a lot (in that world, only operations can be detached).
* Added quite a bit of test coverage to check for leaks and reference issues.
* Supercedes: https://reviews.llvm.org/D87213

Differential Revision: https://reviews.llvm.org/D87958
2020-09-23 07:57:50 -07:00
Stella Laurenzo 85185b61b6 First pass on MLIR python context lifetime management.
* Per thread https://llvm.discourse.group/t/revisiting-ownership-and-lifetime-in-the-python-bindings/1769
* Reworks contexts so it is always possible to get back to a py::object that holds the reference count for an arbitrary MlirContext.
* Retrofits some of the base classes to automatically take a reference to the context, elimintating keep_alives.
* More needs to be done, as discussed, when moving on to the operations/blocks/regions.

Differential Revision: https://reviews.llvm.org/D87886
2020-09-18 12:17:50 -07:00
Alex Zinenko 855ec517a3 [mlir] Model StringRef in C API
Numerous MLIR functions return instances of `StringRef` to refer to a
non-owning fragment of a string (usually owned by the context). This is a
relatively simple class that is defined in LLVM. Provide a simple wrapper in
the MLIR C API that contains the pointer and length of the string fragment and
use it for Standard attribute functions that return StringRef instead of the
previous, callback-based mechanism.

Reviewed By: stellaraccident

Differential Revision: https://reviews.llvm.org/D87677
2020-09-16 16:04:36 +02:00
Stella Laurenzo 7403e3ee32 Extend PyConcreteType to support intermediate base classes.
* Resolves todos from D87091.
* Also modifies PyConcreteAttribute to follow suite (should be useful for ElementsAttr and friends).
* Adds a test to ensure that the ShapedType base class functions as expected.

Differential Revision: https://reviews.llvm.org/D87208
2020-09-06 23:39:47 -07:00
zhanghb97 54d432aa6b [mlir] Add Shaped Type, Tensor Type and MemRef Type to python bindings.
Based on the PyType and PyConcreteType classes, this patch implements the bindings of Shaped Type, Tensor Type and MemRef Type subclasses.
The Tensor Type and MemRef Type are bound as ranked and unranked separately.
This patch adds the ***GetChecked C API to make sure the python side can get a valid type or a nullptr.
Shaped type is not a kind of standard types, it is the base class for vectors, memrefs and tensors, this patch binds the PyShapedType class as the base class of Vector Type, Tensor Type and MemRef Type subclasses.

Reviewed By: stellaraccident

Differential Revision: https://reviews.llvm.org/D87091
2020-09-06 11:45:54 -07:00
ZHANG Hongbin 1d99472875 [mlir] Add Complex Type, Vector Type and Tuple Type subclasses to python bindings
Based on the PyType and PyConcreteType classes, this patch implements the bindings of Complex Type, Vector Type and Tuple Type subclasses.
For the convenience of type checking, this patch defines a `mlirTypeIsAIntegerOrFloat` function to check whether the given type is an integer or float type.
These three subclasses in this patch have similar binding strategy:
- The function pointer `isaFunction` points to `mlirTypeIsA***`.
- The `mlir***TypeGet` C API is bound with the `get_***` method in the python side.
- The Complex Type and Vector Type check whether the given type is an integer or float type.

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D86785
2020-09-02 05:46:00 +00:00
Stella Laurenzo 2d1362e09a Add Location, Region and Block to MLIR Python bindings.
* This is just enough to create regions/blocks and iterate over them.
* Does not yet implement the preferred iteration strategy (python pseudo containers).
* Refinements need to come after doing basic mappings of operations and values so that the whole hierarchy can be used.

Differential Revision: https://reviews.llvm.org/D86683
2020-08-28 15:26:05 -07:00
zhanghb97 1f6c4d829c [mlir] Add Index Type, Floating Point Type and None Type subclasses to python bindings.
Based on the PyType and PyConcreteType classes, this patch implements the bindings of Index Type, Floating Point Type and None Type subclasses.
These three subclasses share the same binding strategy:
- The function pointer `isaFunction` points to `mlirTypeIsA***`.
- The `mlir***TypeGet` C API is bound with the `***Type` constructor in the python side.

Reviewed By: stellaraccident

Differential Revision: https://reviews.llvm.org/D86466
2020-08-24 18:54:54 +00:00
Stella Laurenzo 3137c29926 Add initial python bindings for attributes.
* Generic mlir.ir.Attribute class.
* First standard attribute (mlir.ir.StringAttr), following the same pattern as generic vs standard types.
* NamedAttribute class.

Differential Revision: https://reviews.llvm.org/D86250
2020-08-23 22:16:23 -07:00
Alex Zinenko da56297462 [mlir] expose standard attributes to C API
Provide C API for MLIR standard attributes. Since standard attributes live
under lib/IR in core MLIR, place the C APIs in the IR library as well (standard
ops will go in a separate library).

Affine map and integer set attributes are only exposed as placeholder types
with IsA support due to the lack of C APIs for the corresponding types.

Integer and floating point attribute APIs expecting APInt and APFloat are not
exposed pending decision on how to support APInt and APFloat.

Reviewed By: stellaraccident

Differential Revision: https://reviews.llvm.org/D86143
2020-08-19 18:50:19 +02:00
Stella Laurenzo d29d1e2ffd Add python bindings for Type and IntegerType.
* The binding for Type is trivial and should be non-controversial.
* The way that I define the IntegerType should serve as a pattern for what I want to do next.
* I propose defining the rest of the standard types in this fashion and then generalizing for dialect types as necessary.
* Essentially, creating/accessing a concrete Type (vs interacting with the string form) is done by "casting" to the concrete type (i.e. IntegerType can be constructed with a Type and will throw if the cast is illegal).
* This deviates from some of our previous discussions about global objects but I think produces a usable API and we should go this way.

Differential Revision: https://reviews.llvm.org/D86179
2020-08-19 09:23:44 -07:00
Stella Laurenzo 95b77f2eac Adds __str__ support to python mlir.ir.MlirModule.
* Also raises an exception on parse error.
* Removes placeholder smoketest.
* Adds docstrings.

Differential Revision: https://reviews.llvm.org/D86046
2020-08-17 09:46:33 -07:00
zhanghb97 fcd2969da9 Initial MLIR python bindings based on the C API.
* Basic support for context creation, module parsing and dumping.

Differential Revision: https://reviews.llvm.org/D85481
2020-08-16 19:34:25 -07:00
Stella Laurenzo 722475a375 Initial boiler-plate for python bindings.
Summary:
* Native '_mlir' extension module.
* Python mlir/__init__.py trampoline module.
* Lit test that checks a message.
* Uses some cmake configurations that have worked for me in the past but likely needs further elaboration.

Subscribers: mgorny, mehdi_amini, rriddle, jpienaar, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, aartbik, liufengdb, stephenneuendorffer, Joonsoo, grosul1, Kayjukh, jurahul, msifontes

Tags: #mlir

Differential Revision: https://reviews.llvm.org/D83279
2020-07-09 12:03:58 -07:00