blob: ffb29473c4730ab729a23bd8f73e7d6ffe6228a9 [file] [log] [blame]
Chris Lattneree0c2ae2018-07-29 12:37:35 -07001//===- Unroll.cpp - Code to perform loop unrolling ------------------------===//
Uday Bondhugula0b4059b2018-07-24 20:01:16 -07002//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17//
18// This file implements loop unrolling.
19//
20//===----------------------------------------------------------------------===//
21
Uday Bondhugula15984952018-08-01 22:36:12 -070022#include "mlir/IR/Attributes.h"
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070023#include "mlir/IR/Builders.h"
24#include "mlir/IR/CFGFunction.h"
25#include "mlir/IR/MLFunction.h"
26#include "mlir/IR/Module.h"
27#include "mlir/IR/OperationSet.h"
Uday Bondhugula84b80952018-08-03 13:22:26 -070028#include "mlir/IR/StandardOps.h"
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070029#include "mlir/IR/Statements.h"
30#include "mlir/IR/StmtVisitor.h"
Uday Bondhugula6c1f6602018-08-13 17:25:13 -070031#include "mlir/Transforms/Pass.h"
Chris Lattneree0c2ae2018-07-29 12:37:35 -070032#include "mlir/Transforms/Passes.h"
Chris Lattnere787b322018-08-08 11:14:57 -070033#include "llvm/ADT/DenseMap.h"
Uday Bondhugula67701712018-08-21 16:01:23 -070034#include "llvm/Support/CommandLine.h"
Uday Bondhugula081d9e72018-07-27 10:58:14 -070035#include "llvm/Support/raw_ostream.h"
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070036
37using namespace mlir;
Uday Bondhugula67701712018-08-21 16:01:23 -070038using namespace llvm;
39
40// Loop unrolling factor.
41static llvm::cl::opt<unsigned>
42 clUnrollFactor("unroll-factor", cl::Hidden,
43 cl::desc("Use this unroll factor for all loops"));
44
45static llvm::cl::opt<bool> clUnrollFull("unroll-full", cl::Hidden,
46 cl::desc("Fully unroll loops"));
47
48static llvm::cl::opt<unsigned> clUnrollFullThreshold(
49 "unroll-full-threshold", cl::Hidden,
50 cl::desc("Unroll all loops with trip count less than or equal to this"));
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070051
52namespace {
Uday Bondhugula67701712018-08-21 16:01:23 -070053/// Loop unrolling pass. Unrolls all innermost loops unless full unrolling and a
54/// full unroll threshold was specified, in which case, fully unrolls all loops
55/// with trip count less than the specified threshold. The latter is for testing
56/// purposes, especially for testing outer loop unrolling.
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070057struct LoopUnroll : public MLFunctionPass {
Uday Bondhugula67701712018-08-21 16:01:23 -070058 Optional<unsigned> unrollFactor;
59 Optional<bool> unrollFull;
Uday Bondhugula0077e622018-08-16 13:51:44 -070060
Uday Bondhugula67701712018-08-21 16:01:23 -070061 explicit LoopUnroll(Optional<unsigned> unrollFactor,
62 Optional<bool> unrollFull)
63 : unrollFactor(unrollFactor), unrollFull(unrollFull) {}
64
Uday Bondhugula134154e2018-08-06 18:40:34 -070065 void runOnMLFunction(MLFunction *f) override;
Uday Bondhugula67701712018-08-21 16:01:23 -070066 /// Unroll this for stmt. Returns false if nothing was done.
67 bool runOnForStmt(ForStmt *forStmt);
68 bool loopUnrollFull(ForStmt *forStmt);
69 bool loopUnrollByFactor(ForStmt *forStmt, unsigned unrollFactor);
Uday Bondhugula134154e2018-08-06 18:40:34 -070070};
Chris Lattneree0c2ae2018-07-29 12:37:35 -070071} // end anonymous namespace
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070072
Uday Bondhugula67701712018-08-21 16:01:23 -070073MLFunctionPass *mlir::createLoopUnrollPass(int unrollFactor, int unrollFull) {
74 return new LoopUnroll(unrollFactor == -1 ? None
75 : Optional<unsigned>(unrollFactor),
76 unrollFull == -1 ? None : Optional<bool>(unrollFull));
Uday Bondhugula134154e2018-08-06 18:40:34 -070077}
78
Chris Lattneree0c2ae2018-07-29 12:37:35 -070079void LoopUnroll::runOnMLFunction(MLFunction *f) {
Uday Bondhugula081d9e72018-07-27 10:58:14 -070080 // Gathers all innermost loops through a post order pruned walk.
Uday Bondhugula081d9e72018-07-27 10:58:14 -070081 class InnermostLoopGatherer : public StmtWalker<InnermostLoopGatherer, bool> {
82 public:
83 // Store innermost loops as we walk.
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070084 std::vector<ForStmt *> loops;
Uday Bondhugula081d9e72018-07-27 10:58:14 -070085
86 // This method specialized to encode custom return logic.
87 typedef llvm::iplist<Statement> StmtListType;
Uday Bondhugula8572d1a2018-07-30 10:49:49 -070088 bool walkPostOrder(StmtListType::iterator Start,
89 StmtListType::iterator End) {
Uday Bondhugula15984952018-08-01 22:36:12 -070090 bool hasInnerLoops = false;
91 // We need to walk all elements since all innermost loops need to be
92 // gathered as opposed to determining whether this list has any inner
93 // loops or not.
Uday Bondhugula081d9e72018-07-27 10:58:14 -070094 while (Start != End)
Uday Bondhugula15984952018-08-01 22:36:12 -070095 hasInnerLoops |= walkPostOrder(&(*Start++));
96 return hasInnerLoops;
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070097 }
Uday Bondhugula081d9e72018-07-27 10:58:14 -070098
Uday Bondhugula8572d1a2018-07-30 10:49:49 -070099 bool walkForStmtPostOrder(ForStmt *forStmt) {
100 bool hasInnerLoops = walkPostOrder(forStmt->begin(), forStmt->end());
Uday Bondhugula081d9e72018-07-27 10:58:14 -0700101 if (!hasInnerLoops)
102 loops.push_back(forStmt);
103 return true;
104 }
105
Uday Bondhugula8572d1a2018-07-30 10:49:49 -0700106 bool walkIfStmtPostOrder(IfStmt *ifStmt) {
Chris Lattnere787b322018-08-08 11:14:57 -0700107 bool hasInnerLoops =
108 walkPostOrder(ifStmt->getThen()->begin(), ifStmt->getThen()->end());
109 hasInnerLoops |=
110 walkPostOrder(ifStmt->getElse()->begin(), ifStmt->getElse()->end());
Uday Bondhugula15984952018-08-01 22:36:12 -0700111 return hasInnerLoops;
Uday Bondhugula081d9e72018-07-27 10:58:14 -0700112 }
113
Uday Bondhugula134154e2018-08-06 18:40:34 -0700114 bool visitOperationStmt(OperationStmt *opStmt) { return false; }
Uday Bondhugula081d9e72018-07-27 10:58:14 -0700115
Uday Bondhugula134154e2018-08-06 18:40:34 -0700116 // FIXME: can't use base class method for this because that in turn would
117 // need to use the derived class method above. CRTP doesn't allow it, and
118 // the compiler error resulting from it is also misleading.
Uday Bondhugula8572d1a2018-07-30 10:49:49 -0700119 using StmtWalker<InnermostLoopGatherer, bool>::walkPostOrder;
Uday Bondhugula0b4059b2018-07-24 20:01:16 -0700120 };
121
Uday Bondhugula134154e2018-08-06 18:40:34 -0700122 // Gathers all loops with trip count <= minTripCount.
123 class ShortLoopGatherer : public StmtWalker<ShortLoopGatherer> {
124 public:
125 // Store short loops as we walk.
126 std::vector<ForStmt *> loops;
127 const unsigned minTripCount;
128 ShortLoopGatherer(unsigned minTripCount) : minTripCount(minTripCount) {}
Uday Bondhugula15984952018-08-01 22:36:12 -0700129
Uday Bondhugula134154e2018-08-06 18:40:34 -0700130 void visitForStmt(ForStmt *forStmt) {
131 auto lb = forStmt->getLowerBound()->getValue();
132 auto ub = forStmt->getUpperBound()->getValue();
Uday Bondhugula67701712018-08-21 16:01:23 -0700133 auto step = forStmt->getStep();
Uday Bondhugula15984952018-08-01 22:36:12 -0700134
Uday Bondhugula134154e2018-08-06 18:40:34 -0700135 if ((ub - lb) / step + 1 <= minTripCount)
136 loops.push_back(forStmt);
Uday Bondhugula15984952018-08-01 22:36:12 -0700137 }
138 };
139
Uday Bondhugula67701712018-08-21 16:01:23 -0700140 if (clUnrollFull.getNumOccurrences() > 0 &&
141 clUnrollFullThreshold.getNumOccurrences() > 0) {
142 ShortLoopGatherer slg(clUnrollFullThreshold);
143 // Do a post order walk so that loops are gathered from innermost to
144 // outermost (or else unrolling an outer one may delete gathered inner
145 // ones).
146 slg.walkPostOrder(f);
147 auto &loops = slg.loops;
148 for (auto *forStmt : loops)
149 loopUnrollFull(forStmt);
150 return;
151 }
152
153 InnermostLoopGatherer ilg;
154 ilg.walkPostOrder(f);
155 auto &loops = ilg.loops;
Uday Bondhugula134154e2018-08-06 18:40:34 -0700156 for (auto *forStmt : loops)
157 runOnForStmt(forStmt);
158}
159
Uday Bondhugula67701712018-08-21 16:01:23 -0700160/// Unroll a for stmt. Default unroll factor is 4.
161bool LoopUnroll::runOnForStmt(ForStmt *forStmt) {
162 // Unroll completely if full loop unroll was specified.
163 if (clUnrollFull.getNumOccurrences() > 0 ||
164 (unrollFull.hasValue() && unrollFull.getValue()))
165 return loopUnrollFull(forStmt);
166
167 // Unroll by the specified factor if one was specified.
168 if (clUnrollFactor.getNumOccurrences() > 0)
169 return loopUnrollByFactor(forStmt, clUnrollFactor);
170 else if (unrollFactor.hasValue())
171 return loopUnrollByFactor(forStmt, unrollFactor.getValue());
172
173 // Unroll by four otherwise.
174 return loopUnrollByFactor(forStmt, 4);
175}
176
177// Unrolls this loop completely.
178bool LoopUnroll::loopUnrollFull(ForStmt *forStmt) {
Uday Bondhugula0b4059b2018-07-24 20:01:16 -0700179 auto lb = forStmt->getLowerBound()->getValue();
180 auto ub = forStmt->getUpperBound()->getValue();
Uday Bondhugula67701712018-08-21 16:01:23 -0700181 auto step = forStmt->getStep();
Uday Bondhugula0b4059b2018-07-24 20:01:16 -0700182
Uday Bondhugula84b80952018-08-03 13:22:26 -0700183 // Builder to add constants need for the unrolled iterator.
Chris Lattnere787b322018-08-08 11:14:57 -0700184 auto *mlFunc = forStmt->findFunction();
185 MLFuncBuilder funcTopBuilder(&mlFunc->front());
Uday Bondhugula0b4059b2018-07-24 20:01:16 -0700186
Chris Lattnere787b322018-08-08 11:14:57 -0700187 // Builder to insert the unrolled bodies. We insert right after the
188 /// ForStmt we're unrolling.
189 MLFuncBuilder builder(forStmt->getBlock(), ++StmtBlock::iterator(forStmt));
Uday Bondhugula84b80952018-08-03 13:22:26 -0700190
191 // Unroll the contents of 'forStmt'.
Uday Bondhugula134154e2018-08-06 18:40:34 -0700192 for (int64_t i = lb; i <= ub; i += step) {
Chris Lattnere787b322018-08-08 11:14:57 -0700193 DenseMap<const MLValue *, MLValue *> operandMapping;
194
195 // If the induction variable is used, create a constant for this unrolled
196 // value and add an operand mapping for it.
Uday Bondhugula134154e2018-08-06 18:40:34 -0700197 if (!forStmt->use_empty()) {
Chris Lattnere787b322018-08-08 11:14:57 -0700198 auto *ivConst =
Chris Lattner1628fa02018-08-23 14:32:25 -0700199 funcTopBuilder.create<ConstantAffineIntOp>(forStmt->getLoc(), i)
200 ->getResult();
Chris Lattnere787b322018-08-08 11:14:57 -0700201 operandMapping[forStmt] = cast<MLValue>(ivConst);
Uday Bondhugula134154e2018-08-06 18:40:34 -0700202 }
Uday Bondhugula84b80952018-08-03 13:22:26 -0700203
Chris Lattnere787b322018-08-08 11:14:57 -0700204 // Clone the body of the loop.
205 for (auto &childStmt : *forStmt) {
Uday Bondhugula67701712018-08-21 16:01:23 -0700206 builder.clone(childStmt, operandMapping);
Uday Bondhugula0b4059b2018-07-24 20:01:16 -0700207 }
208 }
Uday Bondhugula134154e2018-08-06 18:40:34 -0700209 // Erase the original 'for' stmt from the block.
Uday Bondhugula0b4059b2018-07-24 20:01:16 -0700210 forStmt->eraseFromBlock();
Uday Bondhugula67701712018-08-21 16:01:23 -0700211 return true;
212}
213
214/// Unrolls this loop by the specified unroll factor.
215bool LoopUnroll::loopUnrollByFactor(ForStmt *forStmt, unsigned unrollFactor) {
216 assert(unrollFactor >= 1 && "unroll factor shoud be >= 1");
217
218 if (unrollFactor == 1 || forStmt->getStatements().empty())
219 return false;
220
221 auto lb = forStmt->getLowerBound()->getValue();
222 auto ub = forStmt->getUpperBound()->getValue();
223 auto step = forStmt->getStep();
224
225 int64_t tripCount = (int64_t)ceilf((ub - lb + 1) / (float)step);
226
227 // If the trip count is lower than the unroll factor, no unrolled body.
228 // TODO(bondhugula): option to specify cleanup loop unrolling.
229 if (tripCount < unrollFactor)
230 return true;
231
232 // Generate the cleanup loop if trip count isn't a multiple of unrollFactor.
233 if (tripCount % unrollFactor) {
234 DenseMap<const MLValue *, MLValue *> operandMap;
235 MLFuncBuilder builder(forStmt->getBlock(), ++StmtBlock::iterator(forStmt));
236 auto *cleanupForStmt = cast<ForStmt>(builder.clone(*forStmt, operandMap));
237 cleanupForStmt->setLowerBound(builder.getConstantExpr(
238 lb + (tripCount - tripCount % unrollFactor) * step));
239 }
240
241 // Builder to insert unrolled bodies right after the last statement in the
242 // body of 'forStmt'.
243 MLFuncBuilder builder(forStmt, StmtBlock::iterator(forStmt->end()));
244 forStmt->setStep(step * unrollFactor);
245 forStmt->setUpperBound(builder.getConstantExpr(
246 lb + (tripCount - tripCount % unrollFactor - 1) * step));
247
248 // Keep a pointer to the last statement in the original block so that we know
249 // what to clone (since we are doing this in-place).
250 StmtBlock::iterator srcBlockEnd = --forStmt->end();
251
252 // Unroll the contents of 'forStmt' (unrollFactor-1 additional copies
253 // appended).
254 for (unsigned i = 1; i < unrollFactor; i++) {
255 DenseMap<const MLValue *, MLValue *> operandMapping;
256
257 // If the induction variable is used, create a remapping to the value for
258 // this unrolled instance.
259 if (!forStmt->use_empty()) {
260 // iv' = iv + 1/2/3...unrollFactor-1;
261 auto *bumpExpr = builder.getAddExpr(builder.getDimExpr(0),
262 builder.getConstantExpr(i * step));
263 auto *bumpMap = builder.getAffineMap(1, 0, {bumpExpr}, {});
264 auto *ivUnroll =
Chris Lattner1628fa02018-08-23 14:32:25 -0700265 builder.create<AffineApplyOp>(forStmt->getLoc(), bumpMap, forStmt)
266 ->getResult(0);
Uday Bondhugula67701712018-08-21 16:01:23 -0700267 operandMapping[forStmt] = cast<MLValue>(ivUnroll);
268 }
269
270 // Clone the original body of the loop (this doesn't include the last stmt).
271 for (auto it = forStmt->begin(); it != srcBlockEnd; it++) {
272 builder.clone(*it, operandMapping);
273 }
274 // Clone the last statement in the original body.
275 builder.clone(*srcBlockEnd, operandMapping);
276 }
277 return true;
Uday Bondhugula0b4059b2018-07-24 20:01:16 -0700278}