Skip to content

Commit 91a257e

Browse files
committed
compiler: fix orelse branch location
When the else was in a nest for loop the else terminator was branching to the end of the outer loop instead of the inner one.
1 parent 25ce041 commit 91a257e

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

integration/tests/for.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
def test_else_branch():
2+
a = []
3+
for el in ["a", "b", "c"]:
4+
for _ in a:
5+
pass
6+
else:
7+
a.append(el)
8+
return a
9+
10+
assert test_else_branch() == ["a", "b", "c"]

src/executable/mlir/Conversion/PythonToPythonBytecode/PythonToPythonBytecode.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1272,6 +1272,11 @@ namespace py {
12721272
mlir::Block *end_block) const
12731273
{
12741274
return [this, &rewriter, condition_start, end_block](mlir::Operation *operation) {
1275+
auto parent_is_orelse = [](mlir::Operation *operation) {
1276+
auto forloop_op = operation->getParentOfType<mlir::py::ForLoopOp>();
1277+
if (!forloop_op) { return false; }
1278+
return &forloop_op.getOrelse() == operation->getParentRegion();
1279+
};
12751280
// llvm::outs() << "ForOpLowering 1:\n";
12761281
// operation->print(llvm::outs());
12771282
// llvm::outs() << '\n';
@@ -1308,6 +1313,9 @@ namespace py {
13081313
&& mlir::isa<TryOp, WithOp, TryHandlerScope>(yield_op->getParentOp())) {
13091314
return WalkResult::advance();
13101315
}
1316+
// is this hacky? maybe there is a better way of ignoring the else branch of
1317+
// a for loop
1318+
if (parent_is_orelse(operation)) { return WalkResult::advance(); }
13111319
rewriter.setInsertionPoint(yield_op);
13121320
if (!yield_op.getKind().has_value()
13131321
|| yield_op.getKind().value() == py::LoopOpKind::continue_) {
@@ -2215,6 +2223,11 @@ namespace py {
22152223
config.enableRegionSimplification = GreedySimplifyRegionLevel::Disabled;
22162224
config.useTopDownTraversal = true;
22172225
FrozenRewritePatternSet frozen_patterns{ std::move(patterns) };
2226+
2227+
// getOperation()->print(llvm::outs());
2228+
// llvm::outs() << "-----------------------------------------------\n\n\n";
2229+
// llvm::outs().flush();
2230+
22182231
// Currently ignoring the return value as it seems to always fail, even though the
22192232
// transformation seems to generate the expected output
22202233
(void)applyPatternsAndFoldGreedily(getOperation(), frozen_patterns, config);

0 commit comments

Comments
 (0)