Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions src/dialect/VxLowering.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
#include "mlir/Conversion/LLVMCommon/Pattern.h"
#include "mlir/Conversion/LLVMCommon/TypeConverter.h"
#include "mlir/Conversion/Passes.h"
#include "mlir/Dialect/Affine/Analysis/LoopAnalysis.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Affine/LoopUtils.h"
#include "mlir/Dialect/Affine/Utils.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Arith/Transforms/Passes.h"
Expand Down Expand Up @@ -13908,6 +13910,58 @@ struct FuseAndTileLoopsPass
}
};

// Unrolls 4 times each innermost affine loop with a constant trip count.
//
// The upstream `affine-loop-unroll` also unrolls a loop whose trip count is not
// a constant. The loop that it adds for the last iterations starts below the
// lower bound when the upper bound is below it, so an empty loop runs. LLVM can
// unroll such loops later.
struct UnrollLoopsPass
: public PassWrapper<UnrollLoopsPass, OperationPass<func::FuncOp>> {
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(UnrollLoopsPass)

llvm::StringRef getArgument() const override { return "vx-unroll-loops"; }

llvm::StringRef getDescription() const override {
return "Unrolls 4 times each innermost affine loop with a constant trip "
"count";
}

void getDependentDialects(DialectRegistry &registry) const override {
registry.insert<affine::AffineDialect>();
}

// Whether the trip count of `loop` is a constant. A negative difference of
// the bounds does not count, because `getConstantTripCount` reads it as a
// large unsigned number.
static bool hasConstantTripCount(affine::AffineForOp loop) {
AffineMap map;
SmallVector<Value> operands;
affine::getTripCountMapAndOperands(loop, &map, &operands);
if (!map || map.getNumResults() == 0)
return false;
return llvm::all_of(map.getResults(), [](AffineExpr result) {
auto count = dyn_cast<AffineConstantExpr>(result);
return count && count.getValue() >= 0;
});
}

void runOnOperation() override {
SmallVector<affine::AffineForOp> loops;
getOperation().walk([&](affine::AffineForOp loop) {
bool innermost = !loop.getBody()
->walk([](affine::AffineForOp) {
return WalkResult::interrupt();
})
.wasInterrupted();
if (innermost && hasConstantTripCount(loop))
loops.push_back(loop);
});
for (affine::AffineForOp loop : loops)
(void)affine::loopUnrollByFactor(loop, 4);
}
};

