blob: 1904a6366477629ce469cb19cbfee000bdf0e48c [file] [log] [blame]
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -07001//===- LoopAnalysis.cpp - Misc loop analysis routines //-------------------===//
2//
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 miscellaneous loop analysis routines.
19//
20//===----------------------------------------------------------------------===//
21
22#include "mlir/Analysis/LoopAnalysis.h"
23
24#include "mlir/Analysis/AffineAnalysis.h"
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -070025#include "mlir/Analysis/AffineStructures.h"
26#include "mlir/Analysis/MLFunctionMatcher.h"
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -070027#include "mlir/IR/Builders.h"
28#include "mlir/IR/BuiltinOps.h"
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070029#include "mlir/IR/Statements.h"
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -070030#include "mlir/StandardOps/StandardOps.h"
Nicolas Vasilache078d9b92018-10-30 07:54:23 -070031#include "mlir/Support/Functional.h"
Uday Bondhugula48e4c4b2018-10-03 10:07:54 -070032#include "mlir/Support/MathExtras.h"
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070033
Nicolas Vasilache5373b092018-10-03 15:39:12 -070034using namespace mlir;
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070035
36/// Returns the trip count of the loop as an affine expression if the latter is
37/// expressible as an affine expression, and nullptr otherwise. The trip count
38/// expression is simplified before returning.
Nicolas Vasilachefb11e0e2018-10-08 13:47:18 -070039AffineExpr mlir::getTripCountExpr(const ForStmt &forStmt) {
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070040 // upper_bound - lower_bound + 1
41 int64_t loopSpan;
42
43 int64_t step = forStmt.getStep();
44 auto *context = forStmt.getContext();
45
46 if (forStmt.hasConstantBounds()) {
47 int64_t lb = forStmt.getConstantLowerBound();
48 int64_t ub = forStmt.getConstantUpperBound();
49 loopSpan = ub - lb + 1;
50 } else {
Nicolas Vasilache75ed3372018-10-09 16:39:24 -070051 auto lbMap = forStmt.getLowerBoundMap();
52 auto ubMap = forStmt.getUpperBoundMap();
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070053 // TODO(bondhugula): handle max/min of multiple expressions.
Nicolas Vasilache75ed3372018-10-09 16:39:24 -070054 if (lbMap.getNumResults() != 1 || ubMap.getNumResults() != 1)
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070055 return nullptr;
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070056
57 // TODO(bondhugula): handle bounds with different operands.
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070058 // Bounds have different operands, unhandled for now.
Uday Bondhugula5912e872018-09-18 10:22:03 -070059 if (!forStmt.matchingBoundOperandList())
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070060 return nullptr;
61
62 // ub_expr - lb_expr + 1
Nicolas Vasilache75ed3372018-10-09 16:39:24 -070063 AffineExpr lbExpr(lbMap.getResult(0));
64 AffineExpr ubExpr(ubMap.getResult(0));
Nicolas Vasilache5373b092018-10-03 15:39:12 -070065 auto loopSpanExpr = simplifyAffineExpr(
Nicolas Vasilache75ed3372018-10-09 16:39:24 -070066 ubExpr - lbExpr + 1, std::max(lbMap.getNumDims(), ubMap.getNumDims()),
67 std::max(lbMap.getNumSymbols(), ubMap.getNumSymbols()));
Nicolas Vasilachefb11e0e2018-10-08 13:47:18 -070068 auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>();
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070069 if (!cExpr)
Nicolas Vasilachebc746092018-10-08 10:20:25 -070070 return loopSpanExpr.ceilDiv(step);
Nicolas Vasilacheb7717092018-10-09 10:59:27 -070071 loopSpan = cExpr.getValue();
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070072 }
73
74 // 0 iteration loops.
Uday Bondhugulaff5d6bd2018-09-27 18:03:27 -070075 if (loopSpan < 0)
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070076 return 0;
77
Nicolas Vasilachebc746092018-10-08 10:20:25 -070078 return getAffineConstantExpr(static_cast<uint64_t>(ceilDiv(loopSpan, step)),
79 context);
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070080}
81
82/// Returns the trip count of the loop if it's a constant, None otherwise. This
83/// method uses affine expression analysis (in turn using getTripCount) and is
84/// able to determine constant trip count in non-trivial cases.
85llvm::Optional<uint64_t> mlir::getConstantTripCount(const ForStmt &forStmt) {
Nicolas Vasilache5373b092018-10-03 15:39:12 -070086 auto tripCountExpr = getTripCountExpr(forStmt);
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070087
Nicolas Vasilache32402e52018-10-08 08:09:50 -070088 if (!tripCountExpr)
89 return None;
90
Nicolas Vasilachefb11e0e2018-10-08 13:47:18 -070091 if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>())
Nicolas Vasilacheb7717092018-10-09 10:59:27 -070092 return constExpr.getValue();
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070093
94 return None;
95}
96
97/// Returns the greatest known integral divisor of the trip count. Affine
98/// expression analysis is used (indirectly through getTripCount), and
99/// this method is thus able to determine non-trivial divisors.
100uint64_t mlir::getLargestDivisorOfTripCount(const ForStmt &forStmt) {
Nicolas Vasilache5373b092018-10-03 15:39:12 -0700101 auto tripCountExpr = getTripCountExpr(forStmt);
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -0700102
103 if (!tripCountExpr)
104 return 1;
105
Nicolas Vasilachefb11e0e2018-10-08 13:47:18 -0700106 if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>()) {
Nicolas Vasilacheb7717092018-10-09 10:59:27 -0700107 uint64_t tripCount = constExpr.getValue();
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -0700108
109 // 0 iteration loops (greatest divisor is 2^64 - 1).
110 if (tripCount == 0)
111 return ULONG_MAX;
112
113 // The greatest divisor is the trip count.
114 return tripCount;
115 }
116
117 // Trip count is not a known constant; return its largest known divisor.
Nicolas Vasilacheb7717092018-10-09 10:59:27 -0700118 return tripCountExpr.getLargestKnownDivisor();
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -0700119}
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700120
River Riddle666dfbe2018-10-30 14:59:22 -0700121bool mlir::isAccessInvariant(const MLValue &input, MemRefType memRefType,
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700122 ArrayRef<MLValue *> indices, unsigned dim) {
River Riddle666dfbe2018-10-30 14:59:22 -0700123 assert(indices.size() == memRefType.getRank());
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700124 assert(dim < indices.size());
River Riddle666dfbe2018-10-30 14:59:22 -0700125 auto layoutMap = memRefType.getAffineMaps();
126 assert(memRefType.getAffineMaps().size() <= 1);
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700127 // TODO(ntv): remove dependency on Builder once we support non-identity
128 // layout map.
River Riddle666dfbe2018-10-30 14:59:22 -0700129 Builder b(memRefType.getContext());
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700130 assert(layoutMap.empty() ||
131 layoutMap[0] == b.getMultiDimIdentityMap(indices.size()));
Uday Bondhugula861fe642018-10-18 11:14:26 -0700132 (void)layoutMap;
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700133
134 SmallVector<OperationStmt *, 4> affineApplyOps;
135 getReachableAffineApplyOps({indices[dim]}, affineApplyOps);
136
137 if (affineApplyOps.empty()) {
138 // Pointer equality test because of MLValue pointer semantics.
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700139 return indices[dim] != &input;
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700140 }
141
142 assert(affineApplyOps.size() == 1 &&
143 "CompositionAffineMapsPass must have "
144 "been run: there should be at most one AffineApplyOp");
Feng Liuec065d72018-10-19 09:07:58 -0700145 auto composeOp = affineApplyOps[0]->cast<AffineApplyOp>();
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700146 // We need yet another level of indirection because the `dim` index of the
147 // access may not correspond to the `dim` index of composeOp.
148 unsigned idx = std::numeric_limits<unsigned>::max();
149 unsigned numResults = composeOp->getNumResults();
150 for (unsigned i = 0; i < numResults; ++i) {
151 if (indices[dim] == composeOp->getResult(i)) {
152 idx = i;
153 break;
154 }
155 }
156 assert(idx < std::numeric_limits<unsigned>::max());
157 return !AffineValueMap(*composeOp)
158 .isFunctionOf(idx, &const_cast<MLValue &>(input));
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700159}
160
161/// Determines whether a load or a store has a contiguous access along the
162/// value `input`. Contiguous is defined as either invariant or varying only
163/// along the fastest varying memory dimension.
164// TODO(ntv): allow more advanced notions of contiguity (non-fastest varying,
165// check strides, ...).
166template <typename LoadOrStoreOpPointer>
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700167static bool isContiguousAccess(const MLValue &input,
168 LoadOrStoreOpPointer memoryOp,
169 unsigned fastestVaryingDim) {
170 using namespace functional;
171 auto indices = map([](SSAValue *val) { return dyn_cast<MLValue>(val); },
172 memoryOp->getIndices());
River Riddle666dfbe2018-10-30 14:59:22 -0700173 auto memRefType = memoryOp->getMemRefType();
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700174 for (unsigned d = 0, numIndices = indices.size(); d < numIndices; ++d) {
175 if (fastestVaryingDim == (numIndices - 1) - d) {
176 continue;
177 }
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700178 if (!isAccessInvariant(input, memRefType, indices, d)) {
179 return false;
180 }
181 }
182 return true;
183}
184
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700185template <typename LoadOrStoreOpPointer>
186static bool isVectorElement(LoadOrStoreOpPointer memoryOp) {
River Riddle666dfbe2018-10-30 14:59:22 -0700187 auto memRefType = memoryOp->getMemRefType();
188 return memRefType.getElementType().template isa<VectorType>();
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700189}
190
191bool mlir::isVectorizableLoop(const ForStmt &loop, unsigned fastestVaryingDim) {
192 if (!matcher::isParallelLoop(loop) && !matcher::isReductionLoop(loop)) {
193 return false;
194 }
195
196 // No vectorization across conditionals for now.
197 auto conditionals = matcher::If();
198 auto *forStmt = const_cast<ForStmt *>(&loop);
199 auto conditionalsMatched = conditionals.match(forStmt);
200 if (!conditionalsMatched.empty()) {
201 return false;
202 }
203
204 auto loadAndStores = matcher::Op(matcher::isLoadOrStore);
205 auto loadAndStoresMatched = loadAndStores.match(forStmt);
206 for (auto ls : loadAndStoresMatched) {
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700207 auto *op = cast<OperationStmt>(ls.first);
Feng Liuec065d72018-10-19 09:07:58 -0700208 auto load = op->dyn_cast<LoadOp>();
209 auto store = op->dyn_cast<StoreOp>();
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700210 // Only scalar types are considered vectorizable, all load/store must be
211 // vectorizable for a loop to qualify as vectorizable.
212 // TODO(ntv): ponder whether we want to be more general here.
213 bool vector = load ? isVectorElement(load) : isVectorElement(store);
214 if (vector) {
215 return false;
216 }
217 bool contiguous = load ? isContiguousAccess(loop, load, fastestVaryingDim)
218 : isContiguousAccess(loop, store, fastestVaryingDim);
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700219 if (!contiguous) {
220 return false;
221 }
222 }
223 return true;
224}
Uday Bondhugula861fe642018-10-18 11:14:26 -0700225
226/// Checks whether SSA dominance would be violated if a for stmt's body
227/// statements are shifted by the specified shifts. This method checks if a
228/// 'def' and all its uses have the same shift factor.
229// TODO(mlir-team): extend this to check for memory-based dependence
230// violation when we have the support.
231bool mlir::isStmtwiseShiftValid(const ForStmt &forStmt,
232 ArrayRef<uint64_t> shifts) {
233 assert(shifts.size() == forStmt.getStatements().size());
234 unsigned s = 0;
235 for (const auto &stmt : forStmt) {
236 // A for or if stmt does not produce any def/results (that are used
237 // outside).
238 if (const auto *opStmt = dyn_cast<OperationStmt>(&stmt)) {
239 for (unsigned i = 0, e = opStmt->getNumResults(); i < e; ++i) {
240 const MLValue *result = opStmt->getResult(i);
241 for (const StmtOperand &use : result->getUses()) {
242 // If an ancestor statement doesn't lie in the block of forStmt, there
243 // is no shift to check.
244 // This is a naive way. If performance becomes an issue, a map can
245 // be used to store 'shifts' - to look up the shift for a statement in
246 // constant time.
247 if (auto *ancStmt = forStmt.findAncestorStmtInBlock(*use.getOwner()))
248 if (shifts[s] != shifts[forStmt.findStmtPosInBlock(*ancStmt)])
249 return false;
250 }
251 }
252 }
253 s++;
254 }
255 return true;
256}