blob: 3d7428bc406a842d0f397cbc4c9c9d54783af395 [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//
15// This represantation is shared among several tools in the polyhedral
16// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Sebastian Pop27c10c62013-03-22 22:07:43 +000020#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000022#include "polly/ScopInfo.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000023#include "polly/Options.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000027#include "polly/TempScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +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"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/Analysis/LoopInfo.h"
32#include "llvm/Analysis/RegionIterator.h"
33#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000034#include "llvm/Support/Debug.h"
35
36#include "isl/constraint.h"
37#include "isl/set.h"
38#include "isl/map.h"
Tobias Grosser37eb4222014-02-20 21:43:54 +000039#include "isl/union_map.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000040#include "isl/aff.h"
41#include "isl/printer.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000042#include "isl/local_space.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000043#include "isl/options.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000044#include "isl/val.h"
Chandler Carruth95fef942014-04-22 03:30:19 +000045
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
Tobias Grosser0695ee42013-09-17 03:30:31 +000066/// Translate a 'const SCEV *' expression in an isl_pw_aff.
Tobias Grosserabfbe632013-02-05 12:09:06 +000067struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
Tobias Grosser0695ee42013-09-17 03:30:31 +000068public:
Tobias Grosser0695ee42013-09-17 03:30:31 +000069 /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
70 ///
71 /// @param Stmt The location at which the scalar evolution expression
72 /// is evaluated.
73 /// @param Expr The expression that is translated.
74 static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
75
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000076private:
Tobias Grosser3cc99742012-06-06 16:33:15 +000077 isl_ctx *Ctx;
Tobias Grosserf5338802011-10-06 00:03:35 +000078 int NbLoopSpaces;
Tobias Grosser3cc99742012-06-06 16:33:15 +000079 const Scop *S;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000080
Tobias Grosser0695ee42013-09-17 03:30:31 +000081 SCEVAffinator(const ScopStmt *Stmt);
82 int getLoopDepth(const Loop *L);
Tobias Grosser60b54f12011-11-08 15:41:28 +000083
Tobias Grosser0695ee42013-09-17 03:30:31 +000084 __isl_give isl_pw_aff *visit(const SCEV *Expr);
85 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
86 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
87 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
88 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
89 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
90 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
91 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
92 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
93 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
94 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
95 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
Tobias Grosser60b54f12011-11-08 15:41:28 +000096
Tobias Grosser0695ee42013-09-17 03:30:31 +000097 friend struct SCEVVisitor<SCEVAffinator, isl_pw_aff *>;
98};
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000099
Tobias Grosser0695ee42013-09-17 03:30:31 +0000100SCEVAffinator::SCEVAffinator(const ScopStmt *Stmt)
101 : Ctx(Stmt->getIslCtx()), NbLoopSpaces(Stmt->getNumIterators()),
102 S(Stmt->getParent()) {}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000103
Tobias Grosser0695ee42013-09-17 03:30:31 +0000104__isl_give isl_pw_aff *SCEVAffinator::getPwAff(ScopStmt *Stmt,
105 const SCEV *Scev) {
106 Scop *S = Stmt->getParent();
107 const Region *Reg = &S->getRegion();
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000108
Tobias Grosser0695ee42013-09-17 03:30:31 +0000109 S->addParams(getParamsInAffineExpr(Reg, Scev, *S->getSE()));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000110
Tobias Grosser0695ee42013-09-17 03:30:31 +0000111 SCEVAffinator Affinator(Stmt);
112 return Affinator.visit(Scev);
113}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000114
Tobias Grosser0695ee42013-09-17 03:30:31 +0000115__isl_give isl_pw_aff *SCEVAffinator::visit(const SCEV *Expr) {
116 // In case the scev is a valid parameter, we do not further analyze this
117 // expression, but create a new parameter in the isl_pw_aff. This allows us
118 // to treat subexpressions that we cannot translate into an piecewise affine
119 // expression, as constant parameters of the piecewise affine expression.
120 if (isl_id *Id = S->getIdForParam(Expr)) {
121 isl_space *Space = isl_space_set_alloc(Ctx, 1, NbLoopSpaces);
122 Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000123
Tobias Grosser0695ee42013-09-17 03:30:31 +0000124 isl_set *Domain = isl_set_universe(isl_space_copy(Space));
125 isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
126 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000127
128 return isl_pw_aff_alloc(Domain, Affine);
129 }
130
Tobias Grosser0695ee42013-09-17 03:30:31 +0000131 return SCEVVisitor<SCEVAffinator, isl_pw_aff *>::visit(Expr);
132}
133
Tobias Grosser0d170132013-10-03 13:09:19 +0000134__isl_give isl_pw_aff *SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
Tobias Grosser0695ee42013-09-17 03:30:31 +0000135 ConstantInt *Value = Expr->getValue();
136 isl_val *v;
137
138 // LLVM does not define if an integer value is interpreted as a signed or
139 // unsigned value. Hence, without further information, it is unknown how
140 // this value needs to be converted to GMP. At the moment, we only support
141 // signed operations. So we just interpret it as signed. Later, there are
142 // two options:
143 //
144 // 1. We always interpret any value as signed and convert the values on
145 // demand.
146 // 2. We pass down the signedness of the calculation and use it to interpret
147 // this constant correctly.
148 v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
149
150 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
151 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(Space));
152 isl_aff *Affine = isl_aff_zero_on_domain(ls);
153 isl_set *Domain = isl_set_universe(Space);
154
155 Affine = isl_aff_add_constant_val(Affine, v);
156
157 return isl_pw_aff_alloc(Domain, Affine);
158}
159
160__isl_give isl_pw_aff *
161SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
162 llvm_unreachable("SCEVTruncateExpr not yet supported");
163}
164
165__isl_give isl_pw_aff *
166SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
167 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
168}
169
170__isl_give isl_pw_aff *
171SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
172 // Assuming the value is signed, a sign extension is basically a noop.
173 // TODO: Reconsider this as soon as we support unsigned values.
174 return visit(Expr->getOperand());
175}
176
177__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
178 isl_pw_aff *Sum = visit(Expr->getOperand(0));
179
180 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
181 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
182 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000183 }
184
Tobias Grosser0695ee42013-09-17 03:30:31 +0000185 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000186
Tobias Grosser0695ee42013-09-17 03:30:31 +0000187 return Sum;
188}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000189
Tobias Grosser0695ee42013-09-17 03:30:31 +0000190__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
191 isl_pw_aff *Product = visit(Expr->getOperand(0));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000192
Tobias Grosser0695ee42013-09-17 03:30:31 +0000193 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
194 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
195
196 if (!isl_pw_aff_is_cst(Product) && !isl_pw_aff_is_cst(NextOperand)) {
197 isl_pw_aff_free(Product);
198 isl_pw_aff_free(NextOperand);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000199 return nullptr;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000200 }
201
Tobias Grosser0695ee42013-09-17 03:30:31 +0000202 Product = isl_pw_aff_mul(Product, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000203 }
204
Tobias Grosser0695ee42013-09-17 03:30:31 +0000205 // TODO: Check for NSW and NUW.
206 return Product;
207}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000208
Tobias Grosser0695ee42013-09-17 03:30:31 +0000209__isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
210 llvm_unreachable("SCEVUDivExpr not yet supported");
211}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000212
Tobias Grosser0695ee42013-09-17 03:30:31 +0000213__isl_give isl_pw_aff *
214SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
215 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000216
Tobias Grosser0695ee42013-09-17 03:30:31 +0000217 // Directly generate isl_pw_aff for Expr if 'start' is zero.
218 if (Expr->getStart()->isZero()) {
219 assert(S->getRegion().contains(Expr->getLoop()) &&
220 "Scop does not contain the loop referenced in this AddRec");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000221
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000222 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser0695ee42013-09-17 03:30:31 +0000223 isl_pw_aff *Step = visit(Expr->getOperand(1));
224 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
225 isl_local_space *LocalSpace = isl_local_space_from_space(Space);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000226
Tobias Grosser0695ee42013-09-17 03:30:31 +0000227 int loopDimension = getLoopDepth(Expr->getLoop());
228
229 isl_aff *LAff = isl_aff_set_coefficient_si(
230 isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
231 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
232
233 // TODO: Do we need to check for NSW and NUW?
234 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000235 }
236
Tobias Grosser0695ee42013-09-17 03:30:31 +0000237 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
238 // if 'start' is not zero.
239 ScalarEvolution &SE = *S->getSE();
240 const SCEV *ZeroStartExpr = SE.getAddRecExpr(
241 SE.getConstant(Expr->getStart()->getType(), 0),
242 Expr->getStepRecurrence(SE), Expr->getLoop(), SCEV::FlagAnyWrap);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000243
Tobias Grosser0695ee42013-09-17 03:30:31 +0000244 isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
245 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000246
Tobias Grosser0695ee42013-09-17 03:30:31 +0000247 return isl_pw_aff_add(ZeroStartResult, Start);
248}
249
250__isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
251 isl_pw_aff *Max = visit(Expr->getOperand(0));
252
253 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
254 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
255 Max = isl_pw_aff_max(Max, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000256 }
257
Tobias Grosser0695ee42013-09-17 03:30:31 +0000258 return Max;
259}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000260
Tobias Grosser0695ee42013-09-17 03:30:31 +0000261__isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
262 llvm_unreachable("SCEVUMaxExpr not yet supported");
263}
264
265__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
Tobias Grosserf4daf342014-08-16 09:08:55 +0000266 llvm_unreachable("Unknowns are always parameters");
Tobias Grosser0695ee42013-09-17 03:30:31 +0000267}
268
269int SCEVAffinator::getLoopDepth(const Loop *L) {
270 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
271 assert(outerLoop && "Scop does not contain this loop");
272 return L->getLoopDepth() - outerLoop->getLoopDepth();
273}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000274
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000275const std::string
276MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
277 switch (RT) {
278 case MemoryAccess::RT_NONE:
279 llvm_unreachable("Requested a reduction operator string for a memory "
280 "access which isn't a reduction");
281 case MemoryAccess::RT_ADD:
282 return "+";
283 case MemoryAccess::RT_MUL:
284 return "*";
285 case MemoryAccess::RT_BOR:
286 return "|";
287 case MemoryAccess::RT_BXOR:
288 return "^";
289 case MemoryAccess::RT_BAND:
290 return "&";
291 }
292 llvm_unreachable("Unknown reduction type");
293 return "";
294}
295
Johannes Doerfertf6183392014-07-01 20:52:51 +0000296/// @brief Return the reduction type for a given binary operator
297static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
298 const Instruction *Load) {
299 if (!BinOp)
300 return MemoryAccess::RT_NONE;
301 switch (BinOp->getOpcode()) {
302 case Instruction::FAdd:
303 if (!BinOp->hasUnsafeAlgebra())
304 return MemoryAccess::RT_NONE;
305 // Fall through
306 case Instruction::Add:
307 return MemoryAccess::RT_ADD;
308 case Instruction::Or:
309 return MemoryAccess::RT_BOR;
310 case Instruction::Xor:
311 return MemoryAccess::RT_BXOR;
312 case Instruction::And:
313 return MemoryAccess::RT_BAND;
314 case Instruction::FMul:
315 if (!BinOp->hasUnsafeAlgebra())
316 return MemoryAccess::RT_NONE;
317 // Fall through
318 case Instruction::Mul:
319 if (DisableMultiplicativeReductions)
320 return MemoryAccess::RT_NONE;
321 return MemoryAccess::RT_MUL;
322 default:
323 return MemoryAccess::RT_NONE;
324 }
325}
Tobias Grosser75805372011-04-29 06:27:02 +0000326//===----------------------------------------------------------------------===//
327
328MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000329 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000330 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000331}
332
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000333static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
334 switch (Access.getType()) {
335 case IRAccess::READ:
336 return MemoryAccess::READ;
337 case IRAccess::MUST_WRITE:
338 return MemoryAccess::MUST_WRITE;
339 case IRAccess::MAY_WRITE:
340 return MemoryAccess::MAY_WRITE;
341 }
342 llvm_unreachable("Unknown IRAccess type!");
343}
344
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000345isl_id *MemoryAccess::getArrayId() const {
346 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
347}
348
Tobias Grosser5d453812011-10-06 00:04:11 +0000349isl_map *MemoryAccess::getAccessRelation() const {
350 return isl_map_copy(AccessRelation);
351}
352
353std::string MemoryAccess::getAccessRelationStr() const {
354 return stringFromIslObj(AccessRelation);
355}
356
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000357__isl_give isl_space *MemoryAccess::getAccessRelationSpace() const {
358 return isl_map_get_space(AccessRelation);
359}
360
Tobias Grosser5d453812011-10-06 00:04:11 +0000361isl_map *MemoryAccess::getNewAccessRelation() const {
362 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000363}
364
365isl_basic_map *MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000366 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000367 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000368
Tobias Grosser084d8f72012-05-29 09:29:44 +0000369 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000370 isl_basic_set_universe(Statement->getDomainSpace()),
371 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000372}
373
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000374// Formalize no out-of-bound access assumption
375//
376// When delinearizing array accesses we optimistically assume that the
377// delinearized accesses do not access out of bound locations (the subscript
378// expression of each array evaluates for each statement instance that is
379// executed to a value that is larger than zero and strictly smaller than the
380// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000381// dimension for which we do not need to assume any upper bound. At this point
382// we formalize this assumption to ensure that at code generation time the
383// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000384//
385// To find the set of constraints necessary to avoid out of bound accesses, we
386// first build the set of data locations that are not within array bounds. We
387// then apply the reverse access relation to obtain the set of iterations that
388// may contain invalid accesses and reduce this set of iterations to the ones
389// that are actually executed by intersecting them with the domain of the
390// statement. If we now project out all loop dimensions, we obtain a set of
391// parameters that may cause statement instances to be executed that may
392// possibly yield out of bound memory accesses. The complement of these
393// constraints is the set of constraints that needs to be assumed to ensure such
394// statement instances are never executed.
395void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
396 isl_space *Space = isl_space_range(getAccessRelationSpace());
397 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000398 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000399 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
400 isl_pw_aff *Var =
401 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
402 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
403
404 isl_set *DimOutside;
405
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000406 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
407 isl_pw_aff *SizeE = SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000408
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000409 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
410 Statement->getNumIterators());
411 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
412 isl_space_dim(Space, isl_dim_set));
413 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
414 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000415
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000416 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000417
418 Outside = isl_set_union(Outside, DimOutside);
419 }
420
421 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
422 Outside = isl_set_intersect(Outside, Statement->getDomain());
423 Outside = isl_set_params(Outside);
424 Outside = isl_set_complement(Outside);
425 Statement->getParent()->addAssumption(Outside);
426 isl_space_free(Space);
427}
428
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000429MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosserabfbe632013-02-05 12:09:06 +0000430 ScopStmt *Statement)
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000431 : Type(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
432 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000433
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000434 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000435 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000436 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000437 isl_id *BaseAddrId = isl_id_alloc(Ctx, getBaseName().c_str(), nullptr);
Tobias Grosser5683df42011-11-09 22:34:34 +0000438
Tobias Grossera1879642011-12-20 10:43:14 +0000439 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000440 // We overapproximate non-affine accesses with a possible access to the
441 // whole array. For read accesses it does not make a difference, if an
442 // access must or may happen. However, for write accesses it is important to
443 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000444 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000445 AccessRelation =
446 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000447 return;
448 }
449
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000450 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000451 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000452
Tobias Grosser79baa212014-04-10 08:38:02 +0000453 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000454 isl_pw_aff *Affine =
455 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000456
Sebastian Pop422e33f2014-06-03 18:16:31 +0000457 if (Size == 1) {
458 // For the non delinearized arrays, divide the access function of the last
459 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000460 //
461 // A stride one array access in C expressed as A[i] is expressed in
462 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
463 // two subsequent values of 'i' index two values that are stored next to
464 // each other in memory. By this division we make this characteristic
465 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000466 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000467 Affine = isl_pw_aff_scale_down_val(Affine, v);
468 }
469
470 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
471
Tobias Grosser79baa212014-04-10 08:38:02 +0000472 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000473 }
474
Tobias Grosser79baa212014-04-10 08:38:02 +0000475 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000476 AccessRelation = isl_map_set_tuple_id(
477 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000478 AccessRelation =
479 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
480
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000481 assumeNoOutOfBound(Access);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000482 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000483}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000484
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000485void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000486 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000487 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000488}
489
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000490const std::string MemoryAccess::getReductionOperatorStr() const {
491 return MemoryAccess::getReductionOperatorStr(getReductionType());
492}
493
Johannes Doerfertf6183392014-07-01 20:52:51 +0000494raw_ostream &polly::operator<<(raw_ostream &OS,
495 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000496 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000497 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000498 else
499 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000500 return OS;
501}
502
Tobias Grosser75805372011-04-29 06:27:02 +0000503void MemoryAccess::print(raw_ostream &OS) const {
Tobias Grosser4f967492013-06-23 05:21:18 +0000504 switch (Type) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000505 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000506 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000507 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000508 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000509 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000510 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000511 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000512 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000513 break;
514 }
Johannes Doerfertf6183392014-07-01 20:52:51 +0000515 OS << "[Reduction Type: " << getReductionType() << "]\n";
Tobias Grosser5d453812011-10-06 00:04:11 +0000516 OS.indent(16) << getAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000517}
518
Tobias Grosser74394f02013-01-14 22:40:23 +0000519void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000520
521// Create a map in the size of the provided set domain, that maps from the
522// one element of the provided set domain to another element of the provided
523// set domain.
524// The mapping is limited to all points that are equal in all but the last
525// dimension and for which the last dimension of the input is strict smaller
526// than the last dimension of the output.
527//
528// getEqualAndLarger(set[i0, i1, ..., iX]):
529//
530// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
531// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
532//
Tobias Grosserf5338802011-10-06 00:03:35 +0000533static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000534 isl_space *Space = isl_space_map_from_set(setDomain);
535 isl_map *Map = isl_map_universe(isl_space_copy(Space));
536 isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000537 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000538
539 // Set all but the last dimension to be equal for the input and output
540 //
541 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
542 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000543 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000544 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000545
546 // Set the last dimension of the input to be strict smaller than the
547 // last dimension of the output.
548 //
549 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
550 //
Tobias Grosseredab1352013-06-21 06:41:31 +0000551 isl_val *v;
552 isl_ctx *Ctx = isl_map_get_ctx(Map);
Tobias Grosserf5338802011-10-06 00:03:35 +0000553 isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
Tobias Grosseredab1352013-06-21 06:41:31 +0000554 v = isl_val_int_from_si(Ctx, -1);
555 c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
556 v = isl_val_int_from_si(Ctx, 1);
557 c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
558 v = isl_val_int_from_si(Ctx, -1);
559 c = isl_constraint_set_constant_val(c, v);
Tobias Grosser75805372011-04-29 06:27:02 +0000560
Tobias Grosserc327932c2012-02-01 14:23:36 +0000561 Map = isl_map_add_constraint(Map, c);
Tobias Grosser75805372011-04-29 06:27:02 +0000562
Tobias Grosser23b36662011-10-17 08:32:36 +0000563 isl_local_space_free(MapLocalSpace);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000564 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000565}
566
Sebastian Popa00a0292012-12-18 07:46:06 +0000567isl_set *MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000568 isl_map *S = const_cast<isl_map *>(Schedule);
Sebastian Popa00a0292012-12-18 07:46:06 +0000569 isl_map *AccessRelation = getAccessRelation();
570 isl_space *Space = isl_space_range(isl_map_get_space(S));
571 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000572
Sebastian Popa00a0292012-12-18 07:46:06 +0000573 S = isl_map_reverse(S);
574 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000575
Sebastian Popa00a0292012-12-18 07:46:06 +0000576 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
577 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
578 NextScatt = isl_map_apply_domain(NextScatt, S);
579 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000580
Sebastian Popa00a0292012-12-18 07:46:06 +0000581 isl_set *Deltas = isl_map_deltas(NextScatt);
582 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000583}
584
Sebastian Popa00a0292012-12-18 07:46:06 +0000585bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000586 int StrideWidth) const {
587 isl_set *Stride, *StrideX;
588 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000589
Sebastian Popa00a0292012-12-18 07:46:06 +0000590 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000591 StrideX = isl_set_universe(isl_set_get_space(Stride));
592 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
593 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000594
Tobias Grosser28dd4862012-01-24 16:42:16 +0000595 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000596 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000597
Tobias Grosser28dd4862012-01-24 16:42:16 +0000598 return IsStrideX;
599}
600
Sebastian Popa00a0292012-12-18 07:46:06 +0000601bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
602 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000603}
604
Tobias Grosser79baa212014-04-10 08:38:02 +0000605bool MemoryAccess::isScalar() const {
606 return isl_map_n_out(AccessRelation) == 0;
607}
608
Sebastian Popa00a0292012-12-18 07:46:06 +0000609bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
610 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000611}
612
Tobias Grosser5d453812011-10-06 00:04:11 +0000613void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000614 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000615 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000616}
Tobias Grosser75805372011-04-29 06:27:02 +0000617
618//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000619
Tobias Grosser74394f02013-01-14 22:40:23 +0000620isl_map *ScopStmt::getScattering() const { return isl_map_copy(Scattering); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000621
Tobias Grosser37eb4222014-02-20 21:43:54 +0000622void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
623 assert(isl_set_is_subset(NewDomain, Domain) &&
624 "New domain is not a subset of old domain!");
625 isl_set_free(Domain);
626 Domain = NewDomain;
627 Scattering = isl_map_intersect_domain(Scattering, isl_set_copy(Domain));
628}
629
Tobias Grossercf3942d2011-10-06 00:04:05 +0000630void ScopStmt::setScattering(isl_map *NewScattering) {
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000631 assert(NewScattering && "New scattering is nullptr");
Tobias Grosserb76f38532011-08-20 11:11:25 +0000632 isl_map_free(Scattering);
Tobias Grossercf3942d2011-10-06 00:04:05 +0000633 Scattering = NewScattering;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000634}
635
Tobias Grosser75805372011-04-29 06:27:02 +0000636void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000637 unsigned NbIterators = getNumIterators();
638 unsigned NbScatteringDims = Parent.getMaxLoopDepth() * 2 + 1;
639
Tobias Grosser084d8f72012-05-29 09:29:44 +0000640 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScatteringDims);
Tobias Grosserf5338802011-10-06 00:03:35 +0000641 Space = isl_space_set_tuple_name(Space, isl_dim_out, "scattering");
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000642
Tobias Grosser084d8f72012-05-29 09:29:44 +0000643 Scattering = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
644 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000645
646 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000647 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosserabfbe632013-02-05 12:09:06 +0000648 Scattering =
649 isl_map_equate(Scattering, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000650
651 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000652 for (unsigned i = 0; i < NbIterators + 1; ++i)
653 Scattering = isl_map_fix_si(Scattering, isl_dim_out, 2 * i, Scatter[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000654
655 // Fill scattering dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000656 for (unsigned i = 2 * NbIterators + 1; i < NbScatteringDims; ++i)
657 Scattering = isl_map_fix_si(Scattering, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000658
Tobias Grosser37487052011-10-06 00:03:42 +0000659 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000660}
661
662void ScopStmt::buildAccesses(TempScop &tempScop, const Region &CurRegion) {
Tobias Grosser083d3d32014-06-28 08:59:45 +0000663 for (auto &&Access : *tempScop.getAccessFunctions(BB)) {
664 MemAccs.push_back(new MemoryAccess(Access.first, Access.second, this));
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000665
666 // We do not track locations for scalar memory accesses at the moment.
667 //
668 // We do not have a use for this information at the moment. If we need this
669 // at some point, the "instruction -> access" mapping needs to be enhanced
670 // as a single instruction could then possibly perform multiple accesses.
Tobias Grosser083d3d32014-06-28 08:59:45 +0000671 if (!Access.first.isScalar()) {
672 assert(!InstructionToAccess.count(Access.second) &&
Tobias Grosser3fc91542014-02-20 21:43:45 +0000673 "Unexpected 1-to-N mapping on instruction to access map!");
Tobias Grosser083d3d32014-06-28 08:59:45 +0000674 InstructionToAccess[Access.second] = MemAccs.back();
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000675 }
Tobias Grosser75805372011-04-29 06:27:02 +0000676 }
677}
678
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000679void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000680 for (MemoryAccess *MA : *this)
681 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000682
683 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
684 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
685}
686
Tobias Grosser65b00582011-11-08 15:41:19 +0000687__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000688 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
689 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000690
Tobias Grosserd2795d02011-08-18 07:51:40 +0000691 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000692 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000693 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000694 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000695 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000696 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000697 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000698 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000699 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000700 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000701 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000702 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000703 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000704 case ICmpInst::ICMP_ULT:
705 case ICmpInst::ICMP_UGT:
706 case ICmpInst::ICMP_ULE:
Tobias Grosser75805372011-04-29 06:27:02 +0000707 case ICmpInst::ICMP_UGE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000708 llvm_unreachable("Unsigned comparisons not yet supported");
Tobias Grosser75805372011-04-29 06:27:02 +0000709 default:
710 llvm_unreachable("Non integer predicate not supported");
711 }
Tobias Grosser75805372011-04-29 06:27:02 +0000712}
713
Tobias Grossere19661e2011-10-07 08:46:57 +0000714__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000715 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000716 isl_space *Space;
717 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000718
Tobias Grossere19661e2011-10-07 08:46:57 +0000719 Space = isl_set_get_space(Domain);
720 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000721
Tobias Grosser75805372011-04-29 06:27:02 +0000722 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000723 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000724 isl_pw_aff *IV =
725 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000726
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000727 // 0 <= IV.
728 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
729 Domain = isl_set_intersect(Domain, LowerBound);
730
731 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000732 const Loop *L = getLoopForDimension(i);
Tobias Grosser1179afa2011-11-02 21:37:51 +0000733 const SCEV *LatchExecutions = tempScop.getLoopBound(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000734 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
735 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000736 Domain = isl_set_intersect(Domain, UpperBoundSet);
737 }
738
Tobias Grosserf5338802011-10-06 00:03:35 +0000739 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000740 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000741}
742
Tobias Grossere602a072013-05-07 07:30:56 +0000743__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
744 TempScop &tempScop,
745 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000746 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000747 *CurrentRegion = &CurRegion;
Tobias Grossere19661e2011-10-07 08:46:57 +0000748 const BasicBlock *BranchingBB = BB;
Tobias Grosser75805372011-04-29 06:27:02 +0000749
Tobias Grosser75805372011-04-29 06:27:02 +0000750 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000751 if (BranchingBB != CurrentRegion->getEntry()) {
752 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000753 for (const auto &C : *Condition) {
754 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000755 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000756 }
757 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000758 BranchingBB = CurrentRegion->getEntry();
759 CurrentRegion = CurrentRegion->getParent();
760 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000761
Tobias Grossere19661e2011-10-07 08:46:57 +0000762 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000763}
764
Tobias Grossere602a072013-05-07 07:30:56 +0000765__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
766 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000767 isl_space *Space;
768 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000769 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000770
771 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
772
Tobias Grosser084d8f72012-05-29 09:29:44 +0000773 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
774
Tobias Grossere19661e2011-10-07 08:46:57 +0000775 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000776 Domain = addLoopBoundsToDomain(Domain, tempScop);
777 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000778 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000779
780 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000781}
782
Tobias Grosser74394f02013-01-14 22:40:23 +0000783ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +0000784 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser75805372011-04-29 06:27:02 +0000785 SmallVectorImpl<unsigned> &Scatter)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000786 : Parent(parent), BB(&bb), IVS(Nest.size()), NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000787 // Setup the induction variables.
Sebastian Pop860e0212013-02-15 21:26:44 +0000788 for (unsigned i = 0, e = Nest.size(); i < e; ++i) {
Sebastian Pop27c10c62013-03-22 22:07:43 +0000789 if (!SCEVCodegen) {
790 PHINode *PN = Nest[i]->getCanonicalInductionVariable();
791 assert(PN && "Non canonical IV in Scop!");
Tobias Grosser826b2af2013-03-21 16:14:50 +0000792 IVS[i] = PN;
Sebastian Pop27c10c62013-03-22 22:07:43 +0000793 }
Sebastian Pop860e0212013-02-15 21:26:44 +0000794 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000795 }
796
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000797 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +0000798
Tobias Grossere19661e2011-10-07 08:46:57 +0000799 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000800 buildScattering(Scatter);
801 buildAccesses(tempScop, CurRegion);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000802 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000803}
804
Johannes Doerferte58a0122014-06-27 20:31:28 +0000805/// @brief Collect loads which might form a reduction chain with @p StoreMA
806///
807/// Check if the stored value for @p StoreMA is a binary operator with one or
808/// two loads as operands. If the binary operand is commutative & associative,
809/// used only once (by @p StoreMA) and its load operands are also used only
810/// once, we have found a possible reduction chain. It starts at an operand
811/// load and includes the binary operator and @p StoreMA.
812///
813/// Note: We allow only one use to ensure the load and binary operator cannot
814/// escape this block or into any other store except @p StoreMA.
815void ScopStmt::collectCandiateReductionLoads(
816 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
817 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
818 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000819 return;
820
821 // Skip if there is not one binary operator between the load and the store
822 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +0000823 if (!BinOp)
824 return;
825
826 // Skip if the binary operators has multiple uses
827 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000828 return;
829
830 // Skip if the opcode of the binary operator is not commutative/associative
831 if (!BinOp->isCommutative() || !BinOp->isAssociative())
832 return;
833
Johannes Doerfert9890a052014-07-01 00:32:29 +0000834 // Skip if the binary operator is outside the current SCoP
835 if (BinOp->getParent() != Store->getParent())
836 return;
837
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000838 // Skip if it is a multiplicative reduction and we disabled them
839 if (DisableMultiplicativeReductions &&
840 (BinOp->getOpcode() == Instruction::Mul ||
841 BinOp->getOpcode() == Instruction::FMul))
842 return;
843
Johannes Doerferte58a0122014-06-27 20:31:28 +0000844 // Check the binary operator operands for a candidate load
845 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
846 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
847 if (!PossibleLoad0 && !PossibleLoad1)
848 return;
849
850 // A load is only a candidate if it cannot escape (thus has only this use)
851 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000852 if (PossibleLoad0->getParent() == Store->getParent())
853 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000854 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000855 if (PossibleLoad1->getParent() == Store->getParent())
856 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000857}
858
859/// @brief Check for reductions in this ScopStmt
860///
861/// Iterate over all store memory accesses and check for valid binary reduction
862/// like chains. For all candidates we check if they have the same base address
863/// and there are no other accesses which overlap with them. The base address
864/// check rules out impossible reductions candidates early. The overlap check,
865/// together with the "only one user" check in collectCandiateReductionLoads,
866/// guarantees that none of the intermediate results will escape during
867/// execution of the loop nest. We basically check here that no other memory
868/// access can access the same memory as the potential reduction.
869void ScopStmt::checkForReductions() {
870 SmallVector<MemoryAccess *, 2> Loads;
871 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
872
873 // First collect candidate load-store reduction chains by iterating over all
874 // stores and collecting possible reduction loads.
875 for (MemoryAccess *StoreMA : MemAccs) {
876 if (StoreMA->isRead())
877 continue;
878
879 Loads.clear();
880 collectCandiateReductionLoads(StoreMA, Loads);
881 for (MemoryAccess *LoadMA : Loads)
882 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
883 }
884
885 // Then check each possible candidate pair.
886 for (const auto &CandidatePair : Candidates) {
887 bool Valid = true;
888 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
889 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
890
891 // Skip those with obviously unequal base addresses.
892 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
893 isl_map_free(LoadAccs);
894 isl_map_free(StoreAccs);
895 continue;
896 }
897
898 // And check if the remaining for overlap with other memory accesses.
899 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
900 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
901 isl_set *AllAccs = isl_map_range(AllAccsRel);
902
903 for (MemoryAccess *MA : MemAccs) {
904 if (MA == CandidatePair.first || MA == CandidatePair.second)
905 continue;
906
907 isl_map *AccRel =
908 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
909 isl_set *Accs = isl_map_range(AccRel);
910
911 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
912 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
913 Valid = Valid && isl_set_is_empty(OverlapAccs);
914 isl_set_free(OverlapAccs);
915 }
916 }
917
918 isl_set_free(AllAccs);
919 if (!Valid)
920 continue;
921
Johannes Doerfertf6183392014-07-01 20:52:51 +0000922 const LoadInst *Load =
923 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
924 MemoryAccess::ReductionType RT =
925 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
926
Johannes Doerferte58a0122014-06-27 20:31:28 +0000927 // If no overlapping access was found we mark the load and store as
928 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000929 CandidatePair.first->markAsReductionLike(RT);
930 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000931 }
Tobias Grosser75805372011-04-29 06:27:02 +0000932}
933
Tobias Grosser74394f02013-01-14 22:40:23 +0000934std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +0000935
936std::string ScopStmt::getScatteringStr() const {
Tobias Grossercf3942d2011-10-06 00:04:05 +0000937 return stringFromIslObj(Scattering);
Tobias Grosser75805372011-04-29 06:27:02 +0000938}
939
Tobias Grosser74394f02013-01-14 22:40:23 +0000940unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +0000941
942unsigned ScopStmt::getNumIterators() const {
943 // The final read has one dimension with one element.
944 if (!BB)
945 return 1;
946
Sebastian Pop860e0212013-02-15 21:26:44 +0000947 return NestLoops.size();
Tobias Grosser75805372011-04-29 06:27:02 +0000948}
949
950unsigned ScopStmt::getNumScattering() const {
951 return isl_map_dim(Scattering, isl_dim_out);
952}
953
954const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
955
Tobias Grosserabfbe632013-02-05 12:09:06 +0000956const PHINode *
957ScopStmt::getInductionVariableForDimension(unsigned Dimension) const {
Sebastian Popf30d3b22013-02-15 21:26:48 +0000958 return IVS[Dimension];
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000959}
960
961const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +0000962 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +0000963}
964
Tobias Grosser74394f02013-01-14 22:40:23 +0000965isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +0000966
Tobias Grosser74394f02013-01-14 22:40:23 +0000967isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +0000968
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000969isl_space *ScopStmt::getDomainSpace() const {
970 return isl_set_get_space(Domain);
971}
972
Tobias Grosser74394f02013-01-14 22:40:23 +0000973isl_id *ScopStmt::getDomainId() const { return isl_set_get_tuple_id(Domain); }
Tobias Grossercd95b772012-08-30 11:49:38 +0000974
Tobias Grosser75805372011-04-29 06:27:02 +0000975ScopStmt::~ScopStmt() {
976 while (!MemAccs.empty()) {
977 delete MemAccs.back();
978 MemAccs.pop_back();
979 }
980
981 isl_set_free(Domain);
982 isl_map_free(Scattering);
983}
984
985void ScopStmt::print(raw_ostream &OS) const {
986 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000987 OS.indent(12) << "Domain :=\n";
988
989 if (Domain) {
990 OS.indent(16) << getDomainStr() << ";\n";
991 } else
992 OS.indent(16) << "n/a\n";
993
994 OS.indent(12) << "Scattering :=\n";
995
996 if (Domain) {
997 OS.indent(16) << getScatteringStr() << ";\n";
998 } else
999 OS.indent(16) << "n/a\n";
1000
Tobias Grosser083d3d32014-06-28 08:59:45 +00001001 for (MemoryAccess *Access : MemAccs)
1002 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001003}
1004
1005void ScopStmt::dump() const { print(dbgs()); }
1006
1007//===----------------------------------------------------------------------===//
1008/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001009
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001010void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001011 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1012 isl_set_free(Context);
1013 Context = NewContext;
1014}
1015
Tobias Grosserabfbe632013-02-05 12:09:06 +00001016void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001017 for (const SCEV *Parameter : NewParameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001018 if (ParameterIds.find(Parameter) != ParameterIds.end())
1019 continue;
1020
1021 int dimension = Parameters.size();
1022
1023 Parameters.push_back(Parameter);
1024 ParameterIds[Parameter] = dimension;
1025 }
1026}
1027
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001028__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1029 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001030
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001031 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001032 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001033
Tobias Grosser8f99c162011-11-15 11:38:55 +00001034 std::string ParameterName;
1035
1036 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1037 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001038 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001039 }
1040
1041 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001042 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001043
Tobias Grosser20532b82014-04-11 17:56:49 +00001044 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1045 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001046}
Tobias Grosser75805372011-04-29 06:27:02 +00001047
Tobias Grosser6be480c2011-11-08 15:41:13 +00001048void Scop::buildContext() {
1049 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001050 Context = isl_set_universe(isl_space_copy(Space));
1051 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001052}
1053
Tobias Grosser18daaca2012-05-22 10:47:27 +00001054void Scop::addParameterBounds() {
1055 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
Tobias Grosseredab1352013-06-21 06:41:31 +00001056 isl_val *V;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001057 isl_id *Id;
1058 const SCEV *Scev;
1059 const IntegerType *T;
1060
1061 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserabfbe632013-02-05 12:09:06 +00001062 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001063 T = dyn_cast<IntegerType>(Scev->getType());
1064 isl_id_free(Id);
1065
1066 assert(T && "Not an integer type");
1067 int Width = T->getBitWidth();
1068
Tobias Grosseredab1352013-06-21 06:41:31 +00001069 V = isl_val_int_from_si(IslCtx, Width - 1);
1070 V = isl_val_2exp(V);
1071 V = isl_val_neg(V);
1072 Context = isl_set_lower_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001073
Tobias Grosseredab1352013-06-21 06:41:31 +00001074 V = isl_val_int_from_si(IslCtx, Width - 1);
1075 V = isl_val_2exp(V);
1076 V = isl_val_sub_ui(V, 1);
1077 Context = isl_set_upper_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001078 }
1079}
1080
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001081void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001082 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001083 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001084
Tobias Grosser083d3d32014-06-28 08:59:45 +00001085 for (const auto &ParamID : ParameterIds) {
1086 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001087 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001088 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001089 }
1090
1091 // Align the parameters of all data structures to the model.
1092 Context = isl_set_align_params(Context, Space);
1093
Tobias Grosser083d3d32014-06-28 08:59:45 +00001094 for (ScopStmt *Stmt : *this)
1095 Stmt->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001096}
1097
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001098void Scop::simplifyAssumedContext() {
1099 // The parameter constraints of the iteration domains give us a set of
1100 // constraints that need to hold for all cases where at least a single
1101 // statement iteration is executed in the whole scop. We now simplify the
1102 // assumed context under the assumption that such constraints hold and at
1103 // least a single statement iteration is executed. For cases where no
1104 // statement instances are executed, the assumptions we have taken about
1105 // the executed code do not matter and can be changed.
1106 //
1107 // WARNING: This only holds if the assumptions we have taken do not reduce
1108 // the set of statement instances that are executed. Otherwise we
1109 // may run into a case where the iteration domains suggest that
1110 // for a certain set of parameter constraints no code is executed,
1111 // but in the original program some computation would have been
1112 // performed. In such a case, modifying the run-time conditions and
1113 // possibly influencing the run-time check may cause certain scops
1114 // to not be executed.
1115 //
1116 // Example:
1117 //
1118 // When delinearizing the following code:
1119 //
1120 // for (long i = 0; i < 100; i++)
1121 // for (long j = 0; j < m; j++)
1122 // A[i+p][j] = 1.0;
1123 //
1124 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
1125 // otherwise we would access out of bound data. Now, knowing that code is
1126 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1127 AssumedContext =
1128 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
1129}
1130
Tobias Grosser0e27e242011-10-06 00:03:48 +00001131Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
1132 isl_ctx *Context)
Tobias Grosserabfbe632013-02-05 12:09:06 +00001133 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()),
1134 MaxLoopDepth(tempScop.getMaxLoopDepth()) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001135 IslCtx = Context;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001136 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001137
Tobias Grosserabfbe632013-02-05 12:09:06 +00001138 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001139 SmallVector<unsigned, 8> Scatter;
1140
1141 Scatter.assign(MaxLoopDepth + 1, 0);
1142
1143 // Build the iteration domain, access functions and scattering functions
1144 // traversing the region tree.
1145 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00001146
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001147 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001148 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001149 simplifyAssumedContext();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001150
Tobias Grosser75805372011-04-29 06:27:02 +00001151 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1152}
1153
1154Scop::~Scop() {
1155 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001156 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001157
1158 // Free the statements;
Tobias Grosser083d3d32014-06-28 08:59:45 +00001159 for (ScopStmt *Stmt : *this)
1160 delete Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001161}
1162
Tobias Grosser74394f02013-01-14 22:40:23 +00001163std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001164std::string Scop::getAssumedContextStr() const {
1165 return stringFromIslObj(AssumedContext);
1166}
Tobias Grosser75805372011-04-29 06:27:02 +00001167
1168std::string Scop::getNameStr() const {
1169 std::string ExitName, EntryName;
1170 raw_string_ostream ExitStr(ExitName);
1171 raw_string_ostream EntryStr(EntryName);
1172
Tobias Grosserf240b482014-01-09 10:42:15 +00001173 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001174 EntryStr.str();
1175
1176 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001177 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001178 ExitStr.str();
1179 } else
1180 ExitName = "FunctionExit";
1181
1182 return EntryName + "---" + ExitName;
1183}
1184
Tobias Grosser74394f02013-01-14 22:40:23 +00001185__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001186__isl_give isl_space *Scop::getParamSpace() const {
1187 return isl_set_get_space(this->Context);
1188}
1189
Tobias Grossere86109f2013-10-29 21:05:49 +00001190__isl_give isl_set *Scop::getAssumedContext() const {
1191 return isl_set_copy(AssumedContext);
1192}
1193
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001194void Scop::addAssumption(__isl_take isl_set *Set) {
1195 AssumedContext = isl_set_intersect(AssumedContext, Set);
1196}
1197
Tobias Grosser75805372011-04-29 06:27:02 +00001198void Scop::printContext(raw_ostream &OS) const {
1199 OS << "Context:\n";
1200
1201 if (!Context) {
1202 OS.indent(4) << "n/a\n\n";
1203 return;
1204 }
1205
1206 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001207
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001208 OS.indent(4) << "Assumed Context:\n";
1209 if (!AssumedContext) {
1210 OS.indent(4) << "n/a\n\n";
1211 return;
1212 }
1213
1214 OS.indent(4) << getAssumedContextStr() << "\n";
1215
Tobias Grosser083d3d32014-06-28 08:59:45 +00001216 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001217 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001218 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1219 }
Tobias Grosser75805372011-04-29 06:27:02 +00001220}
1221
1222void Scop::printStatements(raw_ostream &OS) const {
1223 OS << "Statements {\n";
1224
Tobias Grosser083d3d32014-06-28 08:59:45 +00001225 for (ScopStmt *Stmt : *this)
1226 OS.indent(4) << *Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001227
1228 OS.indent(4) << "}\n";
1229}
1230
Tobias Grosser75805372011-04-29 06:27:02 +00001231void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001232 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1233 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001234 OS.indent(4) << "Region: " << getNameStr() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001235 printContext(OS.indent(4));
1236 printStatements(OS.indent(4));
1237}
1238
1239void Scop::dump() const { print(dbgs()); }
1240
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001241isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001242
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001243__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001244 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001245
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001246 for (ScopStmt *Stmt : *this)
1247 Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001248
1249 return Domain;
1250}
1251
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001252__isl_give isl_union_map *Scop::getMustWrites() {
1253 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1254
1255 for (ScopStmt *Stmt : *this) {
1256 for (MemoryAccess *MA : *Stmt) {
1257 if (!MA->isMustWrite())
1258 continue;
1259
1260 isl_set *Domain = Stmt->getDomain();
1261 isl_map *AccessDomain = MA->getAccessRelation();
1262 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1263 Write = isl_union_map_add_map(Write, AccessDomain);
1264 }
1265 }
1266 return isl_union_map_coalesce(Write);
1267}
1268
1269__isl_give isl_union_map *Scop::getMayWrites() {
1270 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1271
1272 for (ScopStmt *Stmt : *this) {
1273 for (MemoryAccess *MA : *Stmt) {
1274 if (!MA->isMayWrite())
1275 continue;
1276
1277 isl_set *Domain = Stmt->getDomain();
1278 isl_map *AccessDomain = MA->getAccessRelation();
1279 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1280 Write = isl_union_map_add_map(Write, AccessDomain);
1281 }
1282 }
1283 return isl_union_map_coalesce(Write);
1284}
1285
Tobias Grosser37eb4222014-02-20 21:43:54 +00001286__isl_give isl_union_map *Scop::getWrites() {
1287 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1288
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001289 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001290 for (MemoryAccess *MA : *Stmt) {
1291 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001292 continue;
1293
1294 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001295 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001296 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1297 Write = isl_union_map_add_map(Write, AccessDomain);
1298 }
1299 }
1300 return isl_union_map_coalesce(Write);
1301}
1302
1303__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001304 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001305
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001306 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001307 for (MemoryAccess *MA : *Stmt) {
1308 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001309 continue;
1310
1311 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001312 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001313
1314 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1315 Read = isl_union_map_add_map(Read, AccessDomain);
1316 }
1317 }
1318 return isl_union_map_coalesce(Read);
1319}
1320
1321__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001322 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001323
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001324 for (ScopStmt *Stmt : *this)
Tobias Grosser37eb4222014-02-20 21:43:54 +00001325 Schedule = isl_union_map_add_map(Schedule, Stmt->getScattering());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001326
Tobias Grosser37eb4222014-02-20 21:43:54 +00001327 return isl_union_map_coalesce(Schedule);
1328}
1329
1330bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1331 bool Changed = false;
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001332 for (ScopStmt *Stmt : *this) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00001333 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001334 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1335 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1336
1337 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1338 isl_union_set_free(StmtDomain);
1339 isl_union_set_free(NewStmtDomain);
1340 continue;
1341 }
1342
1343 Changed = true;
1344
1345 isl_union_set_free(StmtDomain);
1346 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1347
1348 if (isl_union_set_is_empty(NewStmtDomain)) {
1349 Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1350 isl_union_set_free(NewStmtDomain);
1351 } else
1352 Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1353 }
1354 isl_union_set_free(Domain);
1355 return Changed;
1356}
1357
Tobias Grosser75805372011-04-29 06:27:02 +00001358ScalarEvolution *Scop::getSE() const { return SE; }
1359
1360bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1361 if (tempScop.getAccessFunctions(BB))
1362 return false;
1363
1364 return true;
1365}
1366
Tobias Grosser74394f02013-01-14 22:40:23 +00001367void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
1368 SmallVectorImpl<Loop *> &NestLoops,
1369 SmallVectorImpl<unsigned> &Scatter, LoopInfo &LI) {
Tobias Grosser75805372011-04-29 06:27:02 +00001370 Loop *L = castToLoop(CurRegion, LI);
1371
1372 if (L)
1373 NestLoops.push_back(L);
1374
1375 unsigned loopDepth = NestLoops.size();
1376 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
1377
1378 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00001379 E = CurRegion.element_end();
1380 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +00001381 if (I->isSubRegion())
1382 buildScop(tempScop, *(I->getNodeAs<Region>()), NestLoops, Scatter, LI);
1383 else {
1384 BasicBlock *BB = I->getNodeAs<BasicBlock>();
1385
1386 if (isTrivialBB(BB, tempScop))
1387 continue;
1388
Tobias Grosserabfbe632013-02-05 12:09:06 +00001389 Stmts.push_back(
1390 new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, Scatter));
Tobias Grosser75805372011-04-29 06:27:02 +00001391
1392 // Increasing the Scattering function is OK for the moment, because
1393 // we are using a depth first iterator and the program is well structured.
1394 ++Scatter[loopDepth];
1395 }
1396
1397 if (!L)
1398 return;
1399
1400 // Exiting a loop region.
1401 Scatter[loopDepth] = 0;
1402 NestLoops.pop_back();
Tobias Grosser74394f02013-01-14 22:40:23 +00001403 ++Scatter[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00001404}
1405
1406//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00001407ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
1408 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00001409 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001410}
1411
1412ScopInfo::~ScopInfo() {
1413 clear();
1414 isl_ctx_free(ctx);
1415}
1416
Tobias Grosser75805372011-04-29 06:27:02 +00001417void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1418 AU.addRequired<LoopInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001419 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001420 AU.addRequired<ScalarEvolution>();
1421 AU.addRequired<TempScopInfo>();
1422 AU.setPreservesAll();
1423}
1424
1425bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
1426 LoopInfo &LI = getAnalysis<LoopInfo>();
1427 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1428
1429 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
1430
1431 // This region is no Scop.
1432 if (!tempScop) {
1433 scop = 0;
1434 return false;
1435 }
1436
1437 // Statistics.
1438 ++ScopFound;
Tobias Grosser74394f02013-01-14 22:40:23 +00001439 if (tempScop->getMaxLoopDepth() > 0)
1440 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00001441
Tobias Grosserb76f38532011-08-20 11:11:25 +00001442 scop = new Scop(*tempScop, LI, SE, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001443
1444 return false;
1445}
1446
1447char ScopInfo::ID = 0;
1448
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001449Pass *polly::createScopInfoPass() { return new ScopInfo(); }
1450
Tobias Grosser73600b82011-10-08 00:30:40 +00001451INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
1452 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001453 false);
1454INITIALIZE_PASS_DEPENDENCY(LoopInfo);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001455INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001456INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1457INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00001458INITIALIZE_PASS_END(ScopInfo, "polly-scops",
1459 "Polly - Create polyhedral description of Scops", false,
1460 false)