Skip to content

Commit 7c53bf1

Browse files
committed
[mlir][python] auto-locs
1 parent 3212704 commit 7c53bf1

File tree

5 files changed

+254
-18
lines changed

5 files changed

+254
-18
lines changed

mlir/lib/Bindings/Python/Globals.h

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,23 @@
1010
#define MLIR_BINDINGS_PYTHON_GLOBALS_H
1111

1212
#include <optional>
13+
#include <regex>
1314
#include <string>
15+
#include <unordered_set>
1416
#include <vector>
1517

1618
#include "NanobindUtils.h"
1719
#include "mlir-c/IR.h"
1820
#include "mlir/CAPI/Support.h"
1921
#include "llvm/ADT/DenseMap.h"
22+
#include "llvm/ADT/DenseSet.h"
23+
#include "llvm/ADT/SmallVectorExtras.h"
24+
#include "llvm/ADT/StringExtras.h"
2025
#include "llvm/ADT/StringRef.h"
2126
#include "llvm/ADT/StringSet.h"
27+
#include "llvm/Support/Regex.h"
28+
29+
#include <iostream>
2230

2331
namespace mlir {
2432
namespace python {
@@ -114,11 +122,74 @@ class PyGlobals {
114122
std::optional<nanobind::object>
115123
lookupOperationClass(llvm::StringRef operationName);
116124

125+
bool locTracebacksEnabled() {
126+
nanobind::ft_lock_guard lock(mutex);
127+
return locTracebackEnabled_;
128+
}
129+
130+
void setLocTracebacksEnabled(bool value) {
131+
nanobind::ft_lock_guard lock(mutex);
132+
locTracebackEnabled_ = value;
133+
}
134+
135+
size_t locTracebackFramesLimit() {
136+
nanobind::ft_lock_guard lock(mutex);
137+
return locTracebackFramesLimit_;
138+
}
139+
140+
void setLocTracebackFramesLimit(size_t value) {
141+
nanobind::ft_lock_guard lock(mutex);
142+
locTracebackFramesLimit_ = value;
143+
}
144+
145+
void registerTracebackFileInclusion(std::string &file) {
146+
nanobind::ft_lock_guard lock(mutex);
147+
userTracebackIncludeFiles.insert(file);
148+
userTracebackIncludeRegex.assign(
149+
llvm::join(llvm::map_range(userTracebackIncludeFiles,
150+
[](llvm::StringRef path) {
151+
return "^" + llvm::Regex::escape(path);
152+
}),
153+
"|"));
154+
isUserTracebackFilenameCache.clear();
155+
}
156+
157+
void registerTracebackFileExclusion(std::string &file) {
158+
nanobind::ft_lock_guard lock(mutex);
159+
userTracebackExcludeFiles.insert(file);
160+
userTracebackExcludeRegex.assign(
161+
llvm::join(llvm::map_range(userTracebackExcludeFiles,
162+
[](llvm::StringRef path) {
163+
return "^" + llvm::Regex::escape(path);
164+
}),
165+
"|"));
166+
isUserTracebackFilenameCache.clear();
167+
}
168+
169+
bool isUserTracebackFilename(llvm::StringRef file) {
170+
nanobind::ft_lock_guard lock(mutex);
171+
if (!isUserTracebackFilenameCache.contains(file)) {
172+
std::string fileStr = file.str();
173+
bool include = std::regex_search(fileStr, userTracebackIncludeRegex);
174+
bool exclude = std::regex_search(fileStr, userTracebackExcludeRegex);
175+
isUserTracebackFilenameCache[file] = include || !exclude;
176+
}
177+
return isUserTracebackFilenameCache[file];
178+
}
179+
117180
private:
118181
static PyGlobals *instance;
119182

120183
nanobind::ft_mutex mutex;
121184

185+
bool locTracebackEnabled_ = false;
186+
size_t locTracebackFramesLimit_ = 10;
187+
std::unordered_set<std::string> userTracebackIncludeFiles;
188+
std::unordered_set<std::string> userTracebackExcludeFiles;
189+
std::regex userTracebackIncludeRegex;
190+
std::regex userTracebackExcludeRegex;
191+
llvm::StringMap<bool> isUserTracebackFilenameCache;
192+
122193
/// Module name prefixes to search under for dialect implementation modules.
123194
std::vector<std::string> dialectSearchPrefixes;
124195
/// Map of dialect namespace to external dialect class object.

mlir/lib/Bindings/Python/IRCore.cpp

Lines changed: 128 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include "llvm/ADT/SmallVector.h"
2323
#include "llvm/Support/raw_ostream.h"
2424

25+
#include <iostream>
2526
#include <optional>
2627
#include <system_error>
2728
#include <utility>
@@ -1523,7 +1524,7 @@ nb::object PyOperation::create(std::string_view name,
15231524
llvm::ArrayRef<MlirValue> operands,
15241525
std::optional<nb::dict> attributes,
15251526
std::optional<std::vector<PyBlock *>> successors,
1526-
int regions, DefaultingPyLocation ___location,
1527+
int regions, PyLocation ___location,
15271528
const nb::object &maybeIp, bool inferType) {
15281529
llvm::SmallVector<MlirType, 4> mlirResults;
15291530
llvm::SmallVector<MlirBlock, 4> mlirSuccessors;
@@ -1627,7 +1628,7 @@ nb::object PyOperation::create(std::string_view name,
16271628
if (!operation.ptr)
16281629
throw nb::value_error("Operation creation failed");
16291630
PyOperationRef created =
1630-
PyOperation::createDetached(___location->getContext(), operation);
1631+
PyOperation::createDetached(___location.getContext(), operation);
16311632
maybeInsertOperation(created, maybeIp);
16321633

16331634
return created.getObject();
@@ -1937,9 +1938,9 @@ nb::object PyOpView::buildGeneric(
19371938
std::optional<nb::list> resultTypeList, nb::list operandList,
19381939
std::optional<nb::dict> attributes,
19391940
std::optional<std::vector<PyBlock *>> successors,
1940-
std::optional<int> regions, DefaultingPyLocation ___location,
1941+
std::optional<int> regions, PyLocation ___location,
19411942
const nb::object &maybeIp) {
1942-
PyMlirContextRef context = ___location->getContext();
1943+
PyMlirContextRef context = ___location.getContext();
19431944

19441945
// Class level operation construction metadata.
19451946
// Operand and result segment specs are either none, which does no
@@ -2789,6 +2790,94 @@ class PyOpAttributeMap {
27892790
PyOperationRef operation;
27902791
};
27912792

2793+
// bpo-40421 added PyFrame_GetLasti() to Python 3.11.0b1
2794+
#if PY_VERSION_HEX < 0x030b00b1 && !defined(PYPY_VERSION)
2795+
int PyFrame_GetLasti(PyFrameObject *frame) {
2796+
#if PY_VERSION_HEX >= 0x030a00a7
2797+
// bpo-27129: Since Python 3.10.0a7, f_lasti is an instruction offset,
2798+
// not a bytes offset anymore. Python uses 16-bit "wordcode" (2 bytes)
2799+
// instructions.
2800+
if (frame->f_lasti < 0) {
2801+
return -1;
2802+
}
2803+
return frame->f_lasti * 2;
2804+
#else
2805+
return frame->f_lasti;
2806+
#endif
2807+
}
2808+
#endif
2809+
2810+
std::optional<MlirLocation> tracebackToLocation(MlirContext ctx) {
2811+
size_t framesLimit = PyGlobals::get().locTracebackFramesLimit();
2812+
// We use a thread_local here mostly to avoid requiring a large amount of
2813+
// space.
2814+
thread_local std::vector<MlirLocation> frames;
2815+
frames.reserve(framesLimit);
2816+
size_t count = 0;
2817+
2818+
assert(PyGILState_Check());
2819+
2820+
if (!PyGlobals::get().locTracebacksEnabled())
2821+
return std::nullopt;
2822+
2823+
PyThreadState *tstate = PyThreadState_GET();
2824+
2825+
PyFrameObject *next;
2826+
for (PyFrameObject *pyFrame = PyThreadState_GetFrame(tstate);
2827+
pyFrame != nullptr && count < framesLimit;
2828+
next = PyFrame_GetBack(pyFrame), Py_XDECREF(pyFrame), pyFrame = next) {
2829+
PyCodeObject *code = PyFrame_GetCode(pyFrame);
2830+
auto fileNameStr =
2831+
nb::cast<std::string>(nb::borrow<nb::str>(code->co_filename));
2832+
llvm::StringRef fileName(fileNameStr);
2833+
if (!PyGlobals::get().isUserTracebackFilename(fileName))
2834+
continue;
2835+
2836+
#if PY_VERSION_HEX < 0x030b00f0
2837+
std::string name =
2838+
nb::cast<std::string>(nb::borrow<nb::str>(code->co_name));
2839+
llvm::StringRef funcName(name);
2840+
int startLine = PyFrame_GetLineNumber(pyFrame);
2841+
MlirLocation loc =
2842+
mlirLocationFileLineColGet(ctx, wrap(fileName), startLine, 0);
2843+
#else
2844+
// co_qualname added in py3.11
2845+
std::string name =
2846+
nb::cast<std::string>(nb::borrow<nb::str>(code->co_qualname));
2847+
llvm::StringRef funcName(name);
2848+
int startLine, startCol, endLine, endCol;
2849+
int lasti = PyFrame_GetLasti(pyFrame);
2850+
if (!PyCode_Addr2Location(code, lasti, &startLine, &startCol, &endLine,
2851+
&endCol)) {
2852+
throw nb::python_error();
2853+
}
2854+
MlirLocation loc = mlirLocationFileLineColRangeGet(
2855+
ctx, wrap(fileName), startCol, startCol, endLine, endCol);
2856+
#endif
2857+
2858+
frames.push_back(mlirLocationNameGet(ctx, wrap(funcName), loc));
2859+
++count;
2860+
if (count > framesLimit)
2861+
break;
2862+
}
2863+
2864+
if (frames.empty())
2865+
return mlirLocationUnknownGet(ctx);
2866+
if (frames.size() == 1)
2867+
return frames.front();
2868+
2869+
MlirLocation callee = frames.front();
2870+
frames.erase(frames.begin());
2871+
MlirLocation caller = frames.back();
2872+
for (const MlirLocation &frame :
2873+
llvm::reverse(llvm::ArrayRef(frames).drop_back()))
2874+
caller = mlirLocationCallSiteGet(frame, caller);
2875+
2876+
// TODO(max): this is a hack - use std::array and decrement count instead
2877+
frames.clear();
2878+
return mlirLocationCallSiteGet(callee, caller);
2879+
}
2880+
27922881
} // namespace
27932882

27942883
//------------------------------------------------------------------------------
@@ -3241,7 +3330,11 @@ void mlir::python::populateIRCore(nb::module_ &m) {
32413330
.def_static(
32423331
"create",
32433332
[](DefaultingPyLocation loc) {
3244-
MlirModule module = mlirModuleCreateEmpty(loc);
3333+
PyMlirContextRef ctx = loc->getContext();
3334+
MlirLocation mlirLoc = loc;
3335+
if (auto tloc = tracebackToLocation(ctx->get()))
3336+
mlirLoc = *tloc;
3337+
MlirModule module = mlirModuleCreateEmpty(mlirLoc);
32453338
return PyModule::forModule(module).releaseObject();
32463339
},
32473340
nb::arg("loc").none() = nb::none(), "Creates an empty module")
@@ -3467,9 +3560,15 @@ void mlir::python::populateIRCore(nb::module_ &m) {
34673560
}
34683561
}
34693562

3563+
PyMlirContextRef ctx = ___location->getContext();
3564+
if (auto loc = tracebackToLocation(ctx->get())) {
3565+
return PyOperation::create(name, results, mlirOperands,
3566+
attributes, successors, regions,
3567+
{ctx, *loc}, maybeIp, inferType);
3568+
}
34703569
return PyOperation::create(name, results, mlirOperands, attributes,
3471-
successors, regions, ___location, maybeIp,
3472-
inferType);
3570+
successors, regions, *___location.get(),
3571+
maybeIp, inferType);
34733572
},
34743573
nb::arg("name"), nb::arg("results").none() = nb::none(),
34753574
nb::arg("operands").none() = nb::none(),
@@ -3514,10 +3613,19 @@ void mlir::python::populateIRCore(nb::module_ &m) {
35143613
std::optional<std::vector<PyBlock *>> successors,
35153614
std::optional<int> regions, DefaultingPyLocation ___location,
35163615
const nb::object &maybeIp) {
3517-
new (self) PyOpView(PyOpView::buildGeneric(
3518-
name, opRegionSpec, operandSegmentSpecObj,
3519-
resultSegmentSpecObj, resultTypeList, operandList,
3520-
attributes, successors, regions, ___location, maybeIp));
3616+
PyMlirContextRef ctx = ___location->getContext();
3617+
if (auto loc = tracebackToLocation(ctx->get())) {
3618+
new (self) PyOpView(PyOpView::buildGeneric(
3619+
name, opRegionSpec, operandSegmentSpecObj,
3620+
resultSegmentSpecObj, resultTypeList, operandList,
3621+
attributes, successors, regions, {ctx, *loc}, maybeIp));
3622+
} else {
3623+
new (self) PyOpView(PyOpView::buildGeneric(
3624+
name, opRegionSpec, operandSegmentSpecObj,
3625+
resultSegmentSpecObj, resultTypeList, operandList,
3626+
attributes, successors, regions, *___location.get(),
3627+
maybeIp));
3628+
}
35213629
},
35223630
nb::arg("name"), nb::arg("opRegionSpec"),
35233631
nb::arg("operandSegmentSpecObj").none() = nb::none(),
@@ -3558,10 +3666,18 @@ void mlir::python::populateIRCore(nb::module_ &m) {
35583666
nb::cast<std::tuple<int, bool>>(cls.attr("_ODS_REGIONS"));
35593667
nb::object operandSegmentSpec = cls.attr("_ODS_OPERAND_SEGMENTS");
35603668
nb::object resultSegmentSpec = cls.attr("_ODS_RESULT_SEGMENTS");
3669+
3670+
PyMlirContextRef ctx = ___location->getContext();
3671+
if (auto loc = tracebackToLocation(ctx->get())) {
3672+
return PyOpView::buildGeneric(name, opRegionSpec, operandSegmentSpec,
3673+
resultSegmentSpec, resultTypeList,
3674+
operandList, attributes, successors,
3675+
regions, {ctx, *loc}, maybeIp);
3676+
}
35613677
return PyOpView::buildGeneric(name, opRegionSpec, operandSegmentSpec,
35623678
resultSegmentSpec, resultTypeList,
35633679
operandList, attributes, successors,
3564-
regions, ___location, maybeIp);
3680+
regions, *___location.get(), maybeIp);
35653681
},
35663682
nb::arg("cls"), nb::arg("results").none() = nb::none(),
35673683
nb::arg("operands").none() = nb::none(),

mlir/lib/Bindings/Python/IRModule.h

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -722,8 +722,7 @@ class PyOperation : public PyOperationBase, public BaseContextObject {
722722
llvm::ArrayRef<MlirValue> operands,
723723
std::optional<nanobind::dict> attributes,
724724
std::optional<std::vector<PyBlock *>> successors, int regions,
725-
DefaultingPyLocation ___location, const nanobind::object &ip,
726-
bool inferType);
725+
PyLocation ___location, const nanobind::object &ip, bool inferType);
727726

728727
/// Creates an OpView suitable for this operation.
729728
nanobind::object createOpView();
@@ -781,7 +780,7 @@ class PyOpView : public PyOperationBase {
781780
nanobind::list operandList,
782781
std::optional<nanobind::dict> attributes,
783782
std::optional<std::vector<PyBlock *>> successors,
784-
std::optional<int> regions, DefaultingPyLocation ___location,
783+
std::optional<int> regions, PyLocation ___location,
785784
const nanobind::object &maybeIp);
786785

787786
/// Construct an instance of a class deriving from OpView, bypassing its

mlir/lib/Bindings/Python/MainModule.cpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
//
77
//===----------------------------------------------------------------------===//
88

9-
109
#include "Globals.h"
1110
#include "IRModule.h"
1211
#include "NanobindUtils.h"
@@ -44,7 +43,15 @@ NB_MODULE(_mlir, m) {
4443
.def("_register_operation_impl", &PyGlobals::registerOperationImpl,
4544
"operation_name"_a, "operation_class"_a, nb::kw_only(),
4645
"replace"_a = false,
47-
"Testing hook for directly registering an operation");
46+
"Testing hook for directly registering an operation")
47+
.def("loc_tracebacks_enabled", &PyGlobals::locTracebacksEnabled)
48+
.def("set_loc_tracebacks_enabled", &PyGlobals::setLocTracebacksEnabled)
49+
.def("set_loc_tracebacks_frame_limit",
50+
&PyGlobals::setLocTracebackFramesLimit)
51+
.def("register_traceback_file_inclusion",
52+
&PyGlobals::registerTracebackFileInclusion)
53+
.def("register_traceback_file_exclusion",
54+
&PyGlobals::registerTracebackFileExclusion);
4855

4956
// Aside from making the globals accessible to python, having python manage
5057
// it is necessary to make sure it is destroyed (and releases its python

0 commit comments

Comments
 (0)