blob: 558da0a55cd2e82f94d14a84dc716960e62f14d0 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000026#include "polly/TempScopInfo.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000028#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000030#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000031#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000032#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000033#include "llvm/Analysis/RegionIterator.h"
34#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000035#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000036#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000037#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000038#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000039#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000040#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000041#include "isl/printer.h"
42#include "isl/set.h"
43#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000044#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000045#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000046#include <sstream>
47#include <string>
48#include <vector>
49
50using namespace llvm;
51using namespace polly;
52
Chandler Carruth95fef942014-04-22 03:30:19 +000053#define DEBUG_TYPE "polly-scops"
54
Tobias Grosser74394f02013-01-14 22:40:23 +000055STATISTIC(ScopFound, "Number of valid Scops");
56STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000057
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000058// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000059// operations can overflow easily. Additive reductions and bit operations
60// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000061static cl::opt<bool> DisableMultiplicativeReductions(
62 "polly-disable-multiplicative-reductions",
63 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
64 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000065
Johannes Doerfert9143d672014-09-27 11:02:39 +000066static cl::opt<unsigned> RunTimeChecksMaxParameters(
67 "polly-rtc-max-parameters",
68 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
69 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
70
Tobias Grosser71500722015-03-28 15:11:14 +000071static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
72 "polly-rtc-max-arrays-per-group",
73 cl::desc("The maximal number of arrays to compare in each alias group."),
74 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
75
Tobias Grosser0695ee42013-09-17 03:30:31 +000076/// Translate a 'const SCEV *' expression in an isl_pw_aff.
Tobias Grosserabfbe632013-02-05 12:09:06 +000077struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
Tobias Grosser0695ee42013-09-17 03:30:31 +000078public:
Tobias Grosser0695ee42013-09-17 03:30:31 +000079 /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
80 ///
81 /// @param Stmt The location at which the scalar evolution expression
82 /// is evaluated.
83 /// @param Expr The expression that is translated.
84 static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
85
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000086private:
Tobias Grosser3cc99742012-06-06 16:33:15 +000087 isl_ctx *Ctx;
Tobias Grosserf5338802011-10-06 00:03:35 +000088 int NbLoopSpaces;
Tobias Grosser3cc99742012-06-06 16:33:15 +000089 const Scop *S;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000090
Tobias Grosser0695ee42013-09-17 03:30:31 +000091 SCEVAffinator(const ScopStmt *Stmt);
92 int getLoopDepth(const Loop *L);
Tobias Grosser60b54f12011-11-08 15:41:28 +000093
Tobias Grosser0695ee42013-09-17 03:30:31 +000094 __isl_give isl_pw_aff *visit(const SCEV *Expr);
95 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
96 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
97 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
98 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
99 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
100 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
101 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
102 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
103 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
104 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
105 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000106 __isl_give isl_pw_aff *visitSDivInstruction(Instruction *SDiv);
Tobias Grosser60b54f12011-11-08 15:41:28 +0000107
Tobias Grosser0695ee42013-09-17 03:30:31 +0000108 friend struct SCEVVisitor<SCEVAffinator, isl_pw_aff *>;
109};
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000110
Tobias Grosser0695ee42013-09-17 03:30:31 +0000111SCEVAffinator::SCEVAffinator(const ScopStmt *Stmt)
112 : Ctx(Stmt->getIslCtx()), NbLoopSpaces(Stmt->getNumIterators()),
113 S(Stmt->getParent()) {}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000114
Tobias Grosser0695ee42013-09-17 03:30:31 +0000115__isl_give isl_pw_aff *SCEVAffinator::getPwAff(ScopStmt *Stmt,
116 const SCEV *Scev) {
117 Scop *S = Stmt->getParent();
118 const Region *Reg = &S->getRegion();
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000119
Tobias Grosser0695ee42013-09-17 03:30:31 +0000120 S->addParams(getParamsInAffineExpr(Reg, Scev, *S->getSE()));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000121
Tobias Grosser0695ee42013-09-17 03:30:31 +0000122 SCEVAffinator Affinator(Stmt);
123 return Affinator.visit(Scev);
124}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000125
Tobias Grosser0695ee42013-09-17 03:30:31 +0000126__isl_give isl_pw_aff *SCEVAffinator::visit(const SCEV *Expr) {
127 // In case the scev is a valid parameter, we do not further analyze this
128 // expression, but create a new parameter in the isl_pw_aff. This allows us
129 // to treat subexpressions that we cannot translate into an piecewise affine
130 // expression, as constant parameters of the piecewise affine expression.
131 if (isl_id *Id = S->getIdForParam(Expr)) {
132 isl_space *Space = isl_space_set_alloc(Ctx, 1, NbLoopSpaces);
133 Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000134
Tobias Grosser0695ee42013-09-17 03:30:31 +0000135 isl_set *Domain = isl_set_universe(isl_space_copy(Space));
136 isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
137 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000138
139 return isl_pw_aff_alloc(Domain, Affine);
140 }
141
Tobias Grosser0695ee42013-09-17 03:30:31 +0000142 return SCEVVisitor<SCEVAffinator, isl_pw_aff *>::visit(Expr);
143}
144
Tobias Grosser0d170132013-10-03 13:09:19 +0000145__isl_give isl_pw_aff *SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
Tobias Grosser0695ee42013-09-17 03:30:31 +0000146 ConstantInt *Value = Expr->getValue();
147 isl_val *v;
148
149 // LLVM does not define if an integer value is interpreted as a signed or
150 // unsigned value. Hence, without further information, it is unknown how
151 // this value needs to be converted to GMP. At the moment, we only support
152 // signed operations. So we just interpret it as signed. Later, there are
153 // two options:
154 //
155 // 1. We always interpret any value as signed and convert the values on
156 // demand.
157 // 2. We pass down the signedness of the calculation and use it to interpret
158 // this constant correctly.
159 v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
160
161 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
Johannes Doerfert9c147372014-11-19 15:36:59 +0000162 isl_local_space *ls = isl_local_space_from_space(Space);
163 return isl_pw_aff_from_aff(isl_aff_val_on_domain(ls, v));
Tobias Grosser0695ee42013-09-17 03:30:31 +0000164}
165
166__isl_give isl_pw_aff *
167SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
168 llvm_unreachable("SCEVTruncateExpr not yet supported");
169}
170
171__isl_give isl_pw_aff *
172SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
173 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
174}
175
176__isl_give isl_pw_aff *
177SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
178 // Assuming the value is signed, a sign extension is basically a noop.
179 // TODO: Reconsider this as soon as we support unsigned values.
180 return visit(Expr->getOperand());
181}
182
183__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
184 isl_pw_aff *Sum = visit(Expr->getOperand(0));
185
186 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
187 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
188 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000189 }
190
Tobias Grosser0695ee42013-09-17 03:30:31 +0000191 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000192
Tobias Grosser0695ee42013-09-17 03:30:31 +0000193 return Sum;
194}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000195
Tobias Grosser0695ee42013-09-17 03:30:31 +0000196__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
Johannes Doerfertbe409962015-03-29 20:45:09 +0000197 // Divide Expr into a constant part and the rest. Then visit both and multiply
198 // the result to obtain the representation for Expr. While the second part of
199 // ConstantAndLeftOverPair might still be a SCEVMulExpr we will not get to
200 // this point again. The reason is that if it is a multiplication it consists
201 // only of parameters and we will stop in the visit(const SCEV *) function and
202 // return the isl_pw_aff for that parameter.
203 auto ConstantAndLeftOverPair = extractConstantFactor(Expr, *S->getSE());
204 return isl_pw_aff_mul(visit(ConstantAndLeftOverPair.first),
205 visit(ConstantAndLeftOverPair.second));
Tobias Grosser0695ee42013-09-17 03:30:31 +0000206}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000207
Tobias Grosser0695ee42013-09-17 03:30:31 +0000208__isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
209 llvm_unreachable("SCEVUDivExpr not yet supported");
210}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000211
Tobias Grosser0695ee42013-09-17 03:30:31 +0000212__isl_give isl_pw_aff *
213SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
214 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000215
Johannes Doerfertd5d8f672015-04-26 19:55:21 +0000216 auto Flags = Expr->getNoWrapFlags();
217
Tobias Grosser0695ee42013-09-17 03:30:31 +0000218 // Directly generate isl_pw_aff for Expr if 'start' is zero.
219 if (Expr->getStart()->isZero()) {
220 assert(S->getRegion().contains(Expr->getLoop()) &&
221 "Scop does not contain the loop referenced in this AddRec");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000222
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000223 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser0695ee42013-09-17 03:30:31 +0000224 isl_pw_aff *Step = visit(Expr->getOperand(1));
225 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
226 isl_local_space *LocalSpace = isl_local_space_from_space(Space);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000227
Tobias Grosser0695ee42013-09-17 03:30:31 +0000228 int loopDimension = getLoopDepth(Expr->getLoop());
229
230 isl_aff *LAff = isl_aff_set_coefficient_si(
231 isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
232 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
233
234 // TODO: Do we need to check for NSW and NUW?
235 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000236 }
237
Tobias Grosser0695ee42013-09-17 03:30:31 +0000238 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
239 // if 'start' is not zero.
Johannes Doerfertd5d8f672015-04-26 19:55:21 +0000240 // TODO: Using the original SCEV no-wrap flags is not always safe, however
241 // as our code generation is reordering the expression anyway it doesn't
242 // really matter.
Tobias Grosser0695ee42013-09-17 03:30:31 +0000243 ScalarEvolution &SE = *S->getSE();
Johannes Doerfertd5d8f672015-04-26 19:55:21 +0000244 const SCEV *ZeroStartExpr =
245 SE.getAddRecExpr(SE.getConstant(Expr->getStart()->getType(), 0),
246 Expr->getStepRecurrence(SE), Expr->getLoop(), Flags);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000247
Tobias Grosser0695ee42013-09-17 03:30:31 +0000248 isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
249 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000250
Tobias Grosser0695ee42013-09-17 03:30:31 +0000251 return isl_pw_aff_add(ZeroStartResult, Start);
252}
253
254__isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
255 isl_pw_aff *Max = visit(Expr->getOperand(0));
256
257 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
258 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
259 Max = isl_pw_aff_max(Max, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000260 }
261
Tobias Grosser0695ee42013-09-17 03:30:31 +0000262 return Max;
263}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000264
Tobias Grosser0695ee42013-09-17 03:30:31 +0000265__isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
266 llvm_unreachable("SCEVUMaxExpr not yet supported");
267}
268
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000269__isl_give isl_pw_aff *SCEVAffinator::visitSDivInstruction(Instruction *SDiv) {
270 assert(SDiv->getOpcode() == Instruction::SDiv && "Assumed SDiv instruction!");
271 auto *SE = S->getSE();
272
273 auto *Divisor = SDiv->getOperand(1);
274 auto *DivisorSCEV = SE->getSCEV(Divisor);
275 auto *DivisorPWA = visit(DivisorSCEV);
276 assert(isa<ConstantInt>(Divisor) &&
277 "SDiv is no parameter but has a non-constant RHS.");
278
279 auto *Dividend = SDiv->getOperand(0);
280 auto *DividendSCEV = SE->getSCEV(Dividend);
281 auto *DividendPWA = visit(DividendSCEV);
282 return isl_pw_aff_tdiv_q(DividendPWA, DivisorPWA);
283}
284
Tobias Grosser0695ee42013-09-17 03:30:31 +0000285__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000286 if (Instruction *I = dyn_cast<Instruction>(Expr->getValue())) {
287 switch (I->getOpcode()) {
288 case Instruction::SDiv:
289 return visitSDivInstruction(I);
290 default:
291 break; // Fall through.
292 }
293 }
294
295 llvm_unreachable(
296 "Unknowns SCEV was neither parameter nor a valid instruction.");
Tobias Grosser0695ee42013-09-17 03:30:31 +0000297}
298
299int SCEVAffinator::getLoopDepth(const Loop *L) {
300 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
301 assert(outerLoop && "Scop does not contain this loop");
302 return L->getLoopDepth() - outerLoop->getLoopDepth();
303}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000304
Johannes Doerferte7044942015-02-24 11:58:30 +0000305/// @brief Add the bounds of @p Range to the set @p S for dimension @p dim.
306static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
307 const ConstantRange &Range,
308 int dim,
309 enum isl_dim_type type) {
310 isl_val *V;
311 isl_ctx *ctx = isl_set_get_ctx(S);
312
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000313 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
314 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000315 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000316 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
317
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000318 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000319 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000320 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000321 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000322 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
323
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000324 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000325 return isl_set_union(SLB, SUB);
326 else
327 return isl_set_intersect(SLB, SUB);
328}
329
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000330ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *AccessType, isl_ctx *Ctx,
331 const SmallVector<const SCEV *, 4> &DimensionSizes)
332 : BasePtr(BasePtr), AccessType(AccessType), DimensionSizes(DimensionSizes) {
333 const std::string BasePtrName = getIslCompatibleName("MemRef_", BasePtr, "");
334 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
335}
336
337ScopArrayInfo::~ScopArrayInfo() { isl_id_free(Id); }
338
339isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
340
341void ScopArrayInfo::dump() const { print(errs()); }
342
343void ScopArrayInfo::print(raw_ostream &OS) const {
344 OS << "ScopArrayInfo:\n";
345 OS << " Base: " << *getBasePtr() << "\n";
346 OS << " Type: " << *getType() << "\n";
347 OS << " Dimension Sizes:\n";
348 for (unsigned u = 0; u < getNumberOfDimensions(); u++)
349 OS << " " << u << ") " << *DimensionSizes[u] << "\n";
350 OS << "\n";
351}
352
353const ScopArrayInfo *
354ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
355 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
356 assert(Id && "Output dimension didn't have an ID");
357 return getFromId(Id);
358}
359
360const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
361 void *User = isl_id_get_user(Id);
362 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
363 isl_id_free(Id);
364 return SAI;
365}
366
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000367const std::string
368MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
369 switch (RT) {
370 case MemoryAccess::RT_NONE:
371 llvm_unreachable("Requested a reduction operator string for a memory "
372 "access which isn't a reduction");
373 case MemoryAccess::RT_ADD:
374 return "+";
375 case MemoryAccess::RT_MUL:
376 return "*";
377 case MemoryAccess::RT_BOR:
378 return "|";
379 case MemoryAccess::RT_BXOR:
380 return "^";
381 case MemoryAccess::RT_BAND:
382 return "&";
383 }
384 llvm_unreachable("Unknown reduction type");
385 return "";
386}
387
Johannes Doerfertf6183392014-07-01 20:52:51 +0000388/// @brief Return the reduction type for a given binary operator
389static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
390 const Instruction *Load) {
391 if (!BinOp)
392 return MemoryAccess::RT_NONE;
393 switch (BinOp->getOpcode()) {
394 case Instruction::FAdd:
395 if (!BinOp->hasUnsafeAlgebra())
396 return MemoryAccess::RT_NONE;
397 // Fall through
398 case Instruction::Add:
399 return MemoryAccess::RT_ADD;
400 case Instruction::Or:
401 return MemoryAccess::RT_BOR;
402 case Instruction::Xor:
403 return MemoryAccess::RT_BXOR;
404 case Instruction::And:
405 return MemoryAccess::RT_BAND;
406 case Instruction::FMul:
407 if (!BinOp->hasUnsafeAlgebra())
408 return MemoryAccess::RT_NONE;
409 // Fall through
410 case Instruction::Mul:
411 if (DisableMultiplicativeReductions)
412 return MemoryAccess::RT_NONE;
413 return MemoryAccess::RT_MUL;
414 default:
415 return MemoryAccess::RT_NONE;
416 }
417}
Tobias Grosser75805372011-04-29 06:27:02 +0000418//===----------------------------------------------------------------------===//
419
420MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000421 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000422 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000423 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000424}
425
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000426static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
427 switch (Access.getType()) {
428 case IRAccess::READ:
429 return MemoryAccess::READ;
430 case IRAccess::MUST_WRITE:
431 return MemoryAccess::MUST_WRITE;
432 case IRAccess::MAY_WRITE:
433 return MemoryAccess::MAY_WRITE;
434 }
435 llvm_unreachable("Unknown IRAccess type!");
436}
437
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000438const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
439 isl_id *ArrayId = getArrayId();
440 void *User = isl_id_get_user(ArrayId);
441 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
442 isl_id_free(ArrayId);
443 return SAI;
444}
445
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000446__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000447 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
448}
449
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000450__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
451 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000452 isl_map *Schedule, *ScheduledAccRel;
453 isl_union_set *UDomain;
454
455 UDomain = isl_union_set_from_set(getStatement()->getDomain());
456 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
457 Schedule = isl_map_from_union_map(USchedule);
458 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
459 return isl_pw_multi_aff_from_map(ScheduledAccRel);
460}
461
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000462__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000463 return isl_map_copy(AccessRelation);
464}
465
Johannes Doerferta99130f2014-10-13 12:58:03 +0000466std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000467 return stringFromIslObj(AccessRelation);
468}
469
Johannes Doerferta99130f2014-10-13 12:58:03 +0000470__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000471 return isl_map_get_space(AccessRelation);
472}
473
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000474__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000475 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000476}
477
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000478__isl_give isl_basic_map *
479MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000480 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000481 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000482
Tobias Grosser084d8f72012-05-29 09:29:44 +0000483 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000484 isl_basic_set_universe(Statement->getDomainSpace()),
485 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000486}
487
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000488// Formalize no out-of-bound access assumption
489//
490// When delinearizing array accesses we optimistically assume that the
491// delinearized accesses do not access out of bound locations (the subscript
492// expression of each array evaluates for each statement instance that is
493// executed to a value that is larger than zero and strictly smaller than the
494// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000495// dimension for which we do not need to assume any upper bound. At this point
496// we formalize this assumption to ensure that at code generation time the
497// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000498//
499// To find the set of constraints necessary to avoid out of bound accesses, we
500// first build the set of data locations that are not within array bounds. We
501// then apply the reverse access relation to obtain the set of iterations that
502// may contain invalid accesses and reduce this set of iterations to the ones
503// that are actually executed by intersecting them with the domain of the
504// statement. If we now project out all loop dimensions, we obtain a set of
505// parameters that may cause statement instances to be executed that may
506// possibly yield out of bound memory accesses. The complement of these
507// constraints is the set of constraints that needs to be assumed to ensure such
508// statement instances are never executed.
509void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000510 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000511 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000512 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000513 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
514 isl_pw_aff *Var =
515 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
516 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
517
518 isl_set *DimOutside;
519
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000520 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
521 isl_pw_aff *SizeE = SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000522
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000523 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
524 Statement->getNumIterators());
525 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
526 isl_space_dim(Space, isl_dim_set));
527 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
528 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000529
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000530 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000531
532 Outside = isl_set_union(Outside, DimOutside);
533 }
534
535 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
536 Outside = isl_set_intersect(Outside, Statement->getDomain());
537 Outside = isl_set_params(Outside);
538 Outside = isl_set_complement(Outside);
539 Statement->getParent()->addAssumption(Outside);
540 isl_space_free(Space);
541}
542
Johannes Doerferte7044942015-02-24 11:58:30 +0000543void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
544 ScalarEvolution *SE = Statement->getParent()->getSE();
545
546 Value *Ptr = getPointerOperand(*getAccessInstruction());
547 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
548 return;
549
550 auto *PtrSCEV = SE->getSCEV(Ptr);
551 if (isa<SCEVCouldNotCompute>(PtrSCEV))
552 return;
553
554 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
555 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
556 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
557
558 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
559 if (Range.isFullSet())
560 return;
561
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000562 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000563 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000564 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
565 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
566
567 auto Min = LB.sdiv(APInt(BW, ElementSize));
568 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000569
570 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
571 AccessRange =
572 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
573 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
574}
575
Tobias Grosser619190d2015-03-30 17:22:28 +0000576__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
577 __isl_take isl_map *AccessRelation,
578 ScopStmt *Statement) {
579 int Size = Access.Subscripts.size();
580
581 for (int i = Size - 2; i >= 0; --i) {
582 isl_space *Space;
583 isl_map *MapOne, *MapTwo;
584 isl_pw_aff *DimSize = SCEVAffinator::getPwAff(Statement, Access.Sizes[i]);
585
586 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
587 isl_pw_aff_free(DimSize);
588 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
589
590 Space = isl_map_get_space(AccessRelation);
591 Space = isl_space_map_from_set(isl_space_range(Space));
592 Space = isl_space_align_params(Space, SpaceSize);
593
594 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
595 isl_id_free(ParamId);
596
597 MapOne = isl_map_universe(isl_space_copy(Space));
598 for (int j = 0; j < Size; ++j)
599 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
600 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
601
602 MapTwo = isl_map_universe(isl_space_copy(Space));
603 for (int j = 0; j < Size; ++j)
604 if (j < i || j > i + 1)
605 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
606
607 isl_local_space *LS = isl_local_space_from_space(Space);
608 isl_constraint *C;
609 C = isl_equality_alloc(isl_local_space_copy(LS));
610 C = isl_constraint_set_constant_si(C, -1);
611 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
612 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
613 MapTwo = isl_map_add_constraint(MapTwo, C);
614 C = isl_equality_alloc(LS);
615 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
616 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
617 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
618 MapTwo = isl_map_add_constraint(MapTwo, C);
619 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
620
621 MapOne = isl_map_union(MapOne, MapTwo);
622 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
623 }
624 return AccessRelation;
625}
626
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000627MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000628 ScopStmt *Statement, const ScopArrayInfo *SAI,
629 int Identifier)
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000630 : AccType(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000631 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000632
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000633 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000634 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000635 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000636
637 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000638
Tobias Grossere29d31c2015-05-15 12:24:09 +0000639 auto IdName = "__polly_array_ref_ " + std::to_string(Identifier);
640 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000641
Tobias Grossera1879642011-12-20 10:43:14 +0000642 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000643 // We overapproximate non-affine accesses with a possible access to the
644 // whole array. For read accesses it does not make a difference, if an
645 // access must or may happen. However, for write accesses it is important to
646 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000647 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000648 AccessRelation =
649 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000650
651 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000652 return;
653 }
654
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000655 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000656 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000657
Tobias Grosser79baa212014-04-10 08:38:02 +0000658 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000659 isl_pw_aff *Affine =
660 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000661
Sebastian Pop422e33f2014-06-03 18:16:31 +0000662 if (Size == 1) {
663 // For the non delinearized arrays, divide the access function of the last
664 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000665 //
666 // A stride one array access in C expressed as A[i] is expressed in
667 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
668 // two subsequent values of 'i' index two values that are stored next to
669 // each other in memory. By this division we make this characteristic
670 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000671 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000672 Affine = isl_pw_aff_scale_down_val(Affine, v);
673 }
674
675 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
676
Tobias Grosser79baa212014-04-10 08:38:02 +0000677 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000678 }
679
Tobias Grosser619190d2015-03-30 17:22:28 +0000680 AccessRelation = foldAccess(Access, AccessRelation, Statement);
681
Tobias Grosser79baa212014-04-10 08:38:02 +0000682 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000683 AccessRelation = isl_map_set_tuple_id(
684 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000685 AccessRelation =
686 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
687
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000688 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000689 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000690 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000691}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000692
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000693void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000694 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000695 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000696}
697
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000698const std::string MemoryAccess::getReductionOperatorStr() const {
699 return MemoryAccess::getReductionOperatorStr(getReductionType());
700}
701
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000702__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
703
Johannes Doerfertf6183392014-07-01 20:52:51 +0000704raw_ostream &polly::operator<<(raw_ostream &OS,
705 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000706 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000707 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000708 else
709 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000710 return OS;
711}
712
Tobias Grosser75805372011-04-29 06:27:02 +0000713void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000714 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000715 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000716 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000717 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000718 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000719 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000720 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000721 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000722 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000723 break;
724 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000725 OS << "[Reduction Type: " << getReductionType() << "] ";
726 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000727 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000728}
729
Tobias Grosser74394f02013-01-14 22:40:23 +0000730void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000731
732// Create a map in the size of the provided set domain, that maps from the
733// one element of the provided set domain to another element of the provided
734// set domain.
735// The mapping is limited to all points that are equal in all but the last
736// dimension and for which the last dimension of the input is strict smaller
737// than the last dimension of the output.
738//
739// getEqualAndLarger(set[i0, i1, ..., iX]):
740//
741// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
742// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
743//
Tobias Grosserf5338802011-10-06 00:03:35 +0000744static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000745 isl_space *Space = isl_space_map_from_set(setDomain);
746 isl_map *Map = isl_map_universe(isl_space_copy(Space));
747 isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000748 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000749
750 // Set all but the last dimension to be equal for the input and output
751 //
752 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
753 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000754 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000755 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000756
757 // Set the last dimension of the input to be strict smaller than the
758 // last dimension of the output.
759 //
760 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
761 //
Tobias Grosseredab1352013-06-21 06:41:31 +0000762 isl_val *v;
763 isl_ctx *Ctx = isl_map_get_ctx(Map);
Tobias Grosserf5338802011-10-06 00:03:35 +0000764 isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
Tobias Grosseredab1352013-06-21 06:41:31 +0000765 v = isl_val_int_from_si(Ctx, -1);
766 c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
767 v = isl_val_int_from_si(Ctx, 1);
768 c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
769 v = isl_val_int_from_si(Ctx, -1);
770 c = isl_constraint_set_constant_val(c, v);
Tobias Grosser75805372011-04-29 06:27:02 +0000771
Tobias Grosserc327932c2012-02-01 14:23:36 +0000772 Map = isl_map_add_constraint(Map, c);
Tobias Grosser75805372011-04-29 06:27:02 +0000773
Tobias Grosser23b36662011-10-17 08:32:36 +0000774 isl_local_space_free(MapLocalSpace);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000775 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000776}
777
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000778__isl_give isl_set *
779MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000780 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000781 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000782 isl_space *Space = isl_space_range(isl_map_get_space(S));
783 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000784
Sebastian Popa00a0292012-12-18 07:46:06 +0000785 S = isl_map_reverse(S);
786 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000787
Sebastian Popa00a0292012-12-18 07:46:06 +0000788 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
789 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
790 NextScatt = isl_map_apply_domain(NextScatt, S);
791 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000792
Sebastian Popa00a0292012-12-18 07:46:06 +0000793 isl_set *Deltas = isl_map_deltas(NextScatt);
794 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000795}
796
Sebastian Popa00a0292012-12-18 07:46:06 +0000797bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000798 int StrideWidth) const {
799 isl_set *Stride, *StrideX;
800 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000801
Sebastian Popa00a0292012-12-18 07:46:06 +0000802 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000803 StrideX = isl_set_universe(isl_set_get_space(Stride));
804 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
805 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000806
Tobias Grosser28dd4862012-01-24 16:42:16 +0000807 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000808 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000809
Tobias Grosser28dd4862012-01-24 16:42:16 +0000810 return IsStrideX;
811}
812
Sebastian Popa00a0292012-12-18 07:46:06 +0000813bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
814 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000815}
816
Tobias Grosser79baa212014-04-10 08:38:02 +0000817bool MemoryAccess::isScalar() const {
818 return isl_map_n_out(AccessRelation) == 0;
819}
820
Sebastian Popa00a0292012-12-18 07:46:06 +0000821bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
822 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000823}
824
Tobias Grosser5d453812011-10-06 00:04:11 +0000825void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000826 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000827 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000828}
Tobias Grosser75805372011-04-29 06:27:02 +0000829
830//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000831
Tobias Grosser54839312015-04-21 11:37:25 +0000832isl_map *ScopStmt::getSchedule() const { return isl_map_copy(Schedule); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000833
Tobias Grosser37eb4222014-02-20 21:43:54 +0000834void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
835 assert(isl_set_is_subset(NewDomain, Domain) &&
836 "New domain is not a subset of old domain!");
837 isl_set_free(Domain);
838 Domain = NewDomain;
Tobias Grosser54839312015-04-21 11:37:25 +0000839 Schedule = isl_map_intersect_domain(Schedule, isl_set_copy(Domain));
Tobias Grosser37eb4222014-02-20 21:43:54 +0000840}
841
Tobias Grosser54839312015-04-21 11:37:25 +0000842void ScopStmt::setSchedule(__isl_take isl_map *NewSchedule) {
843 assert(NewSchedule && "New schedule is nullptr");
844 isl_map_free(Schedule);
845 Schedule = NewSchedule;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000846}
847
Tobias Grosser54839312015-04-21 11:37:25 +0000848void ScopStmt::buildSchedule(SmallVectorImpl<unsigned> &ScheduleVec) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000849 unsigned NbIterators = getNumIterators();
Tobias Grosser54839312015-04-21 11:37:25 +0000850 unsigned NbScheduleDims = Parent.getMaxLoopDepth() * 2 + 1;
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000851
Tobias Grosser54839312015-04-21 11:37:25 +0000852 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScheduleDims);
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000853
Tobias Grosser54839312015-04-21 11:37:25 +0000854 Schedule = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
Tobias Grosser654af8f2015-04-21 11:42:01 +0000855 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000856
857 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000858 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosser654af8f2015-04-21 11:42:01 +0000859 Schedule = isl_map_equate(Schedule, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000860
861 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000862 for (unsigned i = 0; i < NbIterators + 1; ++i)
Tobias Grosser54839312015-04-21 11:37:25 +0000863 Schedule = isl_map_fix_si(Schedule, isl_dim_out, 2 * i, ScheduleVec[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000864
Tobias Grosser54839312015-04-21 11:37:25 +0000865 // Fill schedule dimensions.
866 for (unsigned i = 2 * NbIterators + 1; i < NbScheduleDims; ++i)
867 Schedule = isl_map_fix_si(Schedule, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000868
Tobias Grosser54839312015-04-21 11:37:25 +0000869 Schedule = isl_map_align_params(Schedule, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000870}
871
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000872void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
873 bool isApproximated) {
874 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
875 if (!AFS)
876 return;
877
878 for (auto &AccessPair : *AFS) {
879 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000880 Instruction *AccessInst = AccessPair.second;
881
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000882 Type *AccessType = getAccessInstType(AccessInst)->getPointerTo();
883 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
884 Access.getBase(), AccessType, Access.Sizes);
885
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000886 if (isApproximated && Access.isWrite())
887 Access.setMayWrite();
888
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000889 MemAccs.push_back(
Tobias Grosser4ac75ba2015-05-15 12:24:12 +0000890 new MemoryAccess(Access, AccessInst, this, SAI, MemAccs.size()));
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000891
892 // We do not track locations for scalar memory accesses at the moment.
893 //
894 // We do not have a use for this information at the moment. If we need this
895 // at some point, the "instruction -> access" mapping needs to be enhanced
896 // as a single instruction could then possibly perform multiple accesses.
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000897 if (!Access.isScalar()) {
898 assert(!InstructionToAccess.count(AccessInst) &&
Tobias Grosser3fc91542014-02-20 21:43:45 +0000899 "Unexpected 1-to-N mapping on instruction to access map!");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000900 InstructionToAccess[AccessInst] = MemAccs.back();
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000901 }
Tobias Grosser75805372011-04-29 06:27:02 +0000902 }
903}
904
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000905void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000906 for (MemoryAccess *MA : *this)
907 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000908
909 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser54839312015-04-21 11:37:25 +0000910 Schedule = isl_map_align_params(Schedule, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000911}
912
Tobias Grosser65b00582011-11-08 15:41:19 +0000913__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000914 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
915 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000916
Tobias Grosserd2795d02011-08-18 07:51:40 +0000917 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000918 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000919 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000920 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000921 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000922 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000923 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000924 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000925 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000926 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000927 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000928 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000929 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000930 case ICmpInst::ICMP_ULT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000931 return isl_pw_aff_lt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000932 case ICmpInst::ICMP_UGT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000933 return isl_pw_aff_gt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000934 case ICmpInst::ICMP_ULE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000935 return isl_pw_aff_le_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000936 case ICmpInst::ICMP_UGE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000937 return isl_pw_aff_ge_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000938 default:
939 llvm_unreachable("Non integer predicate not supported");
940 }
Tobias Grosser75805372011-04-29 06:27:02 +0000941}
942
Tobias Grossere19661e2011-10-07 08:46:57 +0000943__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000944 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000945 isl_space *Space;
946 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000947
Tobias Grossere19661e2011-10-07 08:46:57 +0000948 Space = isl_set_get_space(Domain);
949 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000950
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000951 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000952 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000953 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000954 isl_pw_aff *IV =
955 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000956
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000957 // 0 <= IV.
958 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
959 Domain = isl_set_intersect(Domain, LowerBound);
960
961 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000962 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000963 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000964 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
965 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000966 Domain = isl_set_intersect(Domain, UpperBoundSet);
967 }
968
Tobias Grosserf5338802011-10-06 00:03:35 +0000969 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000970 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000971}
972
Tobias Grossere602a072013-05-07 07:30:56 +0000973__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
974 TempScop &tempScop,
975 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000976 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000977 *CurrentRegion = &CurRegion;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000978 const BasicBlock *BranchingBB = BB ? BB : R->getEntry();
Tobias Grosser75805372011-04-29 06:27:02 +0000979
Tobias Grosser75805372011-04-29 06:27:02 +0000980 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000981 if (BranchingBB != CurrentRegion->getEntry()) {
982 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000983 for (const auto &C : *Condition) {
984 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000985 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000986 }
987 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000988 BranchingBB = CurrentRegion->getEntry();
989 CurrentRegion = CurrentRegion->getParent();
990 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000991
Tobias Grossere19661e2011-10-07 08:46:57 +0000992 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000993}
994
Tobias Grossere602a072013-05-07 07:30:56 +0000995__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
996 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000997 isl_space *Space;
998 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000999 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001000
1001 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
1002
Tobias Grosser084d8f72012-05-29 09:29:44 +00001003 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1004
Tobias Grossere19661e2011-10-07 08:46:57 +00001005 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +00001006 Domain = addLoopBoundsToDomain(Domain, tempScop);
1007 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001008 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +00001009
1010 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +00001011}
1012
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001013void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
1014 int Dimension = 0;
1015 isl_ctx *Ctx = Parent.getIslCtx();
1016 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1017 Type *Ty = GEP->getPointerOperandType();
1018 ScalarEvolution &SE = *Parent.getSE();
1019
1020 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
1021 Dimension = 1;
1022 Ty = PtrTy->getElementType();
1023 }
1024
1025 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
1026 unsigned int Operand = 1 + Dimension;
1027
1028 if (GEP->getNumOperands() <= Operand)
1029 break;
1030
1031 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
1032
1033 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
1034 isl_pw_aff *AccessOffset = SCEVAffinator::getPwAff(this, Expr);
1035 AccessOffset =
1036 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
1037
1038 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1039 isl_local_space_copy(LSpace),
1040 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
1041
1042 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1043 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1044 OutOfBound = isl_set_params(OutOfBound);
1045 isl_set *InBound = isl_set_complement(OutOfBound);
1046 isl_set *Executed = isl_set_params(getDomain());
1047
1048 // A => B == !A or B
1049 isl_set *InBoundIfExecuted =
1050 isl_set_union(isl_set_complement(Executed), InBound);
1051
1052 Parent.addAssumption(InBoundIfExecuted);
1053 }
1054
1055 Dimension += 1;
1056 Ty = ArrayTy->getElementType();
1057 }
1058
1059 isl_local_space_free(LSpace);
1060}
1061
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001062void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1063 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001064 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1065 deriveAssumptionsFromGEP(GEP);
1066}
1067
Tobias Grosser74394f02013-01-14 22:40:23 +00001068ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001069 Region &R, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser54839312015-04-21 11:37:25 +00001070 SmallVectorImpl<unsigned> &ScheduleVec)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001071 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
1072 NestLoops(Nest.size()) {
1073 // Setup the induction variables.
1074 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
1075 NestLoops[i] = Nest[i];
1076
1077 BaseName = getIslCompatibleName("Stmt_(", R.getNameStr(), ")");
1078
1079 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser54839312015-04-21 11:37:25 +00001080 buildSchedule(ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001081
1082 BasicBlock *EntryBB = R.getEntry();
1083 for (BasicBlock *Block : R.blocks()) {
1084 buildAccesses(tempScop, Block, Block != EntryBB);
1085 deriveAssumptions(Block);
1086 }
1087 checkForReductions();
1088}
1089
1090ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +00001091 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser54839312015-04-21 11:37:25 +00001092 SmallVectorImpl<unsigned> &ScheduleVec)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001093 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
1094 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +00001095 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +00001096 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +00001097 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +00001098
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001099 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001100
Tobias Grossere19661e2011-10-07 08:46:57 +00001101 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser54839312015-04-21 11:37:25 +00001102 buildSchedule(ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001103 buildAccesses(tempScop, BB);
1104 deriveAssumptions(BB);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001105 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001106}
1107
Johannes Doerferte58a0122014-06-27 20:31:28 +00001108/// @brief Collect loads which might form a reduction chain with @p StoreMA
1109///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001110/// Check if the stored value for @p StoreMA is a binary operator with one or
1111/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001112/// used only once (by @p StoreMA) and its load operands are also used only
1113/// once, we have found a possible reduction chain. It starts at an operand
1114/// load and includes the binary operator and @p StoreMA.
1115///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001116/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001117/// escape this block or into any other store except @p StoreMA.
1118void ScopStmt::collectCandiateReductionLoads(
1119 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1120 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1121 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001122 return;
1123
1124 // Skip if there is not one binary operator between the load and the store
1125 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001126 if (!BinOp)
1127 return;
1128
1129 // Skip if the binary operators has multiple uses
1130 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001131 return;
1132
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001133 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001134 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1135 return;
1136
Johannes Doerfert9890a052014-07-01 00:32:29 +00001137 // Skip if the binary operator is outside the current SCoP
1138 if (BinOp->getParent() != Store->getParent())
1139 return;
1140
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001141 // Skip if it is a multiplicative reduction and we disabled them
1142 if (DisableMultiplicativeReductions &&
1143 (BinOp->getOpcode() == Instruction::Mul ||
1144 BinOp->getOpcode() == Instruction::FMul))
1145 return;
1146
Johannes Doerferte58a0122014-06-27 20:31:28 +00001147 // Check the binary operator operands for a candidate load
1148 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1149 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1150 if (!PossibleLoad0 && !PossibleLoad1)
1151 return;
1152
1153 // A load is only a candidate if it cannot escape (thus has only this use)
1154 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001155 if (PossibleLoad0->getParent() == Store->getParent())
1156 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001157 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001158 if (PossibleLoad1->getParent() == Store->getParent())
1159 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001160}
1161
1162/// @brief Check for reductions in this ScopStmt
1163///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001164/// Iterate over all store memory accesses and check for valid binary reduction
1165/// like chains. For all candidates we check if they have the same base address
1166/// and there are no other accesses which overlap with them. The base address
1167/// check rules out impossible reductions candidates early. The overlap check,
1168/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001169/// guarantees that none of the intermediate results will escape during
1170/// execution of the loop nest. We basically check here that no other memory
1171/// access can access the same memory as the potential reduction.
1172void ScopStmt::checkForReductions() {
1173 SmallVector<MemoryAccess *, 2> Loads;
1174 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1175
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001176 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001177 // stores and collecting possible reduction loads.
1178 for (MemoryAccess *StoreMA : MemAccs) {
1179 if (StoreMA->isRead())
1180 continue;
1181
1182 Loads.clear();
1183 collectCandiateReductionLoads(StoreMA, Loads);
1184 for (MemoryAccess *LoadMA : Loads)
1185 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1186 }
1187
1188 // Then check each possible candidate pair.
1189 for (const auto &CandidatePair : Candidates) {
1190 bool Valid = true;
1191 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1192 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1193
1194 // Skip those with obviously unequal base addresses.
1195 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1196 isl_map_free(LoadAccs);
1197 isl_map_free(StoreAccs);
1198 continue;
1199 }
1200
1201 // And check if the remaining for overlap with other memory accesses.
1202 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1203 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1204 isl_set *AllAccs = isl_map_range(AllAccsRel);
1205
1206 for (MemoryAccess *MA : MemAccs) {
1207 if (MA == CandidatePair.first || MA == CandidatePair.second)
1208 continue;
1209
1210 isl_map *AccRel =
1211 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1212 isl_set *Accs = isl_map_range(AccRel);
1213
1214 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1215 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1216 Valid = Valid && isl_set_is_empty(OverlapAccs);
1217 isl_set_free(OverlapAccs);
1218 }
1219 }
1220
1221 isl_set_free(AllAccs);
1222 if (!Valid)
1223 continue;
1224
Johannes Doerfertf6183392014-07-01 20:52:51 +00001225 const LoadInst *Load =
1226 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1227 MemoryAccess::ReductionType RT =
1228 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1229
Johannes Doerferte58a0122014-06-27 20:31:28 +00001230 // If no overlapping access was found we mark the load and store as
1231 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001232 CandidatePair.first->markAsReductionLike(RT);
1233 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001234 }
Tobias Grosser75805372011-04-29 06:27:02 +00001235}
1236
Tobias Grosser74394f02013-01-14 22:40:23 +00001237std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001238
Tobias Grosser54839312015-04-21 11:37:25 +00001239std::string ScopStmt::getScheduleStr() const {
1240 return stringFromIslObj(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001241}
1242
Tobias Grosser74394f02013-01-14 22:40:23 +00001243unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001244
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001245unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001246
Tobias Grosser54839312015-04-21 11:37:25 +00001247unsigned ScopStmt::getNumSchedule() const {
1248 return isl_map_dim(Schedule, isl_dim_out);
Tobias Grosser75805372011-04-29 06:27:02 +00001249}
1250
1251const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1252
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001253const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001254 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001255}
1256
Tobias Grosser74394f02013-01-14 22:40:23 +00001257isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001258
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001259__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001260
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001261__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001262 return isl_set_get_space(Domain);
1263}
1264
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001265__isl_give isl_id *ScopStmt::getDomainId() const {
1266 return isl_set_get_tuple_id(Domain);
1267}
Tobias Grossercd95b772012-08-30 11:49:38 +00001268
Tobias Grosser75805372011-04-29 06:27:02 +00001269ScopStmt::~ScopStmt() {
1270 while (!MemAccs.empty()) {
1271 delete MemAccs.back();
1272 MemAccs.pop_back();
1273 }
1274
1275 isl_set_free(Domain);
Tobias Grosser54839312015-04-21 11:37:25 +00001276 isl_map_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001277}
1278
1279void ScopStmt::print(raw_ostream &OS) const {
1280 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001281 OS.indent(12) << "Domain :=\n";
1282
1283 if (Domain) {
1284 OS.indent(16) << getDomainStr() << ";\n";
1285 } else
1286 OS.indent(16) << "n/a\n";
1287
Tobias Grosser54839312015-04-21 11:37:25 +00001288 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001289
1290 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001291 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001292 } else
1293 OS.indent(16) << "n/a\n";
1294
Tobias Grosser083d3d32014-06-28 08:59:45 +00001295 for (MemoryAccess *Access : MemAccs)
1296 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001297}
1298
1299void ScopStmt::dump() const { print(dbgs()); }
1300
1301//===----------------------------------------------------------------------===//
1302/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001303
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001304void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001305 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1306 isl_set_free(Context);
1307 Context = NewContext;
1308}
1309
Tobias Grosserabfbe632013-02-05 12:09:06 +00001310void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001311 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001312 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001313 if (ParameterIds.find(Parameter) != ParameterIds.end())
1314 continue;
1315
1316 int dimension = Parameters.size();
1317
1318 Parameters.push_back(Parameter);
1319 ParameterIds[Parameter] = dimension;
1320 }
1321}
1322
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001323__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1324 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001325
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001326 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001327 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001328
Tobias Grosser8f99c162011-11-15 11:38:55 +00001329 std::string ParameterName;
1330
1331 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1332 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001333 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001334 }
1335
1336 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001337 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001338
Tobias Grosser20532b82014-04-11 17:56:49 +00001339 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1340 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001341}
Tobias Grosser75805372011-04-29 06:27:02 +00001342
Tobias Grosser6be480c2011-11-08 15:41:13 +00001343void Scop::buildContext() {
1344 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001345 Context = isl_set_universe(isl_space_copy(Space));
1346 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001347}
1348
Tobias Grosser18daaca2012-05-22 10:47:27 +00001349void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001350 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001351 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001352
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001353 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001354
Johannes Doerferte7044942015-02-24 11:58:30 +00001355 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001356 }
1357}
1358
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001359void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001360 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001361 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001362
Tobias Grosser083d3d32014-06-28 08:59:45 +00001363 for (const auto &ParamID : ParameterIds) {
1364 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001365 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001366 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001367 }
1368
1369 // Align the parameters of all data structures to the model.
1370 Context = isl_set_align_params(Context, Space);
1371
Tobias Grosser083d3d32014-06-28 08:59:45 +00001372 for (ScopStmt *Stmt : *this)
1373 Stmt->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001374}
1375
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001376void Scop::simplifyAssumedContext() {
1377 // The parameter constraints of the iteration domains give us a set of
1378 // constraints that need to hold for all cases where at least a single
1379 // statement iteration is executed in the whole scop. We now simplify the
1380 // assumed context under the assumption that such constraints hold and at
1381 // least a single statement iteration is executed. For cases where no
1382 // statement instances are executed, the assumptions we have taken about
1383 // the executed code do not matter and can be changed.
1384 //
1385 // WARNING: This only holds if the assumptions we have taken do not reduce
1386 // the set of statement instances that are executed. Otherwise we
1387 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001388 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001389 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001390 // performed. In such a case, modifying the run-time conditions and
1391 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001392 // to not be executed.
1393 //
1394 // Example:
1395 //
1396 // When delinearizing the following code:
1397 //
1398 // for (long i = 0; i < 100; i++)
1399 // for (long j = 0; j < m; j++)
1400 // A[i+p][j] = 1.0;
1401 //
1402 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001403 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001404 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1405 AssumedContext =
1406 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001407 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001408}
1409
Johannes Doerfertb164c792014-09-18 11:17:17 +00001410/// @brief Add the minimal/maximal access in @p Set to @p User.
1411static int buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
1412 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1413 isl_pw_multi_aff *MinPMA, *MaxPMA;
1414 isl_pw_aff *LastDimAff;
1415 isl_aff *OneAff;
1416 unsigned Pos;
1417
Johannes Doerfert9143d672014-09-27 11:02:39 +00001418 // Restrict the number of parameters involved in the access as the lexmin/
1419 // lexmax computation will take too long if this number is high.
1420 //
1421 // Experiments with a simple test case using an i7 4800MQ:
1422 //
1423 // #Parameters involved | Time (in sec)
1424 // 6 | 0.01
1425 // 7 | 0.04
1426 // 8 | 0.12
1427 // 9 | 0.40
1428 // 10 | 1.54
1429 // 11 | 6.78
1430 // 12 | 30.38
1431 //
1432 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1433 unsigned InvolvedParams = 0;
1434 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1435 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1436 InvolvedParams++;
1437
1438 if (InvolvedParams > RunTimeChecksMaxParameters) {
1439 isl_set_free(Set);
1440 return -1;
1441 }
1442 }
1443
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001444 Set = isl_set_remove_divs(Set);
1445
Johannes Doerfertb164c792014-09-18 11:17:17 +00001446 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1447 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1448
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001449 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1450 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1451
Johannes Doerfertb164c792014-09-18 11:17:17 +00001452 // Adjust the last dimension of the maximal access by one as we want to
1453 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1454 // we test during code generation might now point after the end of the
1455 // allocated array but we will never dereference it anyway.
1456 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1457 "Assumed at least one output dimension");
1458 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1459 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1460 OneAff = isl_aff_zero_on_domain(
1461 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1462 OneAff = isl_aff_add_constant_si(OneAff, 1);
1463 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1464 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1465
1466 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1467
1468 isl_set_free(Set);
1469 return 0;
1470}
1471
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001472static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1473 isl_set *Domain = MA->getStatement()->getDomain();
1474 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1475 return isl_set_reset_tuple_id(Domain);
1476}
1477
Johannes Doerfert9143d672014-09-27 11:02:39 +00001478bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001479 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001480 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001481 // for all memory accesses inside the SCoP.
1482 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001483 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001484 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001485 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001486 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001487 // if their access domains intersect, otherwise they are in different
1488 // ones.
Johannes Doerfert13771732014-10-01 12:40:46 +00001489 // o) We split groups such that they contain at most one read only base
1490 // address.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001491 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfertb164c792014-09-18 11:17:17 +00001492 // and maximal accesses to each array in this group.
1493 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1494
1495 AliasSetTracker AST(AA);
1496
1497 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001498 DenseSet<Value *> HasWriteAccess;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001499 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001500
1501 // Skip statements with an empty domain as they will never be executed.
1502 isl_set *StmtDomain = Stmt->getDomain();
1503 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1504 isl_set_free(StmtDomain);
1505 if (StmtDomainEmpty)
1506 continue;
1507
Johannes Doerfertb164c792014-09-18 11:17:17 +00001508 for (MemoryAccess *MA : *Stmt) {
1509 if (MA->isScalar())
1510 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001511 if (!MA->isRead())
1512 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001513 Instruction *Acc = MA->getAccessInstruction();
1514 PtrToAcc[getPointerOperand(*Acc)] = MA;
1515 AST.add(Acc);
1516 }
1517 }
1518
1519 SmallVector<AliasGroupTy, 4> AliasGroups;
1520 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001521 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001522 continue;
1523 AliasGroupTy AG;
1524 for (auto PR : AS)
1525 AG.push_back(PtrToAcc[PR.getValue()]);
1526 assert(AG.size() > 1 &&
1527 "Alias groups should contain at least two accesses");
1528 AliasGroups.push_back(std::move(AG));
1529 }
1530
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001531 // Split the alias groups based on their domain.
1532 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1533 AliasGroupTy NewAG;
1534 AliasGroupTy &AG = AliasGroups[u];
1535 AliasGroupTy::iterator AGI = AG.begin();
1536 isl_set *AGDomain = getAccessDomain(*AGI);
1537 while (AGI != AG.end()) {
1538 MemoryAccess *MA = *AGI;
1539 isl_set *MADomain = getAccessDomain(MA);
1540 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1541 NewAG.push_back(MA);
1542 AGI = AG.erase(AGI);
1543 isl_set_free(MADomain);
1544 } else {
1545 AGDomain = isl_set_union(AGDomain, MADomain);
1546 AGI++;
1547 }
1548 }
1549 if (NewAG.size() > 1)
1550 AliasGroups.push_back(std::move(NewAG));
1551 isl_set_free(AGDomain);
1552 }
1553
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001554 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001555 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1556 for (AliasGroupTy &AG : AliasGroups) {
1557 NonReadOnlyBaseValues.clear();
1558 ReadOnlyPairs.clear();
1559
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001560 if (AG.size() < 2) {
1561 AG.clear();
1562 continue;
1563 }
1564
Johannes Doerfert13771732014-10-01 12:40:46 +00001565 for (auto II = AG.begin(); II != AG.end();) {
1566 Value *BaseAddr = (*II)->getBaseAddr();
1567 if (HasWriteAccess.count(BaseAddr)) {
1568 NonReadOnlyBaseValues.insert(BaseAddr);
1569 II++;
1570 } else {
1571 ReadOnlyPairs[BaseAddr].insert(*II);
1572 II = AG.erase(II);
1573 }
1574 }
1575
1576 // If we don't have read only pointers check if there are at least two
1577 // non read only pointers, otherwise clear the alias group.
1578 if (ReadOnlyPairs.empty()) {
1579 if (NonReadOnlyBaseValues.size() <= 1)
1580 AG.clear();
1581 continue;
1582 }
1583
1584 // If we don't have non read only pointers clear the alias group.
1585 if (NonReadOnlyBaseValues.empty()) {
1586 AG.clear();
1587 continue;
1588 }
1589
1590 // If we have both read only and non read only base pointers we combine
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001591 // the non read only ones with exactly one read only one at a time into a
Johannes Doerfert13771732014-10-01 12:40:46 +00001592 // new alias group and clear the old alias group in the end.
1593 for (const auto &ReadOnlyPair : ReadOnlyPairs) {
1594 AliasGroupTy AGNonReadOnly = AG;
1595 for (MemoryAccess *MA : ReadOnlyPair.second)
1596 AGNonReadOnly.push_back(MA);
1597 AliasGroups.push_back(std::move(AGNonReadOnly));
1598 }
1599 AG.clear();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001600 }
1601
1602 for (AliasGroupTy &AG : AliasGroups) {
Johannes Doerfert13771732014-10-01 12:40:46 +00001603 if (AG.empty())
1604 continue;
1605
Johannes Doerfertb164c792014-09-18 11:17:17 +00001606 MinMaxVectorTy *MinMaxAccesses = new MinMaxVectorTy();
1607 MinMaxAccesses->reserve(AG.size());
1608
1609 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
1610 for (MemoryAccess *MA : AG)
1611 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1612 Accesses = isl_union_map_intersect_domain(Accesses, getDomains());
1613
1614 isl_union_set *Locations = isl_union_map_range(Accesses);
1615 Locations = isl_union_set_intersect_params(Locations, getAssumedContext());
1616 Locations = isl_union_set_coalesce(Locations);
1617 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001618 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
1619 MinMaxAccesses));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001620 isl_union_set_free(Locations);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001621 MinMaxAliasGroups.push_back(MinMaxAccesses);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001622
1623 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001624 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001625 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001626
Tobias Grosser71500722015-03-28 15:11:14 +00001627 // Bail out if the number of values we need to compare is too large.
1628 // This is important as the number of comparisions grows quadratically with
1629 // the number of values we need to compare.
1630 for (const auto *Values : MinMaxAliasGroups)
1631 if (Values->size() > RunTimeChecksMaxArraysPerGroup)
1632 return false;
1633
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001634 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001635}
1636
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001637static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1638 ScopDetection &SD) {
1639
1640 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1641
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001642 unsigned MinLD = INT_MAX, MaxLD = 0;
1643 for (BasicBlock *BB : R.blocks()) {
1644 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001645 if (!R.contains(L))
1646 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001647 if (BoxedLoops && BoxedLoops->count(L))
1648 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001649 unsigned LD = L->getLoopDepth();
1650 MinLD = std::min(MinLD, LD);
1651 MaxLD = std::max(MaxLD, LD);
1652 }
1653 }
1654
1655 // Handle the case that there is no loop in the SCoP first.
1656 if (MaxLD == 0)
1657 return 1;
1658
1659 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1660 assert(MaxLD >= MinLD &&
1661 "Maximal loop depth was smaller than mininaml loop depth?");
1662 return MaxLD - MinLD + 1;
1663}
1664
Tobias Grosser3f296192015-01-01 23:01:11 +00001665void Scop::dropConstantScheduleDims() {
1666 isl_union_map *FullSchedule = getSchedule();
1667
1668 if (isl_union_map_n_map(FullSchedule) == 0) {
1669 isl_union_map_free(FullSchedule);
1670 return;
1671 }
1672
1673 isl_set *ScheduleSpace =
1674 isl_set_from_union_set(isl_union_map_range(FullSchedule));
1675 isl_map *DropDimMap = isl_set_identity(isl_set_copy(ScheduleSpace));
1676
1677 int NumDimsDropped = 0;
Johannes Doerfert3f21e272015-03-04 22:23:21 +00001678 for (unsigned i = 0; i < isl_set_dim(ScheduleSpace, isl_dim_set); i += 2) {
1679 isl_val *FixedVal =
1680 isl_set_plain_get_val_if_fixed(ScheduleSpace, isl_dim_set, i);
1681 if (isl_val_is_int(FixedVal)) {
1682 DropDimMap =
1683 isl_map_project_out(DropDimMap, isl_dim_out, i - NumDimsDropped, 1);
1684 NumDimsDropped++;
Tobias Grosser3f296192015-01-01 23:01:11 +00001685 }
Johannes Doerfert3f21e272015-03-04 22:23:21 +00001686 isl_val_free(FixedVal);
1687 }
Tobias Grosser3f296192015-01-01 23:01:11 +00001688
Tobias Grosser3f296192015-01-01 23:01:11 +00001689 for (auto *S : *this) {
Tobias Grosser54839312015-04-21 11:37:25 +00001690 isl_map *Schedule = S->getSchedule();
Tobias Grosser3f296192015-01-01 23:01:11 +00001691 Schedule = isl_map_apply_range(Schedule, isl_map_copy(DropDimMap));
Tobias Grosser54839312015-04-21 11:37:25 +00001692 S->setSchedule(Schedule);
Tobias Grosser3f296192015-01-01 23:01:11 +00001693 }
1694 isl_set_free(ScheduleSpace);
1695 isl_map_free(DropDimMap);
1696}
1697
Tobias Grosser0e27e242011-10-06 00:03:48 +00001698Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001699 ScopDetection &SD, isl_ctx *Context)
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001700 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()), IsOptimized(false),
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001701 MaxLoopDepth(getMaxLoopDepthInRegion(tempScop.getMaxRegion(), LI, SD)) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001702 IslCtx = Context;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001703
Tobias Grosser6be480c2011-11-08 15:41:13 +00001704 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001705
Tobias Grosserabfbe632013-02-05 12:09:06 +00001706 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser54839312015-04-21 11:37:25 +00001707 SmallVector<unsigned, 8> Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00001708
Tobias Grosser54839312015-04-21 11:37:25 +00001709 Schedule.assign(MaxLoopDepth + 1, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001710
Tobias Grosser54839312015-04-21 11:37:25 +00001711 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001712 // traversing the region tree.
Tobias Grosser54839312015-04-21 11:37:25 +00001713 buildScop(tempScop, getRegion(), NestLoops, Schedule, LI, SD);
Tobias Grosser75805372011-04-29 06:27:02 +00001714
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001715 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001716 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001717 simplifyAssumedContext();
Tobias Grosser3f296192015-01-01 23:01:11 +00001718 dropConstantScheduleDims();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001719
Tobias Grosser75805372011-04-29 06:27:02 +00001720 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1721}
1722
1723Scop::~Scop() {
1724 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001725 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001726
1727 // Free the statements;
Tobias Grosser083d3d32014-06-28 08:59:45 +00001728 for (ScopStmt *Stmt : *this)
1729 delete Stmt;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001730
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001731 // Free the ScopArrayInfo objects.
Tobias Grossere71ed192015-05-06 10:05:20 +00001732 for (auto &ScopArrayInfoPair : arrays())
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001733 delete ScopArrayInfoPair.second;
1734
Johannes Doerfertb164c792014-09-18 11:17:17 +00001735 // Free the alias groups
1736 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1737 for (MinMaxAccessTy &MMA : *MinMaxAccesses) {
1738 isl_pw_multi_aff_free(MMA.first);
1739 isl_pw_multi_aff_free(MMA.second);
1740 }
1741 delete MinMaxAccesses;
1742 }
Tobias Grosser75805372011-04-29 06:27:02 +00001743}
1744
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001745const ScopArrayInfo *
1746Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
1747 const SmallVector<const SCEV *, 4> &Sizes) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001748 const ScopArrayInfo *&SAI = ScopArrayInfoMap[BasePtr];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001749 if (!SAI)
1750 SAI = new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001751 return SAI;
1752}
1753
1754const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr) {
1755 const SCEV *PtrSCEV = SE->getSCEV(BasePtr);
1756 const SCEVUnknown *PtrBaseSCEV =
1757 cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
1758 const ScopArrayInfo *SAI = ScopArrayInfoMap[PtrBaseSCEV->getValue()];
1759 assert(SAI && "No ScopArrayInfo available for this base pointer");
1760 return SAI;
1761}
1762
Tobias Grosser74394f02013-01-14 22:40:23 +00001763std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001764std::string Scop::getAssumedContextStr() const {
1765 return stringFromIslObj(AssumedContext);
1766}
Tobias Grosser75805372011-04-29 06:27:02 +00001767
1768std::string Scop::getNameStr() const {
1769 std::string ExitName, EntryName;
1770 raw_string_ostream ExitStr(ExitName);
1771 raw_string_ostream EntryStr(EntryName);
1772
Tobias Grosserf240b482014-01-09 10:42:15 +00001773 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001774 EntryStr.str();
1775
1776 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001777 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001778 ExitStr.str();
1779 } else
1780 ExitName = "FunctionExit";
1781
1782 return EntryName + "---" + ExitName;
1783}
1784
Tobias Grosser74394f02013-01-14 22:40:23 +00001785__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001786__isl_give isl_space *Scop::getParamSpace() const {
1787 return isl_set_get_space(this->Context);
1788}
1789
Tobias Grossere86109f2013-10-29 21:05:49 +00001790__isl_give isl_set *Scop::getAssumedContext() const {
1791 return isl_set_copy(AssumedContext);
1792}
1793
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001794void Scop::addAssumption(__isl_take isl_set *Set) {
1795 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001796 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001797}
1798
Tobias Grosser75805372011-04-29 06:27:02 +00001799void Scop::printContext(raw_ostream &OS) const {
1800 OS << "Context:\n";
1801
1802 if (!Context) {
1803 OS.indent(4) << "n/a\n\n";
1804 return;
1805 }
1806
1807 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001808
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001809 OS.indent(4) << "Assumed Context:\n";
1810 if (!AssumedContext) {
1811 OS.indent(4) << "n/a\n\n";
1812 return;
1813 }
1814
1815 OS.indent(4) << getAssumedContextStr() << "\n";
1816
Tobias Grosser083d3d32014-06-28 08:59:45 +00001817 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001818 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001819 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1820 }
Tobias Grosser75805372011-04-29 06:27:02 +00001821}
1822
Johannes Doerfertb164c792014-09-18 11:17:17 +00001823void Scop::printAliasAssumptions(raw_ostream &OS) const {
1824 OS.indent(4) << "Alias Groups (" << MinMaxAliasGroups.size() << "):\n";
1825 if (MinMaxAliasGroups.empty()) {
1826 OS.indent(8) << "n/a\n";
1827 return;
1828 }
1829 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1830 OS.indent(8) << "[[";
1831 for (MinMaxAccessTy &MinMacAccess : *MinMaxAccesses)
1832 OS << " <" << MinMacAccess.first << ", " << MinMacAccess.second << ">";
1833 OS << " ]]\n";
1834 }
1835}
1836
Tobias Grosser75805372011-04-29 06:27:02 +00001837void Scop::printStatements(raw_ostream &OS) const {
1838 OS << "Statements {\n";
1839
Tobias Grosser083d3d32014-06-28 08:59:45 +00001840 for (ScopStmt *Stmt : *this)
1841 OS.indent(4) << *Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001842
1843 OS.indent(4) << "}\n";
1844}
1845
Tobias Grosser75805372011-04-29 06:27:02 +00001846void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001847 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1848 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001849 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00001850 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001851 printContext(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001852 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001853 printStatements(OS.indent(4));
1854}
1855
1856void Scop::dump() const { print(dbgs()); }
1857
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001858isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001859
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001860__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001861 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001862
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001863 for (ScopStmt *Stmt : *this)
1864 Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001865
1866 return Domain;
1867}
1868
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001869__isl_give isl_union_map *Scop::getMustWrites() {
1870 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1871
1872 for (ScopStmt *Stmt : *this) {
1873 for (MemoryAccess *MA : *Stmt) {
1874 if (!MA->isMustWrite())
1875 continue;
1876
1877 isl_set *Domain = Stmt->getDomain();
1878 isl_map *AccessDomain = MA->getAccessRelation();
1879 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1880 Write = isl_union_map_add_map(Write, AccessDomain);
1881 }
1882 }
1883 return isl_union_map_coalesce(Write);
1884}
1885
1886__isl_give isl_union_map *Scop::getMayWrites() {
1887 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1888
1889 for (ScopStmt *Stmt : *this) {
1890 for (MemoryAccess *MA : *Stmt) {
1891 if (!MA->isMayWrite())
1892 continue;
1893
1894 isl_set *Domain = Stmt->getDomain();
1895 isl_map *AccessDomain = MA->getAccessRelation();
1896 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1897 Write = isl_union_map_add_map(Write, AccessDomain);
1898 }
1899 }
1900 return isl_union_map_coalesce(Write);
1901}
1902
Tobias Grosser37eb4222014-02-20 21:43:54 +00001903__isl_give isl_union_map *Scop::getWrites() {
1904 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1905
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001906 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001907 for (MemoryAccess *MA : *Stmt) {
1908 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001909 continue;
1910
1911 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001912 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001913 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1914 Write = isl_union_map_add_map(Write, AccessDomain);
1915 }
1916 }
1917 return isl_union_map_coalesce(Write);
1918}
1919
1920__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001921 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001922
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001923 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001924 for (MemoryAccess *MA : *Stmt) {
1925 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001926 continue;
1927
1928 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001929 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001930
1931 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1932 Read = isl_union_map_add_map(Read, AccessDomain);
1933 }
1934 }
1935 return isl_union_map_coalesce(Read);
1936}
1937
1938__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001939 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001940
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001941 for (ScopStmt *Stmt : *this)
Tobias Grosser54839312015-04-21 11:37:25 +00001942 Schedule = isl_union_map_add_map(Schedule, Stmt->getSchedule());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001943
Tobias Grosser37eb4222014-02-20 21:43:54 +00001944 return isl_union_map_coalesce(Schedule);
1945}
1946
1947bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1948 bool Changed = false;
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001949 for (ScopStmt *Stmt : *this) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00001950 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001951 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1952 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1953
1954 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1955 isl_union_set_free(StmtDomain);
1956 isl_union_set_free(NewStmtDomain);
1957 continue;
1958 }
1959
1960 Changed = true;
1961
1962 isl_union_set_free(StmtDomain);
1963 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1964
1965 if (isl_union_set_is_empty(NewStmtDomain)) {
1966 Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1967 isl_union_set_free(NewStmtDomain);
1968 } else
1969 Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1970 }
1971 isl_union_set_free(Domain);
1972 return Changed;
1973}
1974
Tobias Grosser75805372011-04-29 06:27:02 +00001975ScalarEvolution *Scop::getSE() const { return SE; }
1976
1977bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1978 if (tempScop.getAccessFunctions(BB))
1979 return false;
1980
1981 return true;
1982}
1983
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001984void Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
1985 const Region &CurRegion,
1986 SmallVectorImpl<Loop *> &NestLoops,
Tobias Grosser54839312015-04-21 11:37:25 +00001987 SmallVectorImpl<unsigned> &ScheduleVec) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001988 ScopStmt *Stmt;
1989
1990 if (BB) {
Tobias Grosser654af8f2015-04-21 11:42:01 +00001991 Stmt =
1992 new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001993 StmtMap[BB] = Stmt;
1994 } else {
1995 assert(R && "Either a basic block or a region is needed to "
1996 "create a new SCoP stmt.");
Tobias Grosser54839312015-04-21 11:37:25 +00001997 Stmt = new ScopStmt(*this, tempScop, CurRegion, *R, NestLoops, ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001998 for (BasicBlock *BB : R->blocks())
1999 StmtMap[BB] = Stmt;
2000 }
2001
2002 // Insert all statements into the statement map and the statement vector.
2003 Stmts.push_back(Stmt);
2004
Tobias Grosser54839312015-04-21 11:37:25 +00002005 // Increasing the Schedule function is OK for the moment, because
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002006 // we are using a depth first iterator and the program is well structured.
Tobias Grosser54839312015-04-21 11:37:25 +00002007 ++ScheduleVec[NestLoops.size()];
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002008}
2009
Tobias Grosser74394f02013-01-14 22:40:23 +00002010void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
2011 SmallVectorImpl<Loop *> &NestLoops,
Tobias Grosser54839312015-04-21 11:37:25 +00002012 SmallVectorImpl<unsigned> &ScheduleVec, LoopInfo &LI,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002013 ScopDetection &SD) {
2014 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion()))
2015 return addScopStmt(nullptr, const_cast<Region *>(&CurRegion), tempScop,
Tobias Grosser54839312015-04-21 11:37:25 +00002016 CurRegion, NestLoops, ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002017
Tobias Grosser75805372011-04-29 06:27:02 +00002018 Loop *L = castToLoop(CurRegion, LI);
2019
2020 if (L)
2021 NestLoops.push_back(L);
2022
2023 unsigned loopDepth = NestLoops.size();
Tobias Grosser54839312015-04-21 11:37:25 +00002024 assert(ScheduleVec.size() > loopDepth && "Schedule not big enough!");
Tobias Grosser75805372011-04-29 06:27:02 +00002025
2026 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00002027 E = CurRegion.element_end();
2028 I != E; ++I)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002029 if (I->isSubRegion()) {
Tobias Grosser654af8f2015-04-21 11:42:01 +00002030 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, ScheduleVec, LI,
2031 SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002032 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00002033 BasicBlock *BB = I->getNodeAs<BasicBlock>();
2034
2035 if (isTrivialBB(BB, tempScop))
2036 continue;
2037
Tobias Grosser54839312015-04-21 11:37:25 +00002038 addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops, ScheduleVec);
Tobias Grosser75805372011-04-29 06:27:02 +00002039 }
2040
2041 if (!L)
2042 return;
2043
2044 // Exiting a loop region.
Tobias Grosser54839312015-04-21 11:37:25 +00002045 ScheduleVec[loopDepth] = 0;
Tobias Grosser75805372011-04-29 06:27:02 +00002046 NestLoops.pop_back();
Tobias Grosser54839312015-04-21 11:37:25 +00002047 ++ScheduleVec[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00002048}
2049
Johannes Doerfert7c494212014-10-31 23:13:39 +00002050ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
2051 const auto &StmtMapIt = StmtMap.find(BB);
2052 if (StmtMapIt == StmtMap.end())
2053 return nullptr;
2054 return StmtMapIt->second;
2055}
2056
Tobias Grosser75805372011-04-29 06:27:02 +00002057//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00002058ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
2059 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002060 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002061}
2062
2063ScopInfo::~ScopInfo() {
2064 clear();
2065 isl_ctx_free(ctx);
2066}
2067
Tobias Grosser75805372011-04-29 06:27:02 +00002068void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002069 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002070 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00002071 AU.addRequired<ScalarEvolution>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002072 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002073 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002074 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00002075 AU.setPreservesAll();
2076}
2077
2078bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002079 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002080 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002081 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002082 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
2083
2084 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
2085
2086 // This region is no Scop.
2087 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002088 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002089 return false;
2090 }
2091
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002092 scop = new Scop(*tempScop, LI, SE, SD, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002093
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002094 if (!PollyUseRuntimeAliasChecks) {
2095 // Statistics.
2096 ++ScopFound;
2097 if (scop->getMaxLoopDepth() > 0)
2098 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002099 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002100 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002101
Johannes Doerfert9143d672014-09-27 11:02:39 +00002102 // If a problem occurs while building the alias groups we need to delete
2103 // this SCoP and pretend it wasn't valid in the first place.
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002104 if (scop->buildAliasGroups(AA)) {
2105 // Statistics.
2106 ++ScopFound;
2107 if (scop->getMaxLoopDepth() > 0)
2108 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002109 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002110 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002111
2112 DEBUG(dbgs()
2113 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002114 << " could not be created as the number of parameters involved is too "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002115 "high. The SCoP will be "
2116 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002117 "maximal number of parameters but be advised that the compile time "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002118 "might increase exponentially.\n\n");
2119
2120 delete scop;
2121 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002122 return false;
2123}
2124
2125char ScopInfo::ID = 0;
2126
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002127Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2128
Tobias Grosser73600b82011-10-08 00:30:40 +00002129INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2130 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002131 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002132INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002133INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002134INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002135INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002136INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002137INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00002138INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2139 "Polly - Create polyhedral description of Scops", false,
2140 false)