// Raise the loads and stores in affine loops to affine ops, so that loop fusion
// and `affine-scalrep` can see them.
//
Expand Down Expand Up @@ -15052,6 +15106,9 @@ void registerVxPasses() {
mlir::registerPass([]() -> std::unique_ptr<mlir::Pass> {
return std::make_unique<RaiseLoopAccessesPass>();
});
mlir::registerPass([]() -> std::unique_ptr<mlir::Pass> {
return std::make_unique<UnrollLoopsPass>();
});
mlir::registerPass([]() -> std::unique_ptr<mlir::Pass> {
return std::make_unique<LinalgToAffineLoopsPass>();
});
Expand Down
3 changes: 2 additions & 1 deletion src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2279,11 +2279,12 @@ fn get_optimization_pipeline(
// makes their loads and stores affine.
// Fusion and tiling run only where no two buffers can alias; see the pass. Only small
// functions are inlined, so deeply nested calls do not multiply the code.
// `vx-unroll-loops` unrolls only the loops with a constant trip count.
passes.push("vx-inline".to_string());
passes.push("canonicalize".to_string());
passes.push("cse".to_string());
passes.push(
"func.func(vx-linalg-to-affine-loops,vx-raise-loop-accesses,vx-fuse-and-tile-loops,affine-loop-unroll,affine-scalrep)"
"func.func(vx-linalg-to-affine-loops,vx-raise-loop-accesses,vx-fuse-and-tile-loops,vx-unroll-loops,affine-scalrep)"
.to_string(),
);
passes.push("lower-affine".to_string());
Expand Down
61 changes: 61 additions & 0 deletions tests/backend/pass/for_loop_over_an_empty_range.vx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//===- for_loop_over_an_empty_range.vx - Vx Compiler -----------*- Vx -*-===//
//
// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions.
// See LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// A `for` loop over an empty range, such as `2..1`, runs no times. At -O2 the compiler unrolled a
// loop with bounds known only at run time. The loop that it added for the last iterations started
// below the start of the range, so `2..1` ran for -2, -1 and 0. The loop of `count_to_six` has
// constant bounds. The compiler still unrolls it, and its numbers must not change.
//
// RUN: env VX_NO_AST_FALLBACK=1 vxc %s --run 2>&1 | FileCheck %s
// RUN: vxc %s --run -O2 2>&1 | FileCheck %s
// CHECK: count 2..1: seen=0
// CHECK-NEXT: 2 3 4 5 6 7
// CHECK-NEXT: count 2..8: seen=6
// CHECK-NEXT: 0 1 2 3 4 5
// CHECK-NEXT: count_to_six: seen=6
import std::vec;

// Prints each number from `lo` up to `hi`, and returns how many it printed. The `if` after the
// loop reads `seen`, so the compiler does not tile the loop.
fn count(lo : i32, hi : i32) -> i32 {
let mut seen = 0;
for p in lo..hi {
print!("{} ", p);
seen += 1;
}
if seen > 0 {
println!("");
}
return seen;
}

// Prints each number from 0 up to 6, and returns how many it printed. The loop runs 6 times,
// which is not a multiple of 4.
fn count_to_six() -> i32 {
let mut seen = 0;
for p in 0..6 {
print!("{} ", p);
seen += 1;
}
if seen > 0 {
println!("");
}
return seen;
}

fn main() -> i32 {
// The bounds come from a Vec, so that the compiler does not know them.
let mut bounds = Vec<i32>::new();
bounds.push(2);
bounds.push(1);
bounds.push(8);
let lo = bounds.get(0);
println!("count 2..1: seen={}", count(lo, bounds.get(1)));
println!("count 2..8: seen={}", count(lo, bounds.get(2)));
println!("count_to_six: seen={}", count_to_six());
return 0;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// RUN: vx-opt %s --pass-pipeline="builtin.module(func.func(vx-unroll-loops))" | FileCheck %s

// `vx-unroll-loops` unrolls 4 times each innermost loop with a constant trip count. It adds a loop
// for the last iterations. It does not change a loop whose trip count is not a constant. The
// upstream `affine-loop-unroll` unrolls such a loop too. When its range is empty, the loop for the
// last iterations starts below the lower bound, and it runs.

// The bounds of the loops below.
// CHECK: #[[PLUS4:map[0-9]*]] = affine_map<()[s0] -> (s0 + 4)>
// CHECK: #[[PLUS6:map[0-9]*]] = affine_map<()[s0] -> (s0 + 6)>
// CHECK: #[[MINUS2:map[0-9]*]] = affine_map<()[s0] -> (s0 - 2)>
#plus6 = affine_map<()[s0] -> (s0 + 6)>
#minus2 = affine_map<()[s0] -> (s0 - 2)>

module {
func.func private @use(index)

// 6 iterations: 4 copies of the body, and then a loop for the last 2.
// CHECK-LABEL: func.func @zero_to_six
// CHECK-COUNT-4: call @use
// CHECK-NEXT: affine.for %{{.*}} = 4 to 6 {
func.func @zero_to_six() {
affine.for %i = 0 to 6 {
func.call @use(%i) : (index) -> ()
}
return
}

// The bounds are not constants, but they differ by 6. So this loop has 6 iterations too.
// CHECK-LABEL: func.func @a_to_a_plus_six
// CHECK-COUNT-4: call @use
// CHECK-NEXT: affine.for %{{.*}} = #[[PLUS4]]()[%{{.*}}] to #[[PLUS6]]()[%{{.*}}] {
func.func @a_to_a_plus_six(%a: index) {
affine.for %i = %a to #plus6()[%a] {
func.call @use(%i) : (index) -> ()
}
return
}

// The bounds differ by -2, so the range is empty. The loop does not change.
// CHECK-LABEL: func.func @a_to_a_minus_two(
// CHECK-SAME: %[[A:.*]]: index)
// CHECK-NEXT: affine.for %[[I:.*]] = %[[A]] to #[[MINUS2]]()[%[[A]]] {
// CHECK-NEXT: func.call @use(%[[I]])
// CHECK-NEXT: }
// CHECK-NEXT: return
func.func @a_to_a_minus_two(%a: index) {
affine.for %i = %a to #minus2()[%a] {
func.call @use(%i) : (index) -> ()
}
return
}

// The trip count is not a constant. The loop does not change.
// CHECK-LABEL: func.func @lo_to_hi(
// CHECK-SAME: %[[LO:.*]]: index, %[[HI:.*]]: index)
// CHECK-NEXT: affine.for %[[I:.*]] = %[[LO]] to %[[HI]] {
// CHECK-NEXT: func.call @use(%[[I]])
// CHECK-NEXT: }
// CHECK-NEXT: return
func.func @lo_to_hi(%lo: index, %hi: index) {
affine.for %i = %lo to %hi {
func.call @use(%i) : (index) -> ()
}
return
}
}
Loading