blob: eeab87c48e5d21d4bf327c06ce353e09fcf186b8 [file] [log] [blame]
Uday Bondhugula6cd35022018-08-28 18:24:27 -07001//===- LoopUnrollAndJam.cpp - Code to perform loop unroll jam
2//----------------===//
3//
4// Copyright 2019 The MLIR Authors.
5//
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17// =============================================================================
18//
19// This file implements loop unroll jam for MLFunctions. Unroll and jam is a
20// transformation that improves locality, in particular, register reuse, while
21// also improving instruction level parallelism. The example below shows what it
22// does in nearly the general case. Loop unroll jam currently works if the
23// bounds of the loops inner to the loop being unroll-jammed do not depend on
24// the latter.
25//
26// Before After unroll-jam of i by factor 2:
27//
28// for i, step = 2
29// for i S1(i);
30// S1; S2(i);
31// S2; S1(i+1);
32// for j S2(i+1);
33// S3; for j
34// S4; S3(i, j);
35// S5; S4(i, j);
36// S6; S3(i+1, j)
37// S4(i+1, j)
38// S5(i);
39// S6(i);
40// S5(i+1);
41// S6(i+1);
42//
43// Note: 'if/else' blocks are not jammed. So, if there are loops inside if
44// stmt's, bodies of those loops will not be jammed.
45//
46//===----------------------------------------------------------------------===//
47#include "mlir/IR/AffineExpr.h"
48#include "mlir/IR/Builders.h"
49#include "mlir/IR/StandardOps.h"
50#include "mlir/IR/StmtVisitor.h"
51#include "mlir/Transforms/Pass.h"
52#include "mlir/Transforms/Passes.h"
53#include "llvm/ADT/DenseMap.h"
54#include "llvm/Support/CommandLine.h"
55
56using namespace mlir;
57using namespace llvm::cl;
58
59// Loop unroll jam factor.
60static llvm::cl::opt<unsigned>
61 clUnrollJamFactor("unroll-jam-factor", llvm::cl::Hidden,
62 llvm::cl::desc("Use this unroll jam factor for all loops"
63 " (default 4)"));
64
65namespace {
66/// Loop unroll jam pass. For test purposes, this just unroll jams the first
67/// outer loop in an MLFunction.
68struct LoopUnrollAndJam : public MLFunctionPass {
69 Optional<unsigned> unrollJamFactor;
70 static const unsigned kDefaultUnrollJamFactor = 4;
71
72 explicit LoopUnrollAndJam(Optional<unsigned> unrollJamFactor)
73 : unrollJamFactor(unrollJamFactor) {}
74
75 void runOnMLFunction(MLFunction *f) override;
76 bool runOnForStmt(ForStmt *forStmt);
77 bool loopUnrollJamByFactor(ForStmt *forStmt, unsigned unrollJamFactor);
78};
79} // end anonymous namespace
80
81MLFunctionPass *mlir::createLoopUnrollAndJamPass(int unrollJamFactor) {
82 return new LoopUnrollAndJam(
83 unrollJamFactor == -1 ? None : Optional<unsigned>(unrollJamFactor));
84}
85
86void LoopUnrollAndJam::runOnMLFunction(MLFunction *f) {
87 // Currently, just the outermost loop from the first loop nest is
88 // unroll-and-jammed by this pass. However, runOnForStmt can be called on any
89 // for Stmt.
90 if (!isa<ForStmt>(f->begin()))
91 return;
92
93 auto *forStmt = cast<ForStmt>(f->begin());
94 runOnForStmt(forStmt);
95}
96
97/// Unroll and jam a 'for' stmt. Default unroll jam factor is
98/// kDefaultUnrollJamFactor. Return false if nothing was done.
99bool LoopUnrollAndJam::runOnForStmt(ForStmt *forStmt) {
100 // Unroll and jam by the factor that was passed if any.
101 if (unrollJamFactor.hasValue())
102 return loopUnrollJamByFactor(forStmt, unrollJamFactor.getValue());
103 // Otherwise, unroll jam by the command-line factor if one was specified.
104 if (clUnrollJamFactor.getNumOccurrences() > 0)
105 return loopUnrollJamByFactor(forStmt, clUnrollJamFactor);
106
107 // Unroll and jam by four otherwise.
108 return loopUnrollJamByFactor(forStmt, kDefaultUnrollJamFactor);
109}
110
111/// Unrolls and jams this loop by the specified factor.
112bool LoopUnrollAndJam::loopUnrollJamByFactor(ForStmt *forStmt,
113 unsigned unrollJamFactor) {
114 assert(unrollJamFactor >= 1 && "unroll jam factor should be >= 1");
115
116 if (unrollJamFactor == 1 || forStmt->getStatements().empty())
117 return false;
118
119 if (!forStmt->hasConstantBounds())
120 return false;
121
122 // Gathers all maximal sub-blocks of statements that do not themselves include
123 // a for stmt (a statement could have a descendant for stmt though in its
124 // tree).
125 class JamBlockGatherer : public StmtWalker<JamBlockGatherer> {
126 public:
127 typedef llvm::iplist<Statement> StmtListType;
128
129 // Store iterators to the first and last stmt of each sub-block found.
130 std::vector<std::pair<StmtBlock::iterator, StmtBlock::iterator>> subBlocks;
131
132 // This is a linear time walk.
133 void walk(StmtListType::iterator Start, StmtListType::iterator End) {
134 for (auto it = Start; it != End;) {
135 auto subBlockStart = it;
136 while (it != End && !isa<ForStmt>(it))
137 ++it;
138 if (it != subBlockStart)
139 // Record the last statement (one behind the iterator) while not
140 // changing the iterator position.
141 subBlocks.push_back({subBlockStart, (--it)++});
142 // Process all for Stmts that appear next.
143 while (it != End && isa<ForStmt>(it))
144 walkForStmt(cast<ForStmt>(it++));
145 }
146 }
147 };
148
149 auto lb = forStmt->getConstantLowerBound();
150 auto ub = forStmt->getConstantUpperBound();
151 auto step = forStmt->getStep();
152
153 int64_t tripCount = (ub - lb + 1) % step == 0 ? (ub - lb + 1) / step
154 : (ub - lb + 1) / step + 1;
155
156 // If the trip count is lower than the unroll jam factor, no unrolled body.
157 // TODO(bondhugula): option to specify cleanup loop unrolling.
158 if (tripCount < unrollJamFactor)
159 return true;
160
161 // Gather all sub-blocks to jam upon the loop being unrolled.
162 JamBlockGatherer jbg;
163 jbg.walkForStmt(forStmt);
164 auto &subBlocks = jbg.subBlocks;
165
166 // Generate the cleanup loop if trip count isn't a multiple of
167 // unrollJamFactor.
168 if (tripCount % unrollJamFactor) {
169 DenseMap<const MLValue *, MLValue *> operandMap;
170 // Insert the cleanup loop right after 'forStmt'.
171 MLFuncBuilder builder(forStmt->getBlock(), ++StmtBlock::iterator(forStmt));
172 auto *cleanupForStmt = cast<ForStmt>(builder.clone(*forStmt, operandMap));
173 cleanupForStmt->setConstantLowerBound(
174 lb + (tripCount - tripCount % unrollJamFactor) * step);
175 }
176
177 MLFuncBuilder b(forStmt);
178 forStmt->setStep(step * unrollJamFactor);
179 forStmt->setConstantUpperBound(
180 lb + (tripCount - tripCount % unrollJamFactor - 1) * step);
181
182 for (auto &subBlock : subBlocks) {
183 // Builder to insert unroll-jammed bodies. Insert right at the end of
184 // sub-block.
185 MLFuncBuilder builder(subBlock.first->getBlock(),
186 std::next(subBlock.second));
187
188 // Unroll and jam (appends unrollJamFactor-1 additional copies).
189 for (unsigned i = 1; i < unrollJamFactor; i++) {
190 DenseMap<const MLValue *, MLValue *> operandMapping;
191
192 // If the induction variable is used, create a remapping to the value for
193 // this unrolled instance.
194 if (!forStmt->use_empty()) {
195 // iv' = iv + i, i = 1 to unrollJamFactor-1.
196 auto *bumpExpr = builder.getAddExpr(builder.getDimExpr(0),
197 builder.getConstantExpr(i * step));
198 auto *bumpMap = builder.getAffineMap(1, 0, {bumpExpr}, {});
199 auto *ivUnroll =
200 builder.create<AffineApplyOp>(forStmt->getLoc(), bumpMap, forStmt)
201 ->getResult(0);
202 operandMapping[forStmt] = cast<MLValue>(ivUnroll);
203 }
204 // Clone the sub-block being unroll-jammed (this doesn't include the last
205 // stmt because subBlock.second is inclusive).
206 for (auto it = subBlock.first; it != subBlock.second; ++it) {
207 builder.clone(*it, operandMapping);
208 }
209 // Clone the last statement of the sub-block.
210 builder.clone(*subBlock.second, operandMapping);
211 }
212 }
213 return true;
214}