blob: e663ce0ae0085bbc0859eecd6fb5c28e10042f2d [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
Tatiana Shpeismande8829f2018-08-24 23:38:14 -070022#include "mlir/IR/AffineExpr.h"
Uday Bondhugula15984952018-08-01 22:36:12 -070023#include "mlir/IR/Attributes.h"
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070024#include "mlir/IR/Builders.h"
25#include "mlir/IR/CFGFunction.h"
26#include "mlir/IR/MLFunction.h"
27#include "mlir/IR/Module.h"
28#include "mlir/IR/OperationSet.h"
Uday Bondhugula84b80952018-08-03 13:22:26 -070029#include "mlir/IR/StandardOps.h"
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070030#include "mlir/IR/Statements.h"
31#include "mlir/IR/StmtVisitor.h"
Uday Bondhugula6c1f6602018-08-13 17:25:13 -070032#include "mlir/Transforms/Pass.h"
Chris Lattneree0c2ae2018-07-29 12:37:35 -070033#include "mlir/Transforms/Passes.h"
Chris Lattnere787b322018-08-08 11:14:57 -070034#include "llvm/ADT/DenseMap.h"
Uday Bondhugula67701712018-08-21 16:01:23 -070035#include "llvm/Support/CommandLine.h"
Uday Bondhugula0b4059b2018-07-24 20:01:16 -070036
37using namespace mlir;
Uday Bondhugula67701712018-08-21 16:01:23 -070038
39// Loop unrolling factor.
40static llvm::cl::opt<unsigned>
Uday Bondhugula832b17a2018-09-07 14:47:21 -070041 clUnrollFactor("unroll-factor", llvm::cl::Hidden,
42 llvm::cl::desc("Use this unroll factor for all loops"));
Uday Bondhugula67701712018-08-21 16:01:23 -070043
Uday Bondhugula832b17a2018-09-07 14:47:21 -070044static llvm::cl::opt<bool> clUnrollFull("unroll-full", llvm::cl::Hidden,
45 llvm::cl::desc("Fully unroll loops"));
Uday Bondhugula67701712018-08-21 16:01:23 -070046
47static llvm::cl::opt<unsigned> clUnrollFullThreshold(
Uday Bondhugula832b17a2018-09-07 14:47:21 -070048 "unroll-full-threshold", llvm::cl::Hidden,
49 llvm::cl::desc(
50 "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);
Uday Bondhugula832b17a2018-09-07 14:47:21 -070069 bool loopUnrollByFactor(ForStmt *forStmt, uint64_t 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) {
Uday Bondhugula832b17a2018-09-07 14:47:21 -0700131 Optional<uint64_t> tripCount = forStmt->getConstantTripCount();
132 if (tripCount.hasValue() && tripCount.getValue() <= minTripCount)
Uday Bondhugula134154e2018-08-06 18:40:34 -0700133 loops.push_back(forStmt);
Uday Bondhugula15984952018-08-01 22:36:12 -0700134 }
135 };
136
Uday Bondhugula67701712018-08-21 16:01:23 -0700137 if (clUnrollFull.getNumOccurrences() > 0 &&
138 clUnrollFullThreshold.getNumOccurrences() > 0) {
139 ShortLoopGatherer slg(clUnrollFullThreshold);
140 // Do a post order walk so that loops are gathered from innermost to
141 // outermost (or else unrolling an outer one may delete gathered inner
142 // ones).
143 slg.walkPostOrder(f);
144 auto &loops = slg.loops;
145 for (auto *forStmt : loops)
146 loopUnrollFull(forStmt);
147 return;
148 }
149
150 InnermostLoopGatherer ilg;
151 ilg.walkPostOrder(f);
152 auto &loops = ilg.loops;
Uday Bondhugula134154e2018-08-06 18:40:34 -0700153 for (auto *forStmt : loops)
154 runOnForStmt(forStmt);
155}
156
Uday Bondhugula67701712018-08-21 16:01:23 -0700157/// Unroll a for stmt. Default unroll factor is 4.
158bool LoopUnroll::runOnForStmt(ForStmt *forStmt) {
Uday Bondhugula6cd35022018-08-28 18:24:27 -0700159 // Unroll by the factor passed, if any.
160 if (unrollFactor.hasValue())
161 return loopUnrollByFactor(forStmt, unrollFactor.getValue());
162 // Unroll by the command line factor if one was specified.
163 if (clUnrollFactor.getNumOccurrences() > 0)
164 return loopUnrollByFactor(forStmt, clUnrollFactor);
Uday Bondhugula67701712018-08-21 16:01:23 -0700165 // Unroll completely if full loop unroll was specified.
166 if (clUnrollFull.getNumOccurrences() > 0 ||
167 (unrollFull.hasValue() && unrollFull.getValue()))
168 return loopUnrollFull(forStmt);
169
Uday Bondhugula67701712018-08-21 16:01:23 -0700170 // Unroll by four otherwise.
171 return loopUnrollByFactor(forStmt, 4);
172}
173
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700174// Unrolls this loop completely. Fails assertion if loop bounds are
175// non-constant.
Uday Bondhugula67701712018-08-21 16:01:23 -0700176bool LoopUnroll::loopUnrollFull(ForStmt *forStmt) {
Uday Bondhugula832b17a2018-09-07 14:47:21 -0700177 Optional<uint64_t> tripCount = forStmt->getConstantTripCount();
178 if (tripCount.hasValue())
179 return loopUnrollByFactor(forStmt, tripCount.getValue());
180 return false;
Uday Bondhugula67701712018-08-21 16:01:23 -0700181}
182
183/// Unrolls this loop by the specified unroll factor.
Uday Bondhugula832b17a2018-09-07 14:47:21 -0700184bool LoopUnroll::loopUnrollByFactor(ForStmt *forStmt, uint64_t unrollFactor) {
Uday Bondhugula67701712018-08-21 16:01:23 -0700185 assert(unrollFactor >= 1 && "unroll factor shoud be >= 1");
186
187 if (unrollFactor == 1 || forStmt->getStatements().empty())
188 return false;
189
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700190 if (!forStmt->hasConstantBounds())
191 return false;
192
Uday Bondhugula832b17a2018-09-07 14:47:21 -0700193 int64_t lb = forStmt->getConstantLowerBound();
194 int64_t step = forStmt->getStep();
195 uint64_t tripCount = forStmt->getConstantTripCount().getValue();
Uday Bondhugula67701712018-08-21 16:01:23 -0700196
197 // If the trip count is lower than the unroll factor, no unrolled body.
198 // TODO(bondhugula): option to specify cleanup loop unrolling.
199 if (tripCount < unrollFactor)
200 return true;
201
202 // Generate the cleanup loop if trip count isn't a multiple of unrollFactor.
203 if (tripCount % unrollFactor) {
204 DenseMap<const MLValue *, MLValue *> operandMap;
205 MLFuncBuilder builder(forStmt->getBlock(), ++StmtBlock::iterator(forStmt));
206 auto *cleanupForStmt = cast<ForStmt>(builder.clone(*forStmt, operandMap));
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700207 cleanupForStmt->setConstantLowerBound(
208 lb + (tripCount - tripCount % unrollFactor) * step);
Uday Bondhugula832b17a2018-09-07 14:47:21 -0700209 // Promote the loop body up if this has turned into a single iteration loop.
210 promoteIfSingleIteration(cleanupForStmt);
Uday Bondhugula67701712018-08-21 16:01:23 -0700211 }
212
213 // Builder to insert unrolled bodies right after the last statement in the
214 // body of 'forStmt'.
215 MLFuncBuilder builder(forStmt, StmtBlock::iterator(forStmt->end()));
216 forStmt->setStep(step * unrollFactor);
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700217 forStmt->setConstantUpperBound(
218 lb + (tripCount - tripCount % unrollFactor - 1) * step);
Uday Bondhugula67701712018-08-21 16:01:23 -0700219
220 // Keep a pointer to the last statement in the original block so that we know
221 // what to clone (since we are doing this in-place).
222 StmtBlock::iterator srcBlockEnd = --forStmt->end();
223
224 // Unroll the contents of 'forStmt' (unrollFactor-1 additional copies
225 // appended).
226 for (unsigned i = 1; i < unrollFactor; i++) {
227 DenseMap<const MLValue *, MLValue *> operandMapping;
228
229 // If the induction variable is used, create a remapping to the value for
230 // this unrolled instance.
231 if (!forStmt->use_empty()) {
232 // iv' = iv + 1/2/3...unrollFactor-1;
233 auto *bumpExpr = builder.getAddExpr(builder.getDimExpr(0),
234 builder.getConstantExpr(i * step));
235 auto *bumpMap = builder.getAffineMap(1, 0, {bumpExpr}, {});
236 auto *ivUnroll =
Chris Lattner1628fa02018-08-23 14:32:25 -0700237 builder.create<AffineApplyOp>(forStmt->getLoc(), bumpMap, forStmt)
238 ->getResult(0);
Uday Bondhugula67701712018-08-21 16:01:23 -0700239 operandMapping[forStmt] = cast<MLValue>(ivUnroll);
240 }
241
242 // Clone the original body of the loop (this doesn't include the last stmt).
243 for (auto it = forStmt->begin(); it != srcBlockEnd; it++) {
244 builder.clone(*it, operandMapping);
245 }
246 // Clone the last statement in the original body.
247 builder.clone(*srcBlockEnd, operandMapping);
248 }
Uday Bondhugula832b17a2018-09-07 14:47:21 -0700249
250 // Promote the loop body up if this has turned into a single iteration loop.
251 promoteIfSingleIteration(forStmt);
252
Uday Bondhugula67701712018-08-21 16:01:23 -0700253 return true;
Uday Bondhugula0b4059b2018-07-24 20:01:16 -0700254}