blob: f620b44e7bfb2206dd0f029dcbde00ec4e79e820 [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 Doerfert0ee1f212014-06-17 17:31:36 +000058// Multiplicative reductions can be disabled seperately as these kind of
59// operations can overflow easily. Additive reductions and bit operations
60// are in contrast pretty stable.
61static cl::opt<bool>
62DisableMultiplicativeReductions("polly-disable-multiplicative-reductions",
63 cl::desc("Disable multiplicative reductions"),
64 cl::Hidden, cl::ZeroOrMore, cl::init(false),
65 cl::cat(PollyCategory));
66
Tobias Grosser0695ee42013-09-17 03:30:31 +000067/// Translate a 'const SCEV *' expression in an isl_pw_aff.
Tobias Grosserabfbe632013-02-05 12:09:06 +000068struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
Tobias Grosser0695ee42013-09-17 03:30:31 +000069public:
Tobias Grosser0695ee42013-09-17 03:30:31 +000070 /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
71 ///
72 /// @param Stmt The location at which the scalar evolution expression
73 /// is evaluated.
74 /// @param Expr The expression that is translated.
75 static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
76
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000077private:
Tobias Grosser3cc99742012-06-06 16:33:15 +000078 isl_ctx *Ctx;
Tobias Grosserf5338802011-10-06 00:03:35 +000079 int NbLoopSpaces;
Tobias Grosser3cc99742012-06-06 16:33:15 +000080 const Scop *S;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000081
Tobias Grosser0695ee42013-09-17 03:30:31 +000082 SCEVAffinator(const ScopStmt *Stmt);
83 int getLoopDepth(const Loop *L);
Tobias Grosser60b54f12011-11-08 15:41:28 +000084
Tobias Grosser0695ee42013-09-17 03:30:31 +000085 __isl_give isl_pw_aff *visit(const SCEV *Expr);
86 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
87 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
88 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
89 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
90 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
91 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
92 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
93 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
94 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
95 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
96 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
Tobias Grosser60b54f12011-11-08 15:41:28 +000097
Tobias Grosser0695ee42013-09-17 03:30:31 +000098 friend struct SCEVVisitor<SCEVAffinator, isl_pw_aff *>;
99};
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000100
Tobias Grosser0695ee42013-09-17 03:30:31 +0000101SCEVAffinator::SCEVAffinator(const ScopStmt *Stmt)
102 : Ctx(Stmt->getIslCtx()), NbLoopSpaces(Stmt->getNumIterators()),
103 S(Stmt->getParent()) {}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000104
Tobias Grosser0695ee42013-09-17 03:30:31 +0000105__isl_give isl_pw_aff *SCEVAffinator::getPwAff(ScopStmt *Stmt,
106 const SCEV *Scev) {
107 Scop *S = Stmt->getParent();
108 const Region *Reg = &S->getRegion();
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000109
Tobias Grosser0695ee42013-09-17 03:30:31 +0000110 S->addParams(getParamsInAffineExpr(Reg, Scev, *S->getSE()));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000111
Tobias Grosser0695ee42013-09-17 03:30:31 +0000112 SCEVAffinator Affinator(Stmt);
113 return Affinator.visit(Scev);
114}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000115
Tobias Grosser0695ee42013-09-17 03:30:31 +0000116__isl_give isl_pw_aff *SCEVAffinator::visit(const SCEV *Expr) {
117 // In case the scev is a valid parameter, we do not further analyze this
118 // expression, but create a new parameter in the isl_pw_aff. This allows us
119 // to treat subexpressions that we cannot translate into an piecewise affine
120 // expression, as constant parameters of the piecewise affine expression.
121 if (isl_id *Id = S->getIdForParam(Expr)) {
122 isl_space *Space = isl_space_set_alloc(Ctx, 1, NbLoopSpaces);
123 Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000124
Tobias Grosser0695ee42013-09-17 03:30:31 +0000125 isl_set *Domain = isl_set_universe(isl_space_copy(Space));
126 isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
127 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000128
129 return isl_pw_aff_alloc(Domain, Affine);
130 }
131
Tobias Grosser0695ee42013-09-17 03:30:31 +0000132 return SCEVVisitor<SCEVAffinator, isl_pw_aff *>::visit(Expr);
133}
134
Tobias Grosser0d170132013-10-03 13:09:19 +0000135__isl_give isl_pw_aff *SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
Tobias Grosser0695ee42013-09-17 03:30:31 +0000136 ConstantInt *Value = Expr->getValue();
137 isl_val *v;
138
139 // LLVM does not define if an integer value is interpreted as a signed or
140 // unsigned value. Hence, without further information, it is unknown how
141 // this value needs to be converted to GMP. At the moment, we only support
142 // signed operations. So we just interpret it as signed. Later, there are
143 // two options:
144 //
145 // 1. We always interpret any value as signed and convert the values on
146 // demand.
147 // 2. We pass down the signedness of the calculation and use it to interpret
148 // this constant correctly.
149 v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
150
151 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
152 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(Space));
153 isl_aff *Affine = isl_aff_zero_on_domain(ls);
154 isl_set *Domain = isl_set_universe(Space);
155
156 Affine = isl_aff_add_constant_val(Affine, v);
157
158 return isl_pw_aff_alloc(Domain, Affine);
159}
160
161__isl_give isl_pw_aff *
162SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
163 llvm_unreachable("SCEVTruncateExpr not yet supported");
164}
165
166__isl_give isl_pw_aff *
167SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
168 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
169}
170
171__isl_give isl_pw_aff *
172SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
173 // Assuming the value is signed, a sign extension is basically a noop.
174 // TODO: Reconsider this as soon as we support unsigned values.
175 return visit(Expr->getOperand());
176}
177
178__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
179 isl_pw_aff *Sum = visit(Expr->getOperand(0));
180
181 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
182 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
183 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000184 }
185
Tobias Grosser0695ee42013-09-17 03:30:31 +0000186 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000187
Tobias Grosser0695ee42013-09-17 03:30:31 +0000188 return Sum;
189}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000190
Tobias Grosser0695ee42013-09-17 03:30:31 +0000191__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
192 isl_pw_aff *Product = visit(Expr->getOperand(0));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000193
Tobias Grosser0695ee42013-09-17 03:30:31 +0000194 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
195 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
196
197 if (!isl_pw_aff_is_cst(Product) && !isl_pw_aff_is_cst(NextOperand)) {
198 isl_pw_aff_free(Product);
199 isl_pw_aff_free(NextOperand);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000200 return nullptr;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000201 }
202
Tobias Grosser0695ee42013-09-17 03:30:31 +0000203 Product = isl_pw_aff_mul(Product, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000204 }
205
Tobias Grosser0695ee42013-09-17 03:30:31 +0000206 // TODO: Check for NSW and NUW.
207 return Product;
208}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000209
Tobias Grosser0695ee42013-09-17 03:30:31 +0000210__isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
211 llvm_unreachable("SCEVUDivExpr not yet supported");
212}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000213
Tobias Grosser0695ee42013-09-17 03:30:31 +0000214__isl_give isl_pw_aff *
215SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
216 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000217
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.
240 ScalarEvolution &SE = *S->getSE();
241 const SCEV *ZeroStartExpr = SE.getAddRecExpr(
242 SE.getConstant(Expr->getStart()->getType(), 0),
243 Expr->getStepRecurrence(SE), Expr->getLoop(), SCEV::FlagAnyWrap);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000244
Tobias Grosser0695ee42013-09-17 03:30:31 +0000245 isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
246 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000247
Tobias Grosser0695ee42013-09-17 03:30:31 +0000248 return isl_pw_aff_add(ZeroStartResult, Start);
249}
250
251__isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
252 isl_pw_aff *Max = visit(Expr->getOperand(0));
253
254 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
255 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
256 Max = isl_pw_aff_max(Max, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000257 }
258
Tobias Grosser0695ee42013-09-17 03:30:31 +0000259 return Max;
260}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000261
Tobias Grosser0695ee42013-09-17 03:30:31 +0000262__isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
263 llvm_unreachable("SCEVUMaxExpr not yet supported");
264}
265
266__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
267 llvm_unreachable("Unknowns are always parameters");
268}
269
270int SCEVAffinator::getLoopDepth(const Loop *L) {
271 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
272 assert(outerLoop && "Scop does not contain this loop");
273 return L->getLoopDepth() - outerLoop->getLoopDepth();
274}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000275
Johannes Doerfertf6183392014-07-01 20:52:51 +0000276/// @brief Return the reduction type for a given binary operator
277static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
278 const Instruction *Load) {
279 if (!BinOp)
280 return MemoryAccess::RT_NONE;
281 switch (BinOp->getOpcode()) {
282 case Instruction::FAdd:
283 if (!BinOp->hasUnsafeAlgebra())
284 return MemoryAccess::RT_NONE;
285 // Fall through
286 case Instruction::Add:
287 return MemoryAccess::RT_ADD;
288 case Instruction::Or:
289 return MemoryAccess::RT_BOR;
290 case Instruction::Xor:
291 return MemoryAccess::RT_BXOR;
292 case Instruction::And:
293 return MemoryAccess::RT_BAND;
294 case Instruction::FMul:
295 if (!BinOp->hasUnsafeAlgebra())
296 return MemoryAccess::RT_NONE;
297 // Fall through
298 case Instruction::Mul:
299 if (DisableMultiplicativeReductions)
300 return MemoryAccess::RT_NONE;
301 return MemoryAccess::RT_MUL;
302 default:
303 return MemoryAccess::RT_NONE;
304 }
305}
Tobias Grosser75805372011-04-29 06:27:02 +0000306//===----------------------------------------------------------------------===//
307
308MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000309 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000310 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000311}
312
Tobias Grossere602a072013-05-07 07:30:56 +0000313static void replace(std::string &str, const std::string &find,
314 const std::string &replace) {
Tobias Grosser75805372011-04-29 06:27:02 +0000315 size_t pos = 0;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000316 while ((pos = str.find(find, pos)) != std::string::npos) {
Tobias Grosser75805372011-04-29 06:27:02 +0000317 str.replace(pos, find.length(), replace);
318 pos += replace.length();
319 }
320}
321
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000322static void makeIslCompatible(std::string &str) {
Tobias Grossereec4d56e2011-08-20 11:11:14 +0000323 str.erase(0, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000324 replace(str, ".", "_");
Tobias Grosser3b660f82011-08-03 00:12:11 +0000325 replace(str, "\"", "_");
Tobias Grosser75805372011-04-29 06:27:02 +0000326}
327
328void MemoryAccess::setBaseName() {
329 raw_string_ostream OS(BaseName);
Tobias Grosserf240b482014-01-09 10:42:15 +0000330 getBaseAddr()->printAsOperand(OS, false);
Tobias Grosser75805372011-04-29 06:27:02 +0000331 BaseName = OS.str();
332
Tobias Grosser75805372011-04-29 06:27:02 +0000333 makeIslCompatible(BaseName);
334 BaseName = "MemRef_" + BaseName;
335}
336
Tobias Grosser5d453812011-10-06 00:04:11 +0000337isl_map *MemoryAccess::getAccessRelation() const {
338 return isl_map_copy(AccessRelation);
339}
340
341std::string MemoryAccess::getAccessRelationStr() const {
342 return stringFromIslObj(AccessRelation);
343}
344
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000345__isl_give isl_space *MemoryAccess::getAccessRelationSpace() const {
346 return isl_map_get_space(AccessRelation);
347}
348
Tobias Grosser5d453812011-10-06 00:04:11 +0000349isl_map *MemoryAccess::getNewAccessRelation() const {
350 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000351}
352
353isl_basic_map *MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000354 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
355 Space = isl_space_set_tuple_name(Space, isl_dim_set, getBaseName().c_str());
Tobias Grossered295662012-09-11 13:50:21 +0000356 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000357
Tobias Grosser084d8f72012-05-29 09:29:44 +0000358 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000359 isl_basic_set_universe(Statement->getDomainSpace()),
360 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000361}
362
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000363// Formalize no out-of-bound access assumption
364//
365// When delinearizing array accesses we optimistically assume that the
366// delinearized accesses do not access out of bound locations (the subscript
367// expression of each array evaluates for each statement instance that is
368// executed to a value that is larger than zero and strictly smaller than the
369// size of the corresponding dimension). The only exception is the outermost
370// dimension for which we do not assume any upper bound. At this point we
371// formalize this assumption to ensure that at code generation time the relevant
372// run-time checks can be generated.
373//
374// To find the set of constraints necessary to avoid out of bound accesses, we
375// first build the set of data locations that are not within array bounds. We
376// then apply the reverse access relation to obtain the set of iterations that
377// may contain invalid accesses and reduce this set of iterations to the ones
378// that are actually executed by intersecting them with the domain of the
379// statement. If we now project out all loop dimensions, we obtain a set of
380// parameters that may cause statement instances to be executed that may
381// possibly yield out of bound memory accesses. The complement of these
382// constraints is the set of constraints that needs to be assumed to ensure such
383// statement instances are never executed.
384void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
385 isl_space *Space = isl_space_range(getAccessRelationSpace());
386 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
387 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
388 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
389 isl_pw_aff *Var =
390 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
391 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
392
393 isl_set *DimOutside;
394
395 if (i == 0) {
396 DimOutside = isl_pw_aff_lt_set(Var, Zero);
397 } else {
398 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
399 isl_pw_aff *SizeE =
400 SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
401
402 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
403 Statement->getNumIterators());
404 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
405 isl_space_dim(Space, isl_dim_set));
406 SizeE = isl_pw_aff_set_tuple_id(
407 SizeE, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
408
409 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
410 }
411
412 Outside = isl_set_union(Outside, DimOutside);
413 }
414
415 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
416 Outside = isl_set_intersect(Outside, Statement->getDomain());
417 Outside = isl_set_params(Outside);
418 Outside = isl_set_complement(Outside);
419 Statement->getParent()->addAssumption(Outside);
420 isl_space_free(Space);
421}
422
Hongbin Zhengcea35f62012-07-06 06:47:03 +0000423MemoryAccess::MemoryAccess(const IRAccess &Access, const Instruction *AccInst,
Tobias Grosserabfbe632013-02-05 12:09:06 +0000424 ScopStmt *Statement)
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000425 : Statement(Statement), Inst(AccInst), newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000426
Tobias Grosser9759f852011-11-10 12:44:55 +0000427 BaseAddr = Access.getBase();
Tobias Grosser084d8f72012-05-29 09:29:44 +0000428 setBaseName();
Tobias Grosser5683df42011-11-09 22:34:34 +0000429
Tobias Grossera1879642011-12-20 10:43:14 +0000430 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000431 // We overapproximate non-affine accesses with a possible access to the
432 // whole array. For read accesses it does not make a difference, if an
433 // access must or may happen. However, for write accesses it is important to
434 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000435 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000436 Type = Access.isRead() ? READ : MAY_WRITE;
Tobias Grossera1879642011-12-20 10:43:14 +0000437 return;
438 }
439
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000440 Type = Access.isRead() ? READ : MUST_WRITE;
Tobias Grosser4f967492013-06-23 05:21:18 +0000441
Tobias Grosser79baa212014-04-10 08:38:02 +0000442 isl_space *Space = isl_space_alloc(Statement->getIslCtx(), 0,
443 Statement->getNumIterators(), 0);
444 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000445
Tobias Grosser79baa212014-04-10 08:38:02 +0000446 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000447 isl_pw_aff *Affine =
448 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000449
Sebastian Pop422e33f2014-06-03 18:16:31 +0000450 if (Size == 1) {
451 // For the non delinearized arrays, divide the access function of the last
452 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000453 //
454 // A stride one array access in C expressed as A[i] is expressed in
455 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
456 // two subsequent values of 'i' index two values that are stored next to
457 // each other in memory. By this division we make this characteristic
458 // obvious again.
459 isl_val *v;
460 v = isl_val_int_from_si(isl_pw_aff_get_ctx(Affine),
461 Access.getElemSizeInBytes());
462 Affine = isl_pw_aff_scale_down_val(Affine, v);
463 }
464
465 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
466
Tobias Grosser79baa212014-04-10 08:38:02 +0000467 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000468 }
469
Tobias Grosser79baa212014-04-10 08:38:02 +0000470 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000471 AccessRelation = isl_map_set_tuple_id(
472 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser084d8f72012-05-29 09:29:44 +0000473 isl_space_free(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000474 AccessRelation = isl_map_set_tuple_name(AccessRelation, isl_dim_out,
475 getBaseName().c_str());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000476 assumeNoOutOfBound(Access);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000477}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000478
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000479void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000480 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000481 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000482}
483
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000484MemoryAccess::MemoryAccess(const Value *BaseAddress, ScopStmt *Statement)
485 : Type(READ), BaseAddr(BaseAddress), Statement(Statement),
486 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000487
488 isl_basic_map *BasicAccessMap = createBasicAccessMap(Statement);
489 AccessRelation = isl_map_from_basic_map(BasicAccessMap);
Tobias Grosser37487052011-10-06 00:03:42 +0000490 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
491 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000492}
493
Johannes Doerfertf6183392014-07-01 20:52:51 +0000494raw_ostream &polly::operator<<(raw_ostream &OS,
495 MemoryAccess::ReductionType RT) {
496 switch (RT) {
497 case MemoryAccess::RT_NONE:
498 OS << "NONE";
499 break;
500 case MemoryAccess::RT_ADD:
501 OS << "ADD";
502 break;
503 case MemoryAccess::RT_MUL:
504 OS << "MUL";
505 break;
506 case MemoryAccess::RT_BOR:
507 OS << "BOR";
508 break;
509 case MemoryAccess::RT_BXOR:
510 OS << "BXOR";
511 break;
512 case MemoryAccess::RT_BAND:
513 OS << "BAND";
514 break;
515 }
516 return OS;
517}
518
Tobias Grosser75805372011-04-29 06:27:02 +0000519void MemoryAccess::print(raw_ostream &OS) const {
Tobias Grosser4f967492013-06-23 05:21:18 +0000520 switch (Type) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000521 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000522 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000523 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000524 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000525 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000526 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000527 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000528 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000529 break;
530 }
Johannes Doerfertf6183392014-07-01 20:52:51 +0000531 OS << "[Reduction Type: " << getReductionType() << "]\n";
Tobias Grosser5d453812011-10-06 00:04:11 +0000532 OS.indent(16) << getAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000533}
534
Tobias Grosser74394f02013-01-14 22:40:23 +0000535void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000536
537// Create a map in the size of the provided set domain, that maps from the
538// one element of the provided set domain to another element of the provided
539// set domain.
540// The mapping is limited to all points that are equal in all but the last
541// dimension and for which the last dimension of the input is strict smaller
542// than the last dimension of the output.
543//
544// getEqualAndLarger(set[i0, i1, ..., iX]):
545//
546// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
547// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
548//
Tobias Grosserf5338802011-10-06 00:03:35 +0000549static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000550 isl_space *Space = isl_space_map_from_set(setDomain);
551 isl_map *Map = isl_map_universe(isl_space_copy(Space));
552 isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000553 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000554
555 // Set all but the last dimension to be equal for the input and output
556 //
557 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
558 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000559 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000560 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000561
562 // Set the last dimension of the input to be strict smaller than the
563 // last dimension of the output.
564 //
565 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
566 //
Tobias Grosseredab1352013-06-21 06:41:31 +0000567 isl_val *v;
568 isl_ctx *Ctx = isl_map_get_ctx(Map);
Tobias Grosserf5338802011-10-06 00:03:35 +0000569 isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
Tobias Grosseredab1352013-06-21 06:41:31 +0000570 v = isl_val_int_from_si(Ctx, -1);
571 c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
572 v = isl_val_int_from_si(Ctx, 1);
573 c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
574 v = isl_val_int_from_si(Ctx, -1);
575 c = isl_constraint_set_constant_val(c, v);
Tobias Grosser75805372011-04-29 06:27:02 +0000576
Tobias Grosserc327932c2012-02-01 14:23:36 +0000577 Map = isl_map_add_constraint(Map, c);
Tobias Grosser75805372011-04-29 06:27:02 +0000578
Tobias Grosser23b36662011-10-17 08:32:36 +0000579 isl_local_space_free(MapLocalSpace);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000580 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000581}
582
Sebastian Popa00a0292012-12-18 07:46:06 +0000583isl_set *MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000584 isl_map *S = const_cast<isl_map *>(Schedule);
Sebastian Popa00a0292012-12-18 07:46:06 +0000585 isl_map *AccessRelation = getAccessRelation();
586 isl_space *Space = isl_space_range(isl_map_get_space(S));
587 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000588
Sebastian Popa00a0292012-12-18 07:46:06 +0000589 S = isl_map_reverse(S);
590 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000591
Sebastian Popa00a0292012-12-18 07:46:06 +0000592 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
593 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
594 NextScatt = isl_map_apply_domain(NextScatt, S);
595 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000596
Sebastian Popa00a0292012-12-18 07:46:06 +0000597 isl_set *Deltas = isl_map_deltas(NextScatt);
598 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000599}
600
Sebastian Popa00a0292012-12-18 07:46:06 +0000601bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000602 int StrideWidth) const {
603 isl_set *Stride, *StrideX;
604 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000605
Sebastian Popa00a0292012-12-18 07:46:06 +0000606 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000607 StrideX = isl_set_universe(isl_set_get_space(Stride));
608 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
609 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000610
Tobias Grosser28dd4862012-01-24 16:42:16 +0000611 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000612 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000613
Tobias Grosser28dd4862012-01-24 16:42:16 +0000614 return IsStrideX;
615}
616
Sebastian Popa00a0292012-12-18 07:46:06 +0000617bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
618 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000619}
620
Tobias Grosser79baa212014-04-10 08:38:02 +0000621bool MemoryAccess::isScalar() const {
622 return isl_map_n_out(AccessRelation) == 0;
623}
624
Sebastian Popa00a0292012-12-18 07:46:06 +0000625bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
626 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000627}
628
Tobias Grosser5d453812011-10-06 00:04:11 +0000629void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000630 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000631 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000632}
Tobias Grosser75805372011-04-29 06:27:02 +0000633
634//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000635
Tobias Grosser74394f02013-01-14 22:40:23 +0000636isl_map *ScopStmt::getScattering() const { return isl_map_copy(Scattering); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000637
Tobias Grosser37eb4222014-02-20 21:43:54 +0000638void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
639 assert(isl_set_is_subset(NewDomain, Domain) &&
640 "New domain is not a subset of old domain!");
641 isl_set_free(Domain);
642 Domain = NewDomain;
643 Scattering = isl_map_intersect_domain(Scattering, isl_set_copy(Domain));
644}
645
Tobias Grossercf3942d2011-10-06 00:04:05 +0000646void ScopStmt::setScattering(isl_map *NewScattering) {
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000647 assert(NewScattering && "New scattering is nullptr");
Tobias Grosserb76f38532011-08-20 11:11:25 +0000648 isl_map_free(Scattering);
Tobias Grossercf3942d2011-10-06 00:04:05 +0000649 Scattering = NewScattering;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000650}
651
Tobias Grosser75805372011-04-29 06:27:02 +0000652void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000653 unsigned NbIterators = getNumIterators();
654 unsigned NbScatteringDims = Parent.getMaxLoopDepth() * 2 + 1;
655
Tobias Grosser084d8f72012-05-29 09:29:44 +0000656 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScatteringDims);
Tobias Grosserf5338802011-10-06 00:03:35 +0000657 Space = isl_space_set_tuple_name(Space, isl_dim_out, "scattering");
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000658
Tobias Grosser084d8f72012-05-29 09:29:44 +0000659 Scattering = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
660 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000661
662 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000663 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosserabfbe632013-02-05 12:09:06 +0000664 Scattering =
665 isl_map_equate(Scattering, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000666
667 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000668 for (unsigned i = 0; i < NbIterators + 1; ++i)
669 Scattering = isl_map_fix_si(Scattering, isl_dim_out, 2 * i, Scatter[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000670
671 // Fill scattering dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000672 for (unsigned i = 2 * NbIterators + 1; i < NbScatteringDims; ++i)
673 Scattering = isl_map_fix_si(Scattering, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000674
Tobias Grosser37487052011-10-06 00:03:42 +0000675 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000676}
677
678void ScopStmt::buildAccesses(TempScop &tempScop, const Region &CurRegion) {
Tobias Grosser083d3d32014-06-28 08:59:45 +0000679 for (auto &&Access : *tempScop.getAccessFunctions(BB)) {
680 MemAccs.push_back(new MemoryAccess(Access.first, Access.second, this));
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000681
682 // We do not track locations for scalar memory accesses at the moment.
683 //
684 // We do not have a use for this information at the moment. If we need this
685 // at some point, the "instruction -> access" mapping needs to be enhanced
686 // as a single instruction could then possibly perform multiple accesses.
Tobias Grosser083d3d32014-06-28 08:59:45 +0000687 if (!Access.first.isScalar()) {
688 assert(!InstructionToAccess.count(Access.second) &&
Tobias Grosser3fc91542014-02-20 21:43:45 +0000689 "Unexpected 1-to-N mapping on instruction to access map!");
Tobias Grosser083d3d32014-06-28 08:59:45 +0000690 InstructionToAccess[Access.second] = MemAccs.back();
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000691 }
Tobias Grosser75805372011-04-29 06:27:02 +0000692 }
693}
694
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000695void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000696 for (MemoryAccess *MA : *this)
697 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000698
699 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
700 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
701}
702
Tobias Grosser65b00582011-11-08 15:41:19 +0000703__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000704 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
705 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000706
Tobias Grosserd2795d02011-08-18 07:51:40 +0000707 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000708 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000709 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000710 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000711 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000712 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000713 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000714 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000715 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000716 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000717 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000718 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000719 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000720 case ICmpInst::ICMP_ULT:
721 case ICmpInst::ICMP_UGT:
722 case ICmpInst::ICMP_ULE:
Tobias Grosser75805372011-04-29 06:27:02 +0000723 case ICmpInst::ICMP_UGE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000724 llvm_unreachable("Unsigned comparisons not yet supported");
Tobias Grosser75805372011-04-29 06:27:02 +0000725 default:
726 llvm_unreachable("Non integer predicate not supported");
727 }
Tobias Grosser75805372011-04-29 06:27:02 +0000728}
729
Tobias Grossere19661e2011-10-07 08:46:57 +0000730__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000731 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000732 isl_space *Space;
733 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000734
Tobias Grossere19661e2011-10-07 08:46:57 +0000735 Space = isl_set_get_space(Domain);
736 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000737
Tobias Grosser75805372011-04-29 06:27:02 +0000738 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000739 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000740 isl_pw_aff *IV =
741 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000742
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000743 // 0 <= IV.
744 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
745 Domain = isl_set_intersect(Domain, LowerBound);
746
747 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000748 const Loop *L = getLoopForDimension(i);
Tobias Grosser1179afa2011-11-02 21:37:51 +0000749 const SCEV *LatchExecutions = tempScop.getLoopBound(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000750 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
751 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000752 Domain = isl_set_intersect(Domain, UpperBoundSet);
753 }
754
Tobias Grosserf5338802011-10-06 00:03:35 +0000755 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000756 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000757}
758
Tobias Grossere602a072013-05-07 07:30:56 +0000759__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
760 TempScop &tempScop,
761 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000762 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000763 *CurrentRegion = &CurRegion;
Tobias Grossere19661e2011-10-07 08:46:57 +0000764 const BasicBlock *BranchingBB = BB;
Tobias Grosser75805372011-04-29 06:27:02 +0000765
Tobias Grosser75805372011-04-29 06:27:02 +0000766 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000767 if (BranchingBB != CurrentRegion->getEntry()) {
768 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000769 for (const auto &C : *Condition) {
770 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000771 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000772 }
773 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000774 BranchingBB = CurrentRegion->getEntry();
775 CurrentRegion = CurrentRegion->getParent();
776 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000777
Tobias Grossere19661e2011-10-07 08:46:57 +0000778 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000779}
780
Tobias Grossere602a072013-05-07 07:30:56 +0000781__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
782 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000783 isl_space *Space;
784 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000785 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000786
787 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
788
Tobias Grosser084d8f72012-05-29 09:29:44 +0000789 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
790
Tobias Grossere19661e2011-10-07 08:46:57 +0000791 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000792 Domain = addLoopBoundsToDomain(Domain, tempScop);
793 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000794 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000795
796 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000797}
798
Tobias Grosser74394f02013-01-14 22:40:23 +0000799ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +0000800 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser75805372011-04-29 06:27:02 +0000801 SmallVectorImpl<unsigned> &Scatter)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000802 : Parent(parent), BB(&bb), IVS(Nest.size()), NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000803 // Setup the induction variables.
Sebastian Pop860e0212013-02-15 21:26:44 +0000804 for (unsigned i = 0, e = Nest.size(); i < e; ++i) {
Sebastian Pop27c10c62013-03-22 22:07:43 +0000805 if (!SCEVCodegen) {
806 PHINode *PN = Nest[i]->getCanonicalInductionVariable();
807 assert(PN && "Non canonical IV in Scop!");
Tobias Grosser826b2af2013-03-21 16:14:50 +0000808 IVS[i] = PN;
Sebastian Pop27c10c62013-03-22 22:07:43 +0000809 }
Sebastian Pop860e0212013-02-15 21:26:44 +0000810 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000811 }
812
813 raw_string_ostream OS(BaseName);
Tobias Grosserf240b482014-01-09 10:42:15 +0000814 bb.printAsOperand(OS, false);
Tobias Grosser75805372011-04-29 06:27:02 +0000815 BaseName = OS.str();
816
Tobias Grosser75805372011-04-29 06:27:02 +0000817 makeIslCompatible(BaseName);
818 BaseName = "Stmt_" + BaseName;
819
Tobias Grossere19661e2011-10-07 08:46:57 +0000820 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000821 buildScattering(Scatter);
822 buildAccesses(tempScop, CurRegion);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000823 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000824}
825
Johannes Doerferte58a0122014-06-27 20:31:28 +0000826/// @brief Collect loads which might form a reduction chain with @p StoreMA
827///
828/// Check if the stored value for @p StoreMA is a binary operator with one or
829/// two loads as operands. If the binary operand is commutative & associative,
830/// used only once (by @p StoreMA) and its load operands are also used only
831/// once, we have found a possible reduction chain. It starts at an operand
832/// load and includes the binary operator and @p StoreMA.
833///
834/// Note: We allow only one use to ensure the load and binary operator cannot
835/// escape this block or into any other store except @p StoreMA.
836void ScopStmt::collectCandiateReductionLoads(
837 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
838 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
839 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000840 return;
841
842 // Skip if there is not one binary operator between the load and the store
843 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +0000844 if (!BinOp)
845 return;
846
847 // Skip if the binary operators has multiple uses
848 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000849 return;
850
851 // Skip if the opcode of the binary operator is not commutative/associative
852 if (!BinOp->isCommutative() || !BinOp->isAssociative())
853 return;
854
Johannes Doerfert9890a052014-07-01 00:32:29 +0000855 // Skip if the binary operator is outside the current SCoP
856 if (BinOp->getParent() != Store->getParent())
857 return;
858
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000859 // Skip if it is a multiplicative reduction and we disabled them
860 if (DisableMultiplicativeReductions &&
861 (BinOp->getOpcode() == Instruction::Mul ||
862 BinOp->getOpcode() == Instruction::FMul))
863 return;
864
Johannes Doerferte58a0122014-06-27 20:31:28 +0000865 // Check the binary operator operands for a candidate load
866 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
867 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
868 if (!PossibleLoad0 && !PossibleLoad1)
869 return;
870
871 // A load is only a candidate if it cannot escape (thus has only this use)
872 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000873 if (PossibleLoad0->getParent() == Store->getParent())
874 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000875 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000876 if (PossibleLoad1->getParent() == Store->getParent())
877 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000878}
879
880/// @brief Check for reductions in this ScopStmt
881///
882/// Iterate over all store memory accesses and check for valid binary reduction
883/// like chains. For all candidates we check if they have the same base address
884/// and there are no other accesses which overlap with them. The base address
885/// check rules out impossible reductions candidates early. The overlap check,
886/// together with the "only one user" check in collectCandiateReductionLoads,
887/// guarantees that none of the intermediate results will escape during
888/// execution of the loop nest. We basically check here that no other memory
889/// access can access the same memory as the potential reduction.
890void ScopStmt::checkForReductions() {
891 SmallVector<MemoryAccess *, 2> Loads;
892 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
893
894 // First collect candidate load-store reduction chains by iterating over all
895 // stores and collecting possible reduction loads.
896 for (MemoryAccess *StoreMA : MemAccs) {
897 if (StoreMA->isRead())
898 continue;
899
900 Loads.clear();
901 collectCandiateReductionLoads(StoreMA, Loads);
902 for (MemoryAccess *LoadMA : Loads)
903 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
904 }
905
906 // Then check each possible candidate pair.
907 for (const auto &CandidatePair : Candidates) {
908 bool Valid = true;
909 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
910 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
911
912 // Skip those with obviously unequal base addresses.
913 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
914 isl_map_free(LoadAccs);
915 isl_map_free(StoreAccs);
916 continue;
917 }
918
919 // And check if the remaining for overlap with other memory accesses.
920 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
921 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
922 isl_set *AllAccs = isl_map_range(AllAccsRel);
923
924 for (MemoryAccess *MA : MemAccs) {
925 if (MA == CandidatePair.first || MA == CandidatePair.second)
926 continue;
927
928 isl_map *AccRel =
929 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
930 isl_set *Accs = isl_map_range(AccRel);
931
932 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
933 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
934 Valid = Valid && isl_set_is_empty(OverlapAccs);
935 isl_set_free(OverlapAccs);
936 }
937 }
938
939 isl_set_free(AllAccs);
940 if (!Valid)
941 continue;
942
Johannes Doerfertf6183392014-07-01 20:52:51 +0000943 const LoadInst *Load =
944 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
945 MemoryAccess::ReductionType RT =
946 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
947
Johannes Doerferte58a0122014-06-27 20:31:28 +0000948 // If no overlapping access was found we mark the load and store as
949 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000950 CandidatePair.first->markAsReductionLike(RT);
951 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000952 }
Tobias Grosser75805372011-04-29 06:27:02 +0000953}
954
Tobias Grosser74394f02013-01-14 22:40:23 +0000955std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +0000956
957std::string ScopStmt::getScatteringStr() const {
Tobias Grossercf3942d2011-10-06 00:04:05 +0000958 return stringFromIslObj(Scattering);
Tobias Grosser75805372011-04-29 06:27:02 +0000959}
960
Tobias Grosser74394f02013-01-14 22:40:23 +0000961unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +0000962
963unsigned ScopStmt::getNumIterators() const {
964 // The final read has one dimension with one element.
965 if (!BB)
966 return 1;
967
Sebastian Pop860e0212013-02-15 21:26:44 +0000968 return NestLoops.size();
Tobias Grosser75805372011-04-29 06:27:02 +0000969}
970
971unsigned ScopStmt::getNumScattering() const {
972 return isl_map_dim(Scattering, isl_dim_out);
973}
974
975const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
976
Tobias Grosserabfbe632013-02-05 12:09:06 +0000977const PHINode *
978ScopStmt::getInductionVariableForDimension(unsigned Dimension) const {
Sebastian Popf30d3b22013-02-15 21:26:48 +0000979 return IVS[Dimension];
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000980}
981
982const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +0000983 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +0000984}
985
Tobias Grosser74394f02013-01-14 22:40:23 +0000986isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +0000987
Tobias Grosser74394f02013-01-14 22:40:23 +0000988isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +0000989
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000990isl_space *ScopStmt::getDomainSpace() const {
991 return isl_set_get_space(Domain);
992}
993
Tobias Grosser74394f02013-01-14 22:40:23 +0000994isl_id *ScopStmt::getDomainId() const { return isl_set_get_tuple_id(Domain); }
Tobias Grossercd95b772012-08-30 11:49:38 +0000995
Tobias Grosser75805372011-04-29 06:27:02 +0000996ScopStmt::~ScopStmt() {
997 while (!MemAccs.empty()) {
998 delete MemAccs.back();
999 MemAccs.pop_back();
1000 }
1001
1002 isl_set_free(Domain);
1003 isl_map_free(Scattering);
1004}
1005
1006void ScopStmt::print(raw_ostream &OS) const {
1007 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001008 OS.indent(12) << "Domain :=\n";
1009
1010 if (Domain) {
1011 OS.indent(16) << getDomainStr() << ";\n";
1012 } else
1013 OS.indent(16) << "n/a\n";
1014
1015 OS.indent(12) << "Scattering :=\n";
1016
1017 if (Domain) {
1018 OS.indent(16) << getScatteringStr() << ";\n";
1019 } else
1020 OS.indent(16) << "n/a\n";
1021
Tobias Grosser083d3d32014-06-28 08:59:45 +00001022 for (MemoryAccess *Access : MemAccs)
1023 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001024}
1025
1026void ScopStmt::dump() const { print(dbgs()); }
1027
1028//===----------------------------------------------------------------------===//
1029/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001030
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001031void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001032 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1033 isl_set_free(Context);
1034 Context = NewContext;
1035}
1036
Tobias Grosserabfbe632013-02-05 12:09:06 +00001037void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001038 for (const SCEV *Parameter : NewParameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001039 if (ParameterIds.find(Parameter) != ParameterIds.end())
1040 continue;
1041
1042 int dimension = Parameters.size();
1043
1044 Parameters.push_back(Parameter);
1045 ParameterIds[Parameter] = dimension;
1046 }
1047}
1048
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001049__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1050 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001051
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001052 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001053 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001054
Tobias Grosser8f99c162011-11-15 11:38:55 +00001055 std::string ParameterName;
1056
1057 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1058 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001059 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001060 }
1061
1062 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001063 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001064
Tobias Grosser20532b82014-04-11 17:56:49 +00001065 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1066 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001067}
Tobias Grosser75805372011-04-29 06:27:02 +00001068
Tobias Grosser6be480c2011-11-08 15:41:13 +00001069void Scop::buildContext() {
1070 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001071 Context = isl_set_universe(isl_space_copy(Space));
1072 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001073}
1074
Tobias Grosser18daaca2012-05-22 10:47:27 +00001075void Scop::addParameterBounds() {
1076 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
Tobias Grosseredab1352013-06-21 06:41:31 +00001077 isl_val *V;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001078 isl_id *Id;
1079 const SCEV *Scev;
1080 const IntegerType *T;
1081
1082 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserabfbe632013-02-05 12:09:06 +00001083 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001084 T = dyn_cast<IntegerType>(Scev->getType());
1085 isl_id_free(Id);
1086
1087 assert(T && "Not an integer type");
1088 int Width = T->getBitWidth();
1089
Tobias Grosseredab1352013-06-21 06:41:31 +00001090 V = isl_val_int_from_si(IslCtx, Width - 1);
1091 V = isl_val_2exp(V);
1092 V = isl_val_neg(V);
1093 Context = isl_set_lower_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001094
Tobias Grosseredab1352013-06-21 06:41:31 +00001095 V = isl_val_int_from_si(IslCtx, Width - 1);
1096 V = isl_val_2exp(V);
1097 V = isl_val_sub_ui(V, 1);
1098 Context = isl_set_upper_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001099 }
1100}
1101
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001102void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001103 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001104 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001105
Tobias Grosser083d3d32014-06-28 08:59:45 +00001106 for (const auto &ParamID : ParameterIds) {
1107 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001108 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001109 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001110 }
1111
1112 // Align the parameters of all data structures to the model.
1113 Context = isl_set_align_params(Context, Space);
1114
Tobias Grosser083d3d32014-06-28 08:59:45 +00001115 for (ScopStmt *Stmt : *this)
1116 Stmt->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001117}
1118
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001119void Scop::simplifyAssumedContext() {
1120 // The parameter constraints of the iteration domains give us a set of
1121 // constraints that need to hold for all cases where at least a single
1122 // statement iteration is executed in the whole scop. We now simplify the
1123 // assumed context under the assumption that such constraints hold and at
1124 // least a single statement iteration is executed. For cases where no
1125 // statement instances are executed, the assumptions we have taken about
1126 // the executed code do not matter and can be changed.
1127 //
1128 // WARNING: This only holds if the assumptions we have taken do not reduce
1129 // the set of statement instances that are executed. Otherwise we
1130 // may run into a case where the iteration domains suggest that
1131 // for a certain set of parameter constraints no code is executed,
1132 // but in the original program some computation would have been
1133 // performed. In such a case, modifying the run-time conditions and
1134 // possibly influencing the run-time check may cause certain scops
1135 // to not be executed.
1136 //
1137 // Example:
1138 //
1139 // When delinearizing the following code:
1140 //
1141 // for (long i = 0; i < 100; i++)
1142 // for (long j = 0; j < m; j++)
1143 // A[i+p][j] = 1.0;
1144 //
1145 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
1146 // otherwise we would access out of bound data. Now, knowing that code is
1147 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1148 AssumedContext =
1149 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
1150}
1151
Tobias Grosser0e27e242011-10-06 00:03:48 +00001152Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
1153 isl_ctx *Context)
Tobias Grosserabfbe632013-02-05 12:09:06 +00001154 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()),
1155 MaxLoopDepth(tempScop.getMaxLoopDepth()) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001156 IslCtx = Context;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001157 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001158
Tobias Grosserabfbe632013-02-05 12:09:06 +00001159 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001160 SmallVector<unsigned, 8> Scatter;
1161
1162 Scatter.assign(MaxLoopDepth + 1, 0);
1163
1164 // Build the iteration domain, access functions and scattering functions
1165 // traversing the region tree.
1166 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00001167
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001168 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001169 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001170 simplifyAssumedContext();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001171
Tobias Grosser75805372011-04-29 06:27:02 +00001172 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1173}
1174
1175Scop::~Scop() {
1176 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001177 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001178
1179 // Free the statements;
Tobias Grosser083d3d32014-06-28 08:59:45 +00001180 for (ScopStmt *Stmt : *this)
1181 delete Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001182}
1183
Tobias Grosser74394f02013-01-14 22:40:23 +00001184std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001185std::string Scop::getAssumedContextStr() const {
1186 return stringFromIslObj(AssumedContext);
1187}
Tobias Grosser75805372011-04-29 06:27:02 +00001188
1189std::string Scop::getNameStr() const {
1190 std::string ExitName, EntryName;
1191 raw_string_ostream ExitStr(ExitName);
1192 raw_string_ostream EntryStr(EntryName);
1193
Tobias Grosserf240b482014-01-09 10:42:15 +00001194 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001195 EntryStr.str();
1196
1197 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001198 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001199 ExitStr.str();
1200 } else
1201 ExitName = "FunctionExit";
1202
1203 return EntryName + "---" + ExitName;
1204}
1205
Tobias Grosser74394f02013-01-14 22:40:23 +00001206__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001207__isl_give isl_space *Scop::getParamSpace() const {
1208 return isl_set_get_space(this->Context);
1209}
1210
Tobias Grossere86109f2013-10-29 21:05:49 +00001211__isl_give isl_set *Scop::getAssumedContext() const {
1212 return isl_set_copy(AssumedContext);
1213}
1214
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001215void Scop::addAssumption(__isl_take isl_set *Set) {
1216 AssumedContext = isl_set_intersect(AssumedContext, Set);
1217}
1218
Tobias Grosser75805372011-04-29 06:27:02 +00001219void Scop::printContext(raw_ostream &OS) const {
1220 OS << "Context:\n";
1221
1222 if (!Context) {
1223 OS.indent(4) << "n/a\n\n";
1224 return;
1225 }
1226
1227 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001228
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001229 OS.indent(4) << "Assumed Context:\n";
1230 if (!AssumedContext) {
1231 OS.indent(4) << "n/a\n\n";
1232 return;
1233 }
1234
1235 OS.indent(4) << getAssumedContextStr() << "\n";
1236
Tobias Grosser083d3d32014-06-28 08:59:45 +00001237 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001238 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001239 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1240 }
Tobias Grosser75805372011-04-29 06:27:02 +00001241}
1242
1243void Scop::printStatements(raw_ostream &OS) const {
1244 OS << "Statements {\n";
1245
Tobias Grosser083d3d32014-06-28 08:59:45 +00001246 for (ScopStmt *Stmt : *this)
1247 OS.indent(4) << *Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001248
1249 OS.indent(4) << "}\n";
1250}
1251
Tobias Grosser75805372011-04-29 06:27:02 +00001252void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001253 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1254 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001255 OS.indent(4) << "Region: " << getNameStr() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001256 printContext(OS.indent(4));
1257 printStatements(OS.indent(4));
1258}
1259
1260void Scop::dump() const { print(dbgs()); }
1261
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001262isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001263
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001264__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001265 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001266
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001267 for (ScopStmt *Stmt : *this)
1268 Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001269
1270 return Domain;
1271}
1272
Tobias Grosser37eb4222014-02-20 21:43:54 +00001273__isl_give isl_union_map *Scop::getWrites() {
1274 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1275
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001276 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001277 for (MemoryAccess *MA : *Stmt) {
1278 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001279 continue;
1280
1281 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001282 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001283 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1284 Write = isl_union_map_add_map(Write, AccessDomain);
1285 }
1286 }
1287 return isl_union_map_coalesce(Write);
1288}
1289
1290__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001291 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001292
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001293 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001294 for (MemoryAccess *MA : *Stmt) {
1295 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001296 continue;
1297
1298 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001299 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001300
1301 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1302 Read = isl_union_map_add_map(Read, AccessDomain);
1303 }
1304 }
1305 return isl_union_map_coalesce(Read);
1306}
1307
1308__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001309 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001310
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001311 for (ScopStmt *Stmt : *this)
Tobias Grosser37eb4222014-02-20 21:43:54 +00001312 Schedule = isl_union_map_add_map(Schedule, Stmt->getScattering());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001313
Tobias Grosser37eb4222014-02-20 21:43:54 +00001314 return isl_union_map_coalesce(Schedule);
1315}
1316
1317bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1318 bool Changed = false;
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001319 for (ScopStmt *Stmt : *this) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00001320 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001321 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1322 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1323
1324 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1325 isl_union_set_free(StmtDomain);
1326 isl_union_set_free(NewStmtDomain);
1327 continue;
1328 }
1329
1330 Changed = true;
1331
1332 isl_union_set_free(StmtDomain);
1333 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1334
1335 if (isl_union_set_is_empty(NewStmtDomain)) {
1336 Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1337 isl_union_set_free(NewStmtDomain);
1338 } else
1339 Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1340 }
1341 isl_union_set_free(Domain);
1342 return Changed;
1343}
1344
Tobias Grosser75805372011-04-29 06:27:02 +00001345ScalarEvolution *Scop::getSE() const { return SE; }
1346
1347bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1348 if (tempScop.getAccessFunctions(BB))
1349 return false;
1350
1351 return true;
1352}
1353
Tobias Grosser74394f02013-01-14 22:40:23 +00001354void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
1355 SmallVectorImpl<Loop *> &NestLoops,
1356 SmallVectorImpl<unsigned> &Scatter, LoopInfo &LI) {
Tobias Grosser75805372011-04-29 06:27:02 +00001357 Loop *L = castToLoop(CurRegion, LI);
1358
1359 if (L)
1360 NestLoops.push_back(L);
1361
1362 unsigned loopDepth = NestLoops.size();
1363 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
1364
1365 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00001366 E = CurRegion.element_end();
1367 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +00001368 if (I->isSubRegion())
1369 buildScop(tempScop, *(I->getNodeAs<Region>()), NestLoops, Scatter, LI);
1370 else {
1371 BasicBlock *BB = I->getNodeAs<BasicBlock>();
1372
1373 if (isTrivialBB(BB, tempScop))
1374 continue;
1375
Tobias Grosserabfbe632013-02-05 12:09:06 +00001376 Stmts.push_back(
1377 new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, Scatter));
Tobias Grosser75805372011-04-29 06:27:02 +00001378
1379 // Increasing the Scattering function is OK for the moment, because
1380 // we are using a depth first iterator and the program is well structured.
1381 ++Scatter[loopDepth];
1382 }
1383
1384 if (!L)
1385 return;
1386
1387 // Exiting a loop region.
1388 Scatter[loopDepth] = 0;
1389 NestLoops.pop_back();
Tobias Grosser74394f02013-01-14 22:40:23 +00001390 ++Scatter[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00001391}
1392
1393//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00001394ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
1395 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00001396 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001397}
1398
1399ScopInfo::~ScopInfo() {
1400 clear();
1401 isl_ctx_free(ctx);
1402}
1403
Tobias Grosser75805372011-04-29 06:27:02 +00001404void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1405 AU.addRequired<LoopInfo>();
1406 AU.addRequired<RegionInfo>();
1407 AU.addRequired<ScalarEvolution>();
1408 AU.addRequired<TempScopInfo>();
1409 AU.setPreservesAll();
1410}
1411
1412bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
1413 LoopInfo &LI = getAnalysis<LoopInfo>();
1414 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1415
1416 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
1417
1418 // This region is no Scop.
1419 if (!tempScop) {
1420 scop = 0;
1421 return false;
1422 }
1423
1424 // Statistics.
1425 ++ScopFound;
Tobias Grosser74394f02013-01-14 22:40:23 +00001426 if (tempScop->getMaxLoopDepth() > 0)
1427 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00001428
Tobias Grosserb76f38532011-08-20 11:11:25 +00001429 scop = new Scop(*tempScop, LI, SE, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001430
1431 return false;
1432}
1433
1434char ScopInfo::ID = 0;
1435
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001436Pass *polly::createScopInfoPass() { return new ScopInfo(); }
1437
Tobias Grosser73600b82011-10-08 00:30:40 +00001438INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
1439 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001440 false);
1441INITIALIZE_PASS_DEPENDENCY(LoopInfo);
1442INITIALIZE_PASS_DEPENDENCY(RegionInfo);
1443INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1444INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00001445INITIALIZE_PASS_END(ScopInfo, "polly-scops",
1446 "Polly - Create polyhedral description of Scops", false,
1447 false)