MLIR 23.0.0git
ExecutionEngineModule.cpp
Go to the documentation of this file.
1//===- ExecutionEngineModule.cpp - Python module for execution engine -----===//
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 <vector>
10
15
16namespace nb = nanobind;
17
18namespace mlir {
19namespace python {
22
23/// Owning Wrapper around an ExecutionEngine.
25public:
26 PyExecutionEngine(MlirExecutionEngine executionEngine)
27 : executionEngine(executionEngine) {}
29 : executionEngine(other.executionEngine) {
30 other.executionEngine.ptr = nullptr;
31 }
33 if (!mlirExecutionEngineIsNull(executionEngine))
34 mlirExecutionEngineDestroy(executionEngine);
35 }
36 MlirExecutionEngine get() { return executionEngine; }
37
38 void release() {
39 executionEngine.ptr = nullptr;
40 referencedObjects.clear();
41 }
42 nb::object getCapsule() {
43 return nb::steal<nb::object>(mlirPythonExecutionEngineToCapsule(get()));
44 }
45
46 // Add an object to the list of referenced objects whose lifetime must exceed
47 // those of the ExecutionEngine.
48 void addReferencedObject(const nb::object &obj) {
49 referencedObjects.push_back(obj);
50 }
51
52 static nb::object createFromCapsule(const nb::object &capsule) {
53 MlirExecutionEngine rawPm =
56 throw nb::python_error();
57 return nb::cast(PyExecutionEngine(rawPm), nb::rv_policy::move);
58 }
59
60private:
61 MlirExecutionEngine executionEngine;
62 // We support Python ctypes closures as callbacks. Keep a list of the objects
63 // so that they don't get garbage collected. (The ExecutionEngine itself
64 // just holds raw pointers with no lifetime semantics).
65 std::vector<nb::object> referencedObjects;
66};
67
68} // namespace execution_engine
69} // namespace MLIR_BINDINGS_PYTHON_DOMAIN
70} // namespace python
71} // namespace mlir
72
73/// Create the `mlir.execution_engine` module here.
74NB_MODULE(_mlirExecutionEngine, m) {
75 m.doc() = "MLIR Execution Engine";
76
78 using namespace execution_engine;
79 //----------------------------------------------------------------------------
80 // Mapping of the top-level PassManager
81 //----------------------------------------------------------------------------
82 nb::class_<PyExecutionEngine>(m, "ExecutionEngine")
83 .def(
84 "__init__",
85 [](PyExecutionEngine &self, PyModule &module, int optLevel,
86 const std::vector<std::string> &sharedLibPaths,
87 bool enableObjectDump, bool enablePIC) {
88 std::vector<MlirStringRef> libPaths;
89 libPaths.reserve(sharedLibPaths.size());
90 for (const std::string &path : sharedLibPaths)
91 libPaths.push_back({path.c_str(), path.length()});
92 MlirExecutionEngine executionEngine = mlirExecutionEngineCreate(
93 module.get(), optLevel, libPaths.size(), libPaths.data(),
94 enableObjectDump, enablePIC);
95 if (mlirExecutionEngineIsNull(executionEngine))
96 throw std::runtime_error(
97 "Failure while creating the ExecutionEngine.");
98 new (&self) PyExecutionEngine(executionEngine);
99 },
100 nb::arg("module"), nb::arg("opt_level") = 2,
101 nb::arg("shared_libs") = nb::list(),
102 nb::arg("enable_object_dump") = true, nb::arg("enable_pic") = false,
103 "Create a new ExecutionEngine instance for the given Module. The "
104 "module must contain only dialects that can be translated to LLVM. "
105 "Perform transformations and code generation at the optimization "
106 "level `opt_level` if specified, or otherwise at the default "
107 "level of two (-O2). Load a list of libraries specified in "
108 "`shared_libs`.")
109 .def_prop_ro(MLIR_PYTHON_CAPI_PTR_ATTR, &PyExecutionEngine::getCapsule)
110 .def("_testing_release", &PyExecutionEngine::release,
111 "Releases (leaks) the backing ExecutionEngine (for testing purpose)")
112 .def(MLIR_PYTHON_CAPI_FACTORY_ATTR, &PyExecutionEngine::createFromCapsule)
113 .def(
114 "raw_lookup",
115 [](PyExecutionEngine &executionEngine, const std::string &func) {
117 executionEngine.get(),
118 mlirStringRefCreate(func.c_str(), func.size()));
119 return reinterpret_cast<uintptr_t>(res);
120 },
121 nb::arg("func_name"),
122 "Lookup function `func` in the ExecutionEngine.")
123 .def(
124 "raw_register_runtime",
125 [](PyExecutionEngine &executionEngine, const std::string &name,
126 const nb::object &callbackObj) {
127 executionEngine.addReferencedObject(callbackObj);
128 uintptr_t rawSym =
129 nb::cast<uintptr_t>(nb::getattr(callbackObj, "value"));
131 executionEngine.get(),
132 mlirStringRefCreate(name.c_str(), name.size()),
133 reinterpret_cast<void *>(rawSym));
134 },
135 nb::arg("name"), nb::arg("callback"),
136 "Register `callback` as the runtime symbol `name`.")
137 .def(
138 "initialize",
139 [](PyExecutionEngine &executionEngine) {
140 mlirExecutionEngineInitialize(executionEngine.get());
141 },
142 "Initialize the ExecutionEngine. Global constructors specified by "
143 "`llvm.mlir.global_ctors` will be run. One common scenario is that "
144 "kernel binary compiled from `gpu.module` gets loaded during "
145 "initialization. Make sure all symbols are resolvable before "
146 "initialization by calling `register_runtime` or including "
147 "shared libraries.")
148 .def(
149 "dump_to_object_file",
150 [](PyExecutionEngine &executionEngine, const std::string &fileName) {
152 executionEngine.get(),
153 mlirStringRefCreate(fileName.c_str(), fileName.size()));
154 },
155 nb::arg("file_name"), "Dump ExecutionEngine to an object file.");
156}
NB_MODULE(_mlirExecutionEngine, m)
Create the mlir.execution_engine module here.
static MlirExecutionEngine mlirPythonCapsuleToExecutionEngine(PyObject *capsule)
Extracts an MlirExecutionEngine from a capsule as produced from mlirPythonIntegerSetToCapsule.
Definition Interop.h:434
#define MLIR_PYTHON_CAPI_PTR_ATTR
Attribute on MLIR Python objects that expose their C-API pointer.
Definition Interop.h:97
static PyObject * mlirPythonExecutionEngineToCapsule(MlirExecutionEngine jit)
Creates a capsule object encapsulating the raw C-API MlirExecutionEngine.
Definition Interop.h:424
#define MLIR_PYTHON_CAPI_FACTORY_ATTR
Attribute on MLIR Python objects that exposes a factory function for constructing the corresponding P...
Definition Interop.h:110
MlirModule get()
Gets the backing MlirModule.
Definition IRCore.h:548
MLIR_CAPI_EXPORTED void * mlirExecutionEngineLookupPacked(MlirExecutionEngine jit, MlirStringRef name)
Lookup the wrapper of the native function in the execution engine with the given name,...
MLIR_CAPI_EXPORTED void mlirExecutionEngineDumpToObjectFile(MlirExecutionEngine jit, MlirStringRef fileName)
Dump as an object in fileName.
MLIR_CAPI_EXPORTED MlirExecutionEngine mlirExecutionEngineCreate(MlirModule op, int optLevel, int numPaths, const MlirStringRef *sharedLibPaths, bool enableObjectDump, bool enablePIC)
Creates an ExecutionEngine for the provided ModuleOp.
MLIR_CAPI_EXPORTED void mlirExecutionEngineDestroy(MlirExecutionEngine jit)
Destroy an ExecutionEngine instance.
MLIR_CAPI_EXPORTED void mlirExecutionEngineInitialize(MlirExecutionEngine jit)
Initialize the ExecutionEngine.
MLIR_CAPI_EXPORTED void mlirExecutionEngineRegisterSymbol(MlirExecutionEngine jit, MlirStringRef name, void *sym)
Register a symbol with the jit: this symbol will be accessible to the jitted code.
static bool mlirExecutionEngineIsNull(MlirExecutionEngine jit)
Checks whether an execution engine is null.
static MlirStringRef mlirStringRefCreate(const char *str, size_t length)
Constructs a string reference from the pointer and length.
Definition Support.h:87
Include the generated interface declarations.