blob: b3f05503d78f68bf29f4beb15148d0f61b6048cb [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
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"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser83628182013-05-07 08:11:54 +000033#include "llvm/Analysis/RegionIterator.h"
34#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000035#include "llvm/Support/Debug.h"
36
37#include "isl/constraint.h"
38#include "isl/set.h"
39#include "isl/map.h"
Tobias Grosser37eb4222014-02-20 21:43:54 +000040#include "isl/union_map.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
42#include "isl/printer.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000043#include "isl/local_space.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000044#include "isl/options.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000045#include "isl/val.h"
Chandler Carruth95fef942014-04-22 03:30:19 +000046
Tobias Grosser75805372011-04-29 06:27:02 +000047#include <sstream>
48#include <string>
49#include <vector>
50
51using namespace llvm;
52using namespace polly;
53
Chandler Carruth95fef942014-04-22 03:30:19 +000054#define DEBUG_TYPE "polly-scops"
55
Tobias Grosser74394f02013-01-14 22:40:23 +000056STATISTIC(ScopFound, "Number of valid Scops");
57STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000058
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000059// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000060// operations can overflow easily. Additive reductions and bit operations
61// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000062static cl::opt<bool> DisableMultiplicativeReductions(
63 "polly-disable-multiplicative-reductions",
64 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
65 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000066
Johannes Doerfert9143d672014-09-27 11:02:39 +000067static cl::opt<unsigned> RunTimeChecksMaxParameters(
68 "polly-rtc-max-parameters",
69 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
70 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
71
Tobias Grosser0695ee42013-09-17 03:30:31 +000072/// Translate a 'const SCEV *' expression in an isl_pw_aff.
Tobias Grosserabfbe632013-02-05 12:09:06 +000073struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
Tobias Grosser0695ee42013-09-17 03:30:31 +000074public:
Tobias Grosser0695ee42013-09-17 03:30:31 +000075 /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
76 ///
77 /// @param Stmt The location at which the scalar evolution expression
78 /// is evaluated.
79 /// @param Expr The expression that is translated.
80 static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
81
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000082private:
Tobias Grosser3cc99742012-06-06 16:33:15 +000083 isl_ctx *Ctx;
Tobias Grosserf5338802011-10-06 00:03:35 +000084 int NbLoopSpaces;
Tobias Grosser3cc99742012-06-06 16:33:15 +000085 const Scop *S;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000086
Tobias Grosser0695ee42013-09-17 03:30:31 +000087 SCEVAffinator(const ScopStmt *Stmt);
88 int getLoopDepth(const Loop *L);
Tobias Grosser60b54f12011-11-08 15:41:28 +000089
Tobias Grosser0695ee42013-09-17 03:30:31 +000090 __isl_give isl_pw_aff *visit(const SCEV *Expr);
91 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
92 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
93 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
94 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
95 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
96 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
97 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
98 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
99 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
100 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
101 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
Tobias Grosser60b54f12011-11-08 15:41:28 +0000102
Tobias Grosser0695ee42013-09-17 03:30:31 +0000103 friend struct SCEVVisitor<SCEVAffinator, isl_pw_aff *>;
104};
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000105
Tobias Grosser0695ee42013-09-17 03:30:31 +0000106SCEVAffinator::SCEVAffinator(const ScopStmt *Stmt)
107 : Ctx(Stmt->getIslCtx()), NbLoopSpaces(Stmt->getNumIterators()),
108 S(Stmt->getParent()) {}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000109
Tobias Grosser0695ee42013-09-17 03:30:31 +0000110__isl_give isl_pw_aff *SCEVAffinator::getPwAff(ScopStmt *Stmt,
111 const SCEV *Scev) {
112 Scop *S = Stmt->getParent();
113 const Region *Reg = &S->getRegion();
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000114
Tobias Grosser0695ee42013-09-17 03:30:31 +0000115 S->addParams(getParamsInAffineExpr(Reg, Scev, *S->getSE()));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000116
Tobias Grosser0695ee42013-09-17 03:30:31 +0000117 SCEVAffinator Affinator(Stmt);
118 return Affinator.visit(Scev);
119}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000120
Tobias Grosser0695ee42013-09-17 03:30:31 +0000121__isl_give isl_pw_aff *SCEVAffinator::visit(const SCEV *Expr) {
122 // In case the scev is a valid parameter, we do not further analyze this
123 // expression, but create a new parameter in the isl_pw_aff. This allows us
124 // to treat subexpressions that we cannot translate into an piecewise affine
125 // expression, as constant parameters of the piecewise affine expression.
126 if (isl_id *Id = S->getIdForParam(Expr)) {
127 isl_space *Space = isl_space_set_alloc(Ctx, 1, NbLoopSpaces);
128 Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000129
Tobias Grosser0695ee42013-09-17 03:30:31 +0000130 isl_set *Domain = isl_set_universe(isl_space_copy(Space));
131 isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
132 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000133
134 return isl_pw_aff_alloc(Domain, Affine);
135 }
136
Tobias Grosser0695ee42013-09-17 03:30:31 +0000137 return SCEVVisitor<SCEVAffinator, isl_pw_aff *>::visit(Expr);
138}
139
Tobias Grosser0d170132013-10-03 13:09:19 +0000140__isl_give isl_pw_aff *SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
Tobias Grosser0695ee42013-09-17 03:30:31 +0000141 ConstantInt *Value = Expr->getValue();
142 isl_val *v;
143
144 // LLVM does not define if an integer value is interpreted as a signed or
145 // unsigned value. Hence, without further information, it is unknown how
146 // this value needs to be converted to GMP. At the moment, we only support
147 // signed operations. So we just interpret it as signed. Later, there are
148 // two options:
149 //
150 // 1. We always interpret any value as signed and convert the values on
151 // demand.
152 // 2. We pass down the signedness of the calculation and use it to interpret
153 // this constant correctly.
154 v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
155
156 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
157 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(Space));
158 isl_aff *Affine = isl_aff_zero_on_domain(ls);
159 isl_set *Domain = isl_set_universe(Space);
160
161 Affine = isl_aff_add_constant_val(Affine, v);
162
163 return isl_pw_aff_alloc(Domain, Affine);
164}
165
166__isl_give isl_pw_aff *
167SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
168 llvm_unreachable("SCEVTruncateExpr not yet supported");
169}
170
171__isl_give isl_pw_aff *
172SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
173 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
174}
175
176__isl_give isl_pw_aff *
177SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
178 // Assuming the value is signed, a sign extension is basically a noop.
179 // TODO: Reconsider this as soon as we support unsigned values.
180 return visit(Expr->getOperand());
181}
182
183__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
184 isl_pw_aff *Sum = visit(Expr->getOperand(0));
185
186 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
187 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
188 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000189 }
190
Tobias Grosser0695ee42013-09-17 03:30:31 +0000191 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000192
Tobias Grosser0695ee42013-09-17 03:30:31 +0000193 return Sum;
194}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000195
Tobias Grosser0695ee42013-09-17 03:30:31 +0000196__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
197 isl_pw_aff *Product = visit(Expr->getOperand(0));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000198
Tobias Grosser0695ee42013-09-17 03:30:31 +0000199 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
200 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
201
202 if (!isl_pw_aff_is_cst(Product) && !isl_pw_aff_is_cst(NextOperand)) {
203 isl_pw_aff_free(Product);
204 isl_pw_aff_free(NextOperand);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000205 return nullptr;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000206 }
207
Tobias Grosser0695ee42013-09-17 03:30:31 +0000208 Product = isl_pw_aff_mul(Product, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000209 }
210
Tobias Grosser0695ee42013-09-17 03:30:31 +0000211 // TODO: Check for NSW and NUW.
212 return Product;
213}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000214
Tobias Grosser0695ee42013-09-17 03:30:31 +0000215__isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
216 llvm_unreachable("SCEVUDivExpr not yet supported");
217}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000218
Tobias Grosser0695ee42013-09-17 03:30:31 +0000219__isl_give isl_pw_aff *
220SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
221 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000222
Tobias Grosser0695ee42013-09-17 03:30:31 +0000223 // Directly generate isl_pw_aff for Expr if 'start' is zero.
224 if (Expr->getStart()->isZero()) {
225 assert(S->getRegion().contains(Expr->getLoop()) &&
226 "Scop does not contain the loop referenced in this AddRec");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000227
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000228 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser0695ee42013-09-17 03:30:31 +0000229 isl_pw_aff *Step = visit(Expr->getOperand(1));
230 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
231 isl_local_space *LocalSpace = isl_local_space_from_space(Space);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000232
Tobias Grosser0695ee42013-09-17 03:30:31 +0000233 int loopDimension = getLoopDepth(Expr->getLoop());
234
235 isl_aff *LAff = isl_aff_set_coefficient_si(
236 isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
237 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
238
239 // TODO: Do we need to check for NSW and NUW?
240 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000241 }
242
Tobias Grosser0695ee42013-09-17 03:30:31 +0000243 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
244 // if 'start' is not zero.
245 ScalarEvolution &SE = *S->getSE();
246 const SCEV *ZeroStartExpr = SE.getAddRecExpr(
247 SE.getConstant(Expr->getStart()->getType(), 0),
248 Expr->getStepRecurrence(SE), Expr->getLoop(), SCEV::FlagAnyWrap);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000249
Tobias Grosser0695ee42013-09-17 03:30:31 +0000250 isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
251 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000252
Tobias Grosser0695ee42013-09-17 03:30:31 +0000253 return isl_pw_aff_add(ZeroStartResult, Start);
254}
255
256__isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
257 isl_pw_aff *Max = visit(Expr->getOperand(0));
258
259 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
260 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
261 Max = isl_pw_aff_max(Max, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000262 }
263
Tobias Grosser0695ee42013-09-17 03:30:31 +0000264 return Max;
265}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000266
Tobias Grosser0695ee42013-09-17 03:30:31 +0000267__isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
268 llvm_unreachable("SCEVUMaxExpr not yet supported");
269}
270
271__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
Tobias Grosserf4daf342014-08-16 09:08:55 +0000272 llvm_unreachable("Unknowns are always parameters");
Tobias Grosser0695ee42013-09-17 03:30:31 +0000273}
274
275int SCEVAffinator::getLoopDepth(const Loop *L) {
276 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
277 assert(outerLoop && "Scop does not contain this loop");
278 return L->getLoopDepth() - outerLoop->getLoopDepth();
279}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000280
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000281ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *AccessType, isl_ctx *Ctx,
282 const SmallVector<const SCEV *, 4> &DimensionSizes)
283 : BasePtr(BasePtr), AccessType(AccessType), DimensionSizes(DimensionSizes) {
284 const std::string BasePtrName = getIslCompatibleName("MemRef_", BasePtr, "");
285 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
286}
287
288ScopArrayInfo::~ScopArrayInfo() { isl_id_free(Id); }
289
290isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
291
292void ScopArrayInfo::dump() const { print(errs()); }
293
294void ScopArrayInfo::print(raw_ostream &OS) const {
295 OS << "ScopArrayInfo:\n";
296 OS << " Base: " << *getBasePtr() << "\n";
297 OS << " Type: " << *getType() << "\n";
298 OS << " Dimension Sizes:\n";
299 for (unsigned u = 0; u < getNumberOfDimensions(); u++)
300 OS << " " << u << ") " << *DimensionSizes[u] << "\n";
301 OS << "\n";
302}
303
304const ScopArrayInfo *
305ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
306 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
307 assert(Id && "Output dimension didn't have an ID");
308 return getFromId(Id);
309}
310
311const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
312 void *User = isl_id_get_user(Id);
313 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
314 isl_id_free(Id);
315 return SAI;
316}
317
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000318const std::string
319MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
320 switch (RT) {
321 case MemoryAccess::RT_NONE:
322 llvm_unreachable("Requested a reduction operator string for a memory "
323 "access which isn't a reduction");
324 case MemoryAccess::RT_ADD:
325 return "+";
326 case MemoryAccess::RT_MUL:
327 return "*";
328 case MemoryAccess::RT_BOR:
329 return "|";
330 case MemoryAccess::RT_BXOR:
331 return "^";
332 case MemoryAccess::RT_BAND:
333 return "&";
334 }
335 llvm_unreachable("Unknown reduction type");
336 return "";
337}
338
Johannes Doerfertf6183392014-07-01 20:52:51 +0000339/// @brief Return the reduction type for a given binary operator
340static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
341 const Instruction *Load) {
342 if (!BinOp)
343 return MemoryAccess::RT_NONE;
344 switch (BinOp->getOpcode()) {
345 case Instruction::FAdd:
346 if (!BinOp->hasUnsafeAlgebra())
347 return MemoryAccess::RT_NONE;
348 // Fall through
349 case Instruction::Add:
350 return MemoryAccess::RT_ADD;
351 case Instruction::Or:
352 return MemoryAccess::RT_BOR;
353 case Instruction::Xor:
354 return MemoryAccess::RT_BXOR;
355 case Instruction::And:
356 return MemoryAccess::RT_BAND;
357 case Instruction::FMul:
358 if (!BinOp->hasUnsafeAlgebra())
359 return MemoryAccess::RT_NONE;
360 // Fall through
361 case Instruction::Mul:
362 if (DisableMultiplicativeReductions)
363 return MemoryAccess::RT_NONE;
364 return MemoryAccess::RT_MUL;
365 default:
366 return MemoryAccess::RT_NONE;
367 }
368}
Tobias Grosser75805372011-04-29 06:27:02 +0000369//===----------------------------------------------------------------------===//
370
371MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000372 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000373 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000374}
375
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000376static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
377 switch (Access.getType()) {
378 case IRAccess::READ:
379 return MemoryAccess::READ;
380 case IRAccess::MUST_WRITE:
381 return MemoryAccess::MUST_WRITE;
382 case IRAccess::MAY_WRITE:
383 return MemoryAccess::MAY_WRITE;
384 }
385 llvm_unreachable("Unknown IRAccess type!");
386}
387
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000388const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
389 isl_id *ArrayId = getArrayId();
390 void *User = isl_id_get_user(ArrayId);
391 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
392 isl_id_free(ArrayId);
393 return SAI;
394}
395
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000396isl_id *MemoryAccess::getArrayId() const {
397 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
398}
399
Johannes Doerferta99130f2014-10-13 12:58:03 +0000400isl_pw_multi_aff *
401MemoryAccess::applyScheduleToAccessRelation(isl_union_map *USchedule) const {
402 isl_map *Schedule, *ScheduledAccRel;
403 isl_union_set *UDomain;
404
405 UDomain = isl_union_set_from_set(getStatement()->getDomain());
406 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
407 Schedule = isl_map_from_union_map(USchedule);
408 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
409 return isl_pw_multi_aff_from_map(ScheduledAccRel);
410}
411
412isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000413 return isl_map_copy(AccessRelation);
414}
415
Johannes Doerferta99130f2014-10-13 12:58:03 +0000416std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000417 return stringFromIslObj(AccessRelation);
418}
419
Johannes Doerferta99130f2014-10-13 12:58:03 +0000420__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000421 return isl_map_get_space(AccessRelation);
422}
423
Tobias Grosser5d453812011-10-06 00:04:11 +0000424isl_map *MemoryAccess::getNewAccessRelation() const {
425 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000426}
427
428isl_basic_map *MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000429 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000430 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000431
Tobias Grosser084d8f72012-05-29 09:29:44 +0000432 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000433 isl_basic_set_universe(Statement->getDomainSpace()),
434 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000435}
436
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000437// Formalize no out-of-bound access assumption
438//
439// When delinearizing array accesses we optimistically assume that the
440// delinearized accesses do not access out of bound locations (the subscript
441// expression of each array evaluates for each statement instance that is
442// executed to a value that is larger than zero and strictly smaller than the
443// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000444// dimension for which we do not need to assume any upper bound. At this point
445// we formalize this assumption to ensure that at code generation time the
446// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000447//
448// To find the set of constraints necessary to avoid out of bound accesses, we
449// first build the set of data locations that are not within array bounds. We
450// then apply the reverse access relation to obtain the set of iterations that
451// may contain invalid accesses and reduce this set of iterations to the ones
452// that are actually executed by intersecting them with the domain of the
453// statement. If we now project out all loop dimensions, we obtain a set of
454// parameters that may cause statement instances to be executed that may
455// possibly yield out of bound memory accesses. The complement of these
456// constraints is the set of constraints that needs to be assumed to ensure such
457// statement instances are never executed.
458void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000459 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000460 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000461 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000462 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
463 isl_pw_aff *Var =
464 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
465 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
466
467 isl_set *DimOutside;
468
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000469 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
470 isl_pw_aff *SizeE = SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000471
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000472 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
473 Statement->getNumIterators());
474 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
475 isl_space_dim(Space, isl_dim_set));
476 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
477 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000478
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000479 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000480
481 Outside = isl_set_union(Outside, DimOutside);
482 }
483
484 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
485 Outside = isl_set_intersect(Outside, Statement->getDomain());
486 Outside = isl_set_params(Outside);
487 Outside = isl_set_complement(Outside);
488 Statement->getParent()->addAssumption(Outside);
489 isl_space_free(Space);
490}
491
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000492MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000493 ScopStmt *Statement, const ScopArrayInfo *SAI)
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000494 : AccType(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000495 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000496
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000497 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000498 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000499 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000500
501 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000502
Tobias Grossera1879642011-12-20 10:43:14 +0000503 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000504 // We overapproximate non-affine accesses with a possible access to the
505 // whole array. For read accesses it does not make a difference, if an
506 // access must or may happen. However, for write accesses it is important to
507 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000508 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000509 AccessRelation =
510 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000511 return;
512 }
513
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000514 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000515 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000516
Tobias Grosser79baa212014-04-10 08:38:02 +0000517 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000518 isl_pw_aff *Affine =
519 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000520
Sebastian Pop422e33f2014-06-03 18:16:31 +0000521 if (Size == 1) {
522 // For the non delinearized arrays, divide the access function of the last
523 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000524 //
525 // A stride one array access in C expressed as A[i] is expressed in
526 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
527 // two subsequent values of 'i' index two values that are stored next to
528 // each other in memory. By this division we make this characteristic
529 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000530 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000531 Affine = isl_pw_aff_scale_down_val(Affine, v);
532 }
533
534 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
535
Tobias Grosser79baa212014-04-10 08:38:02 +0000536 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000537 }
538
Tobias Grosser79baa212014-04-10 08:38:02 +0000539 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000540 AccessRelation = isl_map_set_tuple_id(
541 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000542 AccessRelation =
543 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
544
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000545 assumeNoOutOfBound(Access);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000546 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000547}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000548
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000549void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000550 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000551 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000552}
553
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000554const std::string MemoryAccess::getReductionOperatorStr() const {
555 return MemoryAccess::getReductionOperatorStr(getReductionType());
556}
557
Johannes Doerfertf6183392014-07-01 20:52:51 +0000558raw_ostream &polly::operator<<(raw_ostream &OS,
559 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000560 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000561 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000562 else
563 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000564 return OS;
565}
566
Tobias Grosser75805372011-04-29 06:27:02 +0000567void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000568 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000569 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000570 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000571 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000572 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000573 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000574 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000575 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000576 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000577 break;
578 }
Johannes Doerfertf6183392014-07-01 20:52:51 +0000579 OS << "[Reduction Type: " << getReductionType() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000580 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000581}
582
Tobias Grosser74394f02013-01-14 22:40:23 +0000583void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000584
585// Create a map in the size of the provided set domain, that maps from the
586// one element of the provided set domain to another element of the provided
587// set domain.
588// The mapping is limited to all points that are equal in all but the last
589// dimension and for which the last dimension of the input is strict smaller
590// than the last dimension of the output.
591//
592// getEqualAndLarger(set[i0, i1, ..., iX]):
593//
594// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
595// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
596//
Tobias Grosserf5338802011-10-06 00:03:35 +0000597static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000598 isl_space *Space = isl_space_map_from_set(setDomain);
599 isl_map *Map = isl_map_universe(isl_space_copy(Space));
600 isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000601 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000602
603 // Set all but the last dimension to be equal for the input and output
604 //
605 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
606 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000607 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000608 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000609
610 // Set the last dimension of the input to be strict smaller than the
611 // last dimension of the output.
612 //
613 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
614 //
Tobias Grosseredab1352013-06-21 06:41:31 +0000615 isl_val *v;
616 isl_ctx *Ctx = isl_map_get_ctx(Map);
Tobias Grosserf5338802011-10-06 00:03:35 +0000617 isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
Tobias Grosseredab1352013-06-21 06:41:31 +0000618 v = isl_val_int_from_si(Ctx, -1);
619 c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
620 v = isl_val_int_from_si(Ctx, 1);
621 c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
622 v = isl_val_int_from_si(Ctx, -1);
623 c = isl_constraint_set_constant_val(c, v);
Tobias Grosser75805372011-04-29 06:27:02 +0000624
Tobias Grosserc327932c2012-02-01 14:23:36 +0000625 Map = isl_map_add_constraint(Map, c);
Tobias Grosser75805372011-04-29 06:27:02 +0000626
Tobias Grosser23b36662011-10-17 08:32:36 +0000627 isl_local_space_free(MapLocalSpace);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000628 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000629}
630
Sebastian Popa00a0292012-12-18 07:46:06 +0000631isl_set *MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000632 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000633 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000634 isl_space *Space = isl_space_range(isl_map_get_space(S));
635 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000636
Sebastian Popa00a0292012-12-18 07:46:06 +0000637 S = isl_map_reverse(S);
638 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000639
Sebastian Popa00a0292012-12-18 07:46:06 +0000640 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
641 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
642 NextScatt = isl_map_apply_domain(NextScatt, S);
643 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000644
Sebastian Popa00a0292012-12-18 07:46:06 +0000645 isl_set *Deltas = isl_map_deltas(NextScatt);
646 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000647}
648
Sebastian Popa00a0292012-12-18 07:46:06 +0000649bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000650 int StrideWidth) const {
651 isl_set *Stride, *StrideX;
652 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000653
Sebastian Popa00a0292012-12-18 07:46:06 +0000654 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000655 StrideX = isl_set_universe(isl_set_get_space(Stride));
656 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
657 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000658
Tobias Grosser28dd4862012-01-24 16:42:16 +0000659 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000660 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000661
Tobias Grosser28dd4862012-01-24 16:42:16 +0000662 return IsStrideX;
663}
664
Sebastian Popa00a0292012-12-18 07:46:06 +0000665bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
666 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000667}
668
Tobias Grosser79baa212014-04-10 08:38:02 +0000669bool MemoryAccess::isScalar() const {
670 return isl_map_n_out(AccessRelation) == 0;
671}
672
Sebastian Popa00a0292012-12-18 07:46:06 +0000673bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
674 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000675}
676
Tobias Grosser5d453812011-10-06 00:04:11 +0000677void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000678 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000679 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000680}
Tobias Grosser75805372011-04-29 06:27:02 +0000681
682//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000683
Tobias Grosser74394f02013-01-14 22:40:23 +0000684isl_map *ScopStmt::getScattering() const { return isl_map_copy(Scattering); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000685
Tobias Grosser37eb4222014-02-20 21:43:54 +0000686void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
687 assert(isl_set_is_subset(NewDomain, Domain) &&
688 "New domain is not a subset of old domain!");
689 isl_set_free(Domain);
690 Domain = NewDomain;
691 Scattering = isl_map_intersect_domain(Scattering, isl_set_copy(Domain));
692}
693
Tobias Grossercf3942d2011-10-06 00:04:05 +0000694void ScopStmt::setScattering(isl_map *NewScattering) {
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000695 assert(NewScattering && "New scattering is nullptr");
Tobias Grosserb76f38532011-08-20 11:11:25 +0000696 isl_map_free(Scattering);
Tobias Grossercf3942d2011-10-06 00:04:05 +0000697 Scattering = NewScattering;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000698}
699
Tobias Grosser75805372011-04-29 06:27:02 +0000700void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000701 unsigned NbIterators = getNumIterators();
702 unsigned NbScatteringDims = Parent.getMaxLoopDepth() * 2 + 1;
703
Tobias Grosser084d8f72012-05-29 09:29:44 +0000704 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScatteringDims);
Tobias Grosserf5338802011-10-06 00:03:35 +0000705 Space = isl_space_set_tuple_name(Space, isl_dim_out, "scattering");
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000706
Tobias Grosser084d8f72012-05-29 09:29:44 +0000707 Scattering = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
708 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000709
710 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000711 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosserabfbe632013-02-05 12:09:06 +0000712 Scattering =
713 isl_map_equate(Scattering, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000714
715 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000716 for (unsigned i = 0; i < NbIterators + 1; ++i)
717 Scattering = isl_map_fix_si(Scattering, isl_dim_out, 2 * i, Scatter[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000718
719 // Fill scattering dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000720 for (unsigned i = 2 * NbIterators + 1; i < NbScatteringDims; ++i)
721 Scattering = isl_map_fix_si(Scattering, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000722
Tobias Grosser37487052011-10-06 00:03:42 +0000723 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000724}
725
Johannes Doerfert75bd66e2014-10-31 23:16:02 +0000726void ScopStmt::buildAccesses(TempScop &tempScop) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000727 for (const auto &AccessPair : *tempScop.getAccessFunctions(BB)) {
728 const IRAccess &Access = AccessPair.first;
729 Instruction *AccessInst = AccessPair.second;
730
731 const ScopArrayInfo *SAI =
732 getParent()->getOrCreateScopArrayInfo(Access, AccessInst);
733 MemAccs.push_back(new MemoryAccess(Access, AccessInst, this, SAI));
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000734
735 // We do not track locations for scalar memory accesses at the moment.
736 //
737 // We do not have a use for this information at the moment. If we need this
738 // at some point, the "instruction -> access" mapping needs to be enhanced
739 // as a single instruction could then possibly perform multiple accesses.
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000740 if (!Access.isScalar()) {
741 assert(!InstructionToAccess.count(AccessInst) &&
Tobias Grosser3fc91542014-02-20 21:43:45 +0000742 "Unexpected 1-to-N mapping on instruction to access map!");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000743 InstructionToAccess[AccessInst] = MemAccs.back();
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000744 }
Tobias Grosser75805372011-04-29 06:27:02 +0000745 }
746}
747
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000748void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000749 for (MemoryAccess *MA : *this)
750 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000751
752 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
753 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
754}
755
Tobias Grosser65b00582011-11-08 15:41:19 +0000756__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000757 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
758 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000759
Tobias Grosserd2795d02011-08-18 07:51:40 +0000760 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000761 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000762 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000763 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000764 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000765 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000766 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000767 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000768 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000769 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000770 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000771 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000772 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000773 case ICmpInst::ICMP_ULT:
774 case ICmpInst::ICMP_UGT:
775 case ICmpInst::ICMP_ULE:
Tobias Grosser75805372011-04-29 06:27:02 +0000776 case ICmpInst::ICMP_UGE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000777 llvm_unreachable("Unsigned comparisons not yet supported");
Tobias Grosser75805372011-04-29 06:27:02 +0000778 default:
779 llvm_unreachable("Non integer predicate not supported");
780 }
Tobias Grosser75805372011-04-29 06:27:02 +0000781}
782
Tobias Grossere19661e2011-10-07 08:46:57 +0000783__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000784 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000785 isl_space *Space;
786 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000787
Tobias Grossere19661e2011-10-07 08:46:57 +0000788 Space = isl_set_get_space(Domain);
789 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000790
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000791 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000792 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000793 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000794 isl_pw_aff *IV =
795 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000796
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000797 // 0 <= IV.
798 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
799 Domain = isl_set_intersect(Domain, LowerBound);
800
801 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000802 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000803 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000804 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
805 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000806 Domain = isl_set_intersect(Domain, UpperBoundSet);
807 }
808
Tobias Grosserf5338802011-10-06 00:03:35 +0000809 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000810 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000811}
812
Tobias Grossere602a072013-05-07 07:30:56 +0000813__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
814 TempScop &tempScop,
815 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000816 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000817 *CurrentRegion = &CurRegion;
Tobias Grossere19661e2011-10-07 08:46:57 +0000818 const BasicBlock *BranchingBB = BB;
Tobias Grosser75805372011-04-29 06:27:02 +0000819
Tobias Grosser75805372011-04-29 06:27:02 +0000820 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000821 if (BranchingBB != CurrentRegion->getEntry()) {
822 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000823 for (const auto &C : *Condition) {
824 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000825 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000826 }
827 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000828 BranchingBB = CurrentRegion->getEntry();
829 CurrentRegion = CurrentRegion->getParent();
830 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000831
Tobias Grossere19661e2011-10-07 08:46:57 +0000832 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000833}
834
Tobias Grossere602a072013-05-07 07:30:56 +0000835__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
836 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000837 isl_space *Space;
838 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000839 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000840
841 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
842
Tobias Grosser084d8f72012-05-29 09:29:44 +0000843 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
844
Tobias Grossere19661e2011-10-07 08:46:57 +0000845 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000846 Domain = addLoopBoundsToDomain(Domain, tempScop);
847 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000848 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000849
850 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000851}
852
Tobias Grosser74394f02013-01-14 22:40:23 +0000853ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +0000854 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser75805372011-04-29 06:27:02 +0000855 SmallVectorImpl<unsigned> &Scatter)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000856 : Parent(parent), BB(&bb), IVS(Nest.size()), NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000857 // Setup the induction variables.
Sebastian Pop860e0212013-02-15 21:26:44 +0000858 for (unsigned i = 0, e = Nest.size(); i < e; ++i) {
Sebastian Pop27c10c62013-03-22 22:07:43 +0000859 if (!SCEVCodegen) {
860 PHINode *PN = Nest[i]->getCanonicalInductionVariable();
861 assert(PN && "Non canonical IV in Scop!");
Tobias Grosser826b2af2013-03-21 16:14:50 +0000862 IVS[i] = PN;
Sebastian Pop27c10c62013-03-22 22:07:43 +0000863 }
Sebastian Pop860e0212013-02-15 21:26:44 +0000864 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000865 }
866
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000867 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +0000868
Tobias Grossere19661e2011-10-07 08:46:57 +0000869 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000870 buildScattering(Scatter);
Johannes Doerfert75bd66e2014-10-31 23:16:02 +0000871 buildAccesses(tempScop);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000872 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000873}
874
Johannes Doerferte58a0122014-06-27 20:31:28 +0000875/// @brief Collect loads which might form a reduction chain with @p StoreMA
876///
877/// Check if the stored value for @p StoreMA is a binary operator with one or
878/// two loads as operands. If the binary operand is commutative & associative,
879/// used only once (by @p StoreMA) and its load operands are also used only
880/// once, we have found a possible reduction chain. It starts at an operand
881/// load and includes the binary operator and @p StoreMA.
882///
883/// Note: We allow only one use to ensure the load and binary operator cannot
884/// escape this block or into any other store except @p StoreMA.
885void ScopStmt::collectCandiateReductionLoads(
886 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
887 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
888 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000889 return;
890
891 // Skip if there is not one binary operator between the load and the store
892 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +0000893 if (!BinOp)
894 return;
895
896 // Skip if the binary operators has multiple uses
897 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000898 return;
899
900 // Skip if the opcode of the binary operator is not commutative/associative
901 if (!BinOp->isCommutative() || !BinOp->isAssociative())
902 return;
903
Johannes Doerfert9890a052014-07-01 00:32:29 +0000904 // Skip if the binary operator is outside the current SCoP
905 if (BinOp->getParent() != Store->getParent())
906 return;
907
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000908 // Skip if it is a multiplicative reduction and we disabled them
909 if (DisableMultiplicativeReductions &&
910 (BinOp->getOpcode() == Instruction::Mul ||
911 BinOp->getOpcode() == Instruction::FMul))
912 return;
913
Johannes Doerferte58a0122014-06-27 20:31:28 +0000914 // Check the binary operator operands for a candidate load
915 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
916 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
917 if (!PossibleLoad0 && !PossibleLoad1)
918 return;
919
920 // A load is only a candidate if it cannot escape (thus has only this use)
921 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000922 if (PossibleLoad0->getParent() == Store->getParent())
923 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000924 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000925 if (PossibleLoad1->getParent() == Store->getParent())
926 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000927}
928
929/// @brief Check for reductions in this ScopStmt
930///
931/// Iterate over all store memory accesses and check for valid binary reduction
932/// like chains. For all candidates we check if they have the same base address
933/// and there are no other accesses which overlap with them. The base address
934/// check rules out impossible reductions candidates early. The overlap check,
935/// together with the "only one user" check in collectCandiateReductionLoads,
936/// guarantees that none of the intermediate results will escape during
937/// execution of the loop nest. We basically check here that no other memory
938/// access can access the same memory as the potential reduction.
939void ScopStmt::checkForReductions() {
940 SmallVector<MemoryAccess *, 2> Loads;
941 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
942
943 // First collect candidate load-store reduction chains by iterating over all
944 // stores and collecting possible reduction loads.
945 for (MemoryAccess *StoreMA : MemAccs) {
946 if (StoreMA->isRead())
947 continue;
948
949 Loads.clear();
950 collectCandiateReductionLoads(StoreMA, Loads);
951 for (MemoryAccess *LoadMA : Loads)
952 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
953 }
954
955 // Then check each possible candidate pair.
956 for (const auto &CandidatePair : Candidates) {
957 bool Valid = true;
958 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
959 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
960
961 // Skip those with obviously unequal base addresses.
962 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
963 isl_map_free(LoadAccs);
964 isl_map_free(StoreAccs);
965 continue;
966 }
967
968 // And check if the remaining for overlap with other memory accesses.
969 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
970 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
971 isl_set *AllAccs = isl_map_range(AllAccsRel);
972
973 for (MemoryAccess *MA : MemAccs) {
974 if (MA == CandidatePair.first || MA == CandidatePair.second)
975 continue;
976
977 isl_map *AccRel =
978 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
979 isl_set *Accs = isl_map_range(AccRel);
980
981 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
982 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
983 Valid = Valid && isl_set_is_empty(OverlapAccs);
984 isl_set_free(OverlapAccs);
985 }
986 }
987
988 isl_set_free(AllAccs);
989 if (!Valid)
990 continue;
991
Johannes Doerfertf6183392014-07-01 20:52:51 +0000992 const LoadInst *Load =
993 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
994 MemoryAccess::ReductionType RT =
995 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
996
Johannes Doerferte58a0122014-06-27 20:31:28 +0000997 // If no overlapping access was found we mark the load and store as
998 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000999 CandidatePair.first->markAsReductionLike(RT);
1000 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001001 }
Tobias Grosser75805372011-04-29 06:27:02 +00001002}
1003
Tobias Grosser74394f02013-01-14 22:40:23 +00001004std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001005
1006std::string ScopStmt::getScatteringStr() const {
Tobias Grossercf3942d2011-10-06 00:04:05 +00001007 return stringFromIslObj(Scattering);
Tobias Grosser75805372011-04-29 06:27:02 +00001008}
1009
Tobias Grosser74394f02013-01-14 22:40:23 +00001010unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001011
1012unsigned ScopStmt::getNumIterators() const {
1013 // The final read has one dimension with one element.
1014 if (!BB)
1015 return 1;
1016
Sebastian Pop860e0212013-02-15 21:26:44 +00001017 return NestLoops.size();
Tobias Grosser75805372011-04-29 06:27:02 +00001018}
1019
1020unsigned ScopStmt::getNumScattering() const {
1021 return isl_map_dim(Scattering, isl_dim_out);
1022}
1023
1024const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1025
Tobias Grosserabfbe632013-02-05 12:09:06 +00001026const PHINode *
1027ScopStmt::getInductionVariableForDimension(unsigned Dimension) const {
Sebastian Popf30d3b22013-02-15 21:26:48 +00001028 return IVS[Dimension];
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001029}
1030
1031const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001032 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001033}
1034
Tobias Grosser74394f02013-01-14 22:40:23 +00001035isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001036
Tobias Grosser74394f02013-01-14 22:40:23 +00001037isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001038
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001039isl_space *ScopStmt::getDomainSpace() const {
1040 return isl_set_get_space(Domain);
1041}
1042
Tobias Grosser74394f02013-01-14 22:40:23 +00001043isl_id *ScopStmt::getDomainId() const { return isl_set_get_tuple_id(Domain); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001044
Tobias Grosser75805372011-04-29 06:27:02 +00001045ScopStmt::~ScopStmt() {
1046 while (!MemAccs.empty()) {
1047 delete MemAccs.back();
1048 MemAccs.pop_back();
1049 }
1050
1051 isl_set_free(Domain);
1052 isl_map_free(Scattering);
1053}
1054
1055void ScopStmt::print(raw_ostream &OS) const {
1056 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001057 OS.indent(12) << "Domain :=\n";
1058
1059 if (Domain) {
1060 OS.indent(16) << getDomainStr() << ";\n";
1061 } else
1062 OS.indent(16) << "n/a\n";
1063
1064 OS.indent(12) << "Scattering :=\n";
1065
1066 if (Domain) {
1067 OS.indent(16) << getScatteringStr() << ";\n";
1068 } else
1069 OS.indent(16) << "n/a\n";
1070
Tobias Grosser083d3d32014-06-28 08:59:45 +00001071 for (MemoryAccess *Access : MemAccs)
1072 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001073}
1074
1075void ScopStmt::dump() const { print(dbgs()); }
1076
1077//===----------------------------------------------------------------------===//
1078/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001079
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001080void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001081 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1082 isl_set_free(Context);
1083 Context = NewContext;
1084}
1085
Tobias Grosserabfbe632013-02-05 12:09:06 +00001086void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001087 for (const SCEV *Parameter : NewParameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001088 if (ParameterIds.find(Parameter) != ParameterIds.end())
1089 continue;
1090
1091 int dimension = Parameters.size();
1092
1093 Parameters.push_back(Parameter);
1094 ParameterIds[Parameter] = dimension;
1095 }
1096}
1097
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001098__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1099 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001100
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001101 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001102 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001103
Tobias Grosser8f99c162011-11-15 11:38:55 +00001104 std::string ParameterName;
1105
1106 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1107 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001108 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001109 }
1110
1111 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001112 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001113
Tobias Grosser20532b82014-04-11 17:56:49 +00001114 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1115 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001116}
Tobias Grosser75805372011-04-29 06:27:02 +00001117
Tobias Grosser6be480c2011-11-08 15:41:13 +00001118void Scop::buildContext() {
1119 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001120 Context = isl_set_universe(isl_space_copy(Space));
1121 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001122}
1123
Tobias Grosser18daaca2012-05-22 10:47:27 +00001124void Scop::addParameterBounds() {
1125 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
Tobias Grosseredab1352013-06-21 06:41:31 +00001126 isl_val *V;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001127 isl_id *Id;
1128 const SCEV *Scev;
1129 const IntegerType *T;
1130
1131 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserabfbe632013-02-05 12:09:06 +00001132 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001133 T = dyn_cast<IntegerType>(Scev->getType());
1134 isl_id_free(Id);
1135
1136 assert(T && "Not an integer type");
1137 int Width = T->getBitWidth();
1138
Tobias Grosseredab1352013-06-21 06:41:31 +00001139 V = isl_val_int_from_si(IslCtx, Width - 1);
1140 V = isl_val_2exp(V);
1141 V = isl_val_neg(V);
1142 Context = isl_set_lower_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001143
Tobias Grosseredab1352013-06-21 06:41:31 +00001144 V = isl_val_int_from_si(IslCtx, Width - 1);
1145 V = isl_val_2exp(V);
1146 V = isl_val_sub_ui(V, 1);
1147 Context = isl_set_upper_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001148 }
1149}
1150
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001151void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001152 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001153 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001154
Tobias Grosser083d3d32014-06-28 08:59:45 +00001155 for (const auto &ParamID : ParameterIds) {
1156 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001157 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001158 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001159 }
1160
1161 // Align the parameters of all data structures to the model.
1162 Context = isl_set_align_params(Context, Space);
1163
Tobias Grosser083d3d32014-06-28 08:59:45 +00001164 for (ScopStmt *Stmt : *this)
1165 Stmt->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001166}
1167
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001168void Scop::simplifyAssumedContext() {
1169 // The parameter constraints of the iteration domains give us a set of
1170 // constraints that need to hold for all cases where at least a single
1171 // statement iteration is executed in the whole scop. We now simplify the
1172 // assumed context under the assumption that such constraints hold and at
1173 // least a single statement iteration is executed. For cases where no
1174 // statement instances are executed, the assumptions we have taken about
1175 // the executed code do not matter and can be changed.
1176 //
1177 // WARNING: This only holds if the assumptions we have taken do not reduce
1178 // the set of statement instances that are executed. Otherwise we
1179 // may run into a case where the iteration domains suggest that
1180 // for a certain set of parameter constraints no code is executed,
1181 // but in the original program some computation would have been
1182 // performed. In such a case, modifying the run-time conditions and
1183 // possibly influencing the run-time check may cause certain scops
1184 // to not be executed.
1185 //
1186 // Example:
1187 //
1188 // When delinearizing the following code:
1189 //
1190 // for (long i = 0; i < 100; i++)
1191 // for (long j = 0; j < m; j++)
1192 // A[i+p][j] = 1.0;
1193 //
1194 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
1195 // otherwise we would access out of bound data. Now, knowing that code is
1196 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1197 AssumedContext =
1198 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
1199}
1200
Johannes Doerfertb164c792014-09-18 11:17:17 +00001201/// @brief Add the minimal/maximal access in @p Set to @p User.
1202static int buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
1203 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1204 isl_pw_multi_aff *MinPMA, *MaxPMA;
1205 isl_pw_aff *LastDimAff;
1206 isl_aff *OneAff;
1207 unsigned Pos;
1208
Johannes Doerfert9143d672014-09-27 11:02:39 +00001209 // Restrict the number of parameters involved in the access as the lexmin/
1210 // lexmax computation will take too long if this number is high.
1211 //
1212 // Experiments with a simple test case using an i7 4800MQ:
1213 //
1214 // #Parameters involved | Time (in sec)
1215 // 6 | 0.01
1216 // 7 | 0.04
1217 // 8 | 0.12
1218 // 9 | 0.40
1219 // 10 | 1.54
1220 // 11 | 6.78
1221 // 12 | 30.38
1222 //
1223 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1224 unsigned InvolvedParams = 0;
1225 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1226 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1227 InvolvedParams++;
1228
1229 if (InvolvedParams > RunTimeChecksMaxParameters) {
1230 isl_set_free(Set);
1231 return -1;
1232 }
1233 }
1234
Johannes Doerfertb164c792014-09-18 11:17:17 +00001235 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1236 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1237
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001238 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1239 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1240
Johannes Doerfertb164c792014-09-18 11:17:17 +00001241 // Adjust the last dimension of the maximal access by one as we want to
1242 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1243 // we test during code generation might now point after the end of the
1244 // allocated array but we will never dereference it anyway.
1245 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1246 "Assumed at least one output dimension");
1247 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1248 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1249 OneAff = isl_aff_zero_on_domain(
1250 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1251 OneAff = isl_aff_add_constant_si(OneAff, 1);
1252 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1253 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1254
1255 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1256
1257 isl_set_free(Set);
1258 return 0;
1259}
1260
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001261static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1262 isl_set *Domain = MA->getStatement()->getDomain();
1263 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1264 return isl_set_reset_tuple_id(Domain);
1265}
1266
Johannes Doerfert9143d672014-09-27 11:02:39 +00001267bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001268 // To create sound alias checks we perform the following steps:
1269 // o) Use the alias analysis and an alias set tracker to build alias sets
1270 // for all memory accesses inside the SCoP.
1271 // o) For each alias set we then map the aliasing pointers back to the
1272 // memory accesses we know, thus obtain groups of memory accesses which
1273 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001274 // o) We divide each group based on the domains of the minimal/maximal
1275 // accesses. That means two minimal/maximal accesses are only in a group
1276 // if their access domains intersect, otherwise they are in different
1277 // ones.
Johannes Doerfert13771732014-10-01 12:40:46 +00001278 // o) We split groups such that they contain at most one read only base
1279 // address.
1280 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfertb164c792014-09-18 11:17:17 +00001281 // and maximal accesses to each array in this group.
1282 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1283
1284 AliasSetTracker AST(AA);
1285
1286 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001287 DenseSet<Value *> HasWriteAccess;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001288 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001289
1290 // Skip statements with an empty domain as they will never be executed.
1291 isl_set *StmtDomain = Stmt->getDomain();
1292 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1293 isl_set_free(StmtDomain);
1294 if (StmtDomainEmpty)
1295 continue;
1296
Johannes Doerfertb164c792014-09-18 11:17:17 +00001297 for (MemoryAccess *MA : *Stmt) {
1298 if (MA->isScalar())
1299 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001300 if (!MA->isRead())
1301 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001302 Instruction *Acc = MA->getAccessInstruction();
1303 PtrToAcc[getPointerOperand(*Acc)] = MA;
1304 AST.add(Acc);
1305 }
1306 }
1307
1308 SmallVector<AliasGroupTy, 4> AliasGroups;
1309 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001310 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001311 continue;
1312 AliasGroupTy AG;
1313 for (auto PR : AS)
1314 AG.push_back(PtrToAcc[PR.getValue()]);
1315 assert(AG.size() > 1 &&
1316 "Alias groups should contain at least two accesses");
1317 AliasGroups.push_back(std::move(AG));
1318 }
1319
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001320 // Split the alias groups based on their domain.
1321 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1322 AliasGroupTy NewAG;
1323 AliasGroupTy &AG = AliasGroups[u];
1324 AliasGroupTy::iterator AGI = AG.begin();
1325 isl_set *AGDomain = getAccessDomain(*AGI);
1326 while (AGI != AG.end()) {
1327 MemoryAccess *MA = *AGI;
1328 isl_set *MADomain = getAccessDomain(MA);
1329 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1330 NewAG.push_back(MA);
1331 AGI = AG.erase(AGI);
1332 isl_set_free(MADomain);
1333 } else {
1334 AGDomain = isl_set_union(AGDomain, MADomain);
1335 AGI++;
1336 }
1337 }
1338 if (NewAG.size() > 1)
1339 AliasGroups.push_back(std::move(NewAG));
1340 isl_set_free(AGDomain);
1341 }
1342
Johannes Doerfert13771732014-10-01 12:40:46 +00001343 DenseMap<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
1344 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1345 for (AliasGroupTy &AG : AliasGroups) {
1346 NonReadOnlyBaseValues.clear();
1347 ReadOnlyPairs.clear();
1348
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001349 if (AG.size() < 2) {
1350 AG.clear();
1351 continue;
1352 }
1353
Johannes Doerfert13771732014-10-01 12:40:46 +00001354 for (auto II = AG.begin(); II != AG.end();) {
1355 Value *BaseAddr = (*II)->getBaseAddr();
1356 if (HasWriteAccess.count(BaseAddr)) {
1357 NonReadOnlyBaseValues.insert(BaseAddr);
1358 II++;
1359 } else {
1360 ReadOnlyPairs[BaseAddr].insert(*II);
1361 II = AG.erase(II);
1362 }
1363 }
1364
1365 // If we don't have read only pointers check if there are at least two
1366 // non read only pointers, otherwise clear the alias group.
1367 if (ReadOnlyPairs.empty()) {
1368 if (NonReadOnlyBaseValues.size() <= 1)
1369 AG.clear();
1370 continue;
1371 }
1372
1373 // If we don't have non read only pointers clear the alias group.
1374 if (NonReadOnlyBaseValues.empty()) {
1375 AG.clear();
1376 continue;
1377 }
1378
1379 // If we have both read only and non read only base pointers we combine
1380 // the non read only ones with exactly one read only one at a time into a
1381 // new alias group and clear the old alias group in the end.
1382 for (const auto &ReadOnlyPair : ReadOnlyPairs) {
1383 AliasGroupTy AGNonReadOnly = AG;
1384 for (MemoryAccess *MA : ReadOnlyPair.second)
1385 AGNonReadOnly.push_back(MA);
1386 AliasGroups.push_back(std::move(AGNonReadOnly));
1387 }
1388 AG.clear();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001389 }
1390
Johannes Doerfert9143d672014-09-27 11:02:39 +00001391 bool Valid = true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001392 for (AliasGroupTy &AG : AliasGroups) {
Johannes Doerfert13771732014-10-01 12:40:46 +00001393 if (AG.empty())
1394 continue;
1395
Johannes Doerfertb164c792014-09-18 11:17:17 +00001396 MinMaxVectorTy *MinMaxAccesses = new MinMaxVectorTy();
1397 MinMaxAccesses->reserve(AG.size());
1398
1399 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
1400 for (MemoryAccess *MA : AG)
1401 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1402 Accesses = isl_union_map_intersect_domain(Accesses, getDomains());
1403
1404 isl_union_set *Locations = isl_union_map_range(Accesses);
1405 Locations = isl_union_set_intersect_params(Locations, getAssumedContext());
1406 Locations = isl_union_set_coalesce(Locations);
1407 Locations = isl_union_set_detect_equalities(Locations);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001408 Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
1409 MinMaxAccesses));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001410 isl_union_set_free(Locations);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001411 MinMaxAliasGroups.push_back(MinMaxAccesses);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001412
1413 if (!Valid)
1414 break;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001415 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001416
1417 return Valid;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001418}
1419
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001420static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI) {
1421 unsigned MinLD = INT_MAX, MaxLD = 0;
1422 for (BasicBlock *BB : R.blocks()) {
1423 if (Loop *L = LI.getLoopFor(BB)) {
1424 unsigned LD = L->getLoopDepth();
1425 MinLD = std::min(MinLD, LD);
1426 MaxLD = std::max(MaxLD, LD);
1427 }
1428 }
1429
1430 // Handle the case that there is no loop in the SCoP first.
1431 if (MaxLD == 0)
1432 return 1;
1433
1434 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1435 assert(MaxLD >= MinLD &&
1436 "Maximal loop depth was smaller than mininaml loop depth?");
1437 return MaxLD - MinLD + 1;
1438}
1439
Tobias Grosser0e27e242011-10-06 00:03:48 +00001440Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
1441 isl_ctx *Context)
Tobias Grosserabfbe632013-02-05 12:09:06 +00001442 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()),
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001443 MaxLoopDepth(getMaxLoopDepthInRegion(tempScop.getMaxRegion(), LI)) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001444 IslCtx = Context;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001445 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001446
Tobias Grosserabfbe632013-02-05 12:09:06 +00001447 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001448 SmallVector<unsigned, 8> Scatter;
1449
1450 Scatter.assign(MaxLoopDepth + 1, 0);
1451
1452 // Build the iteration domain, access functions and scattering functions
1453 // traversing the region tree.
1454 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00001455
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001456 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001457 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001458 simplifyAssumedContext();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001459
Tobias Grosser75805372011-04-29 06:27:02 +00001460 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1461}
1462
1463Scop::~Scop() {
1464 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001465 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001466
1467 // Free the statements;
Tobias Grosser083d3d32014-06-28 08:59:45 +00001468 for (ScopStmt *Stmt : *this)
1469 delete Stmt;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001470
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001471 // Free the ScopArrayInfo objects.
1472 for (auto &ScopArrayInfoPair : ScopArrayInfoMap)
1473 delete ScopArrayInfoPair.second;
1474
Johannes Doerfertb164c792014-09-18 11:17:17 +00001475 // Free the alias groups
1476 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1477 for (MinMaxAccessTy &MMA : *MinMaxAccesses) {
1478 isl_pw_multi_aff_free(MMA.first);
1479 isl_pw_multi_aff_free(MMA.second);
1480 }
1481 delete MinMaxAccesses;
1482 }
Tobias Grosser75805372011-04-29 06:27:02 +00001483}
1484
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001485const ScopArrayInfo *Scop::getOrCreateScopArrayInfo(const IRAccess &Access,
1486 Instruction *AccessInst) {
1487 Value *BasePtr = Access.getBase();
1488 const ScopArrayInfo *&SAI = ScopArrayInfoMap[BasePtr];
1489 if (!SAI) {
1490 Type *AccessType = getPointerOperand(*AccessInst)->getType();
1491 SAI = new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Access.Sizes);
1492 }
1493 return SAI;
1494}
1495
1496const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr) {
1497 const SCEV *PtrSCEV = SE->getSCEV(BasePtr);
1498 const SCEVUnknown *PtrBaseSCEV =
1499 cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
1500 const ScopArrayInfo *SAI = ScopArrayInfoMap[PtrBaseSCEV->getValue()];
1501 assert(SAI && "No ScopArrayInfo available for this base pointer");
1502 return SAI;
1503}
1504
Tobias Grosser74394f02013-01-14 22:40:23 +00001505std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001506std::string Scop::getAssumedContextStr() const {
1507 return stringFromIslObj(AssumedContext);
1508}
Tobias Grosser75805372011-04-29 06:27:02 +00001509
1510std::string Scop::getNameStr() const {
1511 std::string ExitName, EntryName;
1512 raw_string_ostream ExitStr(ExitName);
1513 raw_string_ostream EntryStr(EntryName);
1514
Tobias Grosserf240b482014-01-09 10:42:15 +00001515 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001516 EntryStr.str();
1517
1518 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001519 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001520 ExitStr.str();
1521 } else
1522 ExitName = "FunctionExit";
1523
1524 return EntryName + "---" + ExitName;
1525}
1526
Tobias Grosser74394f02013-01-14 22:40:23 +00001527__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001528__isl_give isl_space *Scop::getParamSpace() const {
1529 return isl_set_get_space(this->Context);
1530}
1531
Tobias Grossere86109f2013-10-29 21:05:49 +00001532__isl_give isl_set *Scop::getAssumedContext() const {
1533 return isl_set_copy(AssumedContext);
1534}
1535
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001536void Scop::addAssumption(__isl_take isl_set *Set) {
1537 AssumedContext = isl_set_intersect(AssumedContext, Set);
1538}
1539
Tobias Grosser75805372011-04-29 06:27:02 +00001540void Scop::printContext(raw_ostream &OS) const {
1541 OS << "Context:\n";
1542
1543 if (!Context) {
1544 OS.indent(4) << "n/a\n\n";
1545 return;
1546 }
1547
1548 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001549
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001550 OS.indent(4) << "Assumed Context:\n";
1551 if (!AssumedContext) {
1552 OS.indent(4) << "n/a\n\n";
1553 return;
1554 }
1555
1556 OS.indent(4) << getAssumedContextStr() << "\n";
1557
Tobias Grosser083d3d32014-06-28 08:59:45 +00001558 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001559 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001560 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1561 }
Tobias Grosser75805372011-04-29 06:27:02 +00001562}
1563
Johannes Doerfertb164c792014-09-18 11:17:17 +00001564void Scop::printAliasAssumptions(raw_ostream &OS) const {
1565 OS.indent(4) << "Alias Groups (" << MinMaxAliasGroups.size() << "):\n";
1566 if (MinMaxAliasGroups.empty()) {
1567 OS.indent(8) << "n/a\n";
1568 return;
1569 }
1570 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1571 OS.indent(8) << "[[";
1572 for (MinMaxAccessTy &MinMacAccess : *MinMaxAccesses)
1573 OS << " <" << MinMacAccess.first << ", " << MinMacAccess.second << ">";
1574 OS << " ]]\n";
1575 }
1576}
1577
Tobias Grosser75805372011-04-29 06:27:02 +00001578void Scop::printStatements(raw_ostream &OS) const {
1579 OS << "Statements {\n";
1580
Tobias Grosser083d3d32014-06-28 08:59:45 +00001581 for (ScopStmt *Stmt : *this)
1582 OS.indent(4) << *Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001583
1584 OS.indent(4) << "}\n";
1585}
1586
Tobias Grosser75805372011-04-29 06:27:02 +00001587void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001588 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1589 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001590 OS.indent(4) << "Region: " << getNameStr() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001591 printContext(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001592 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001593 printStatements(OS.indent(4));
1594}
1595
1596void Scop::dump() const { print(dbgs()); }
1597
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001598isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001599
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001600__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001601 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001602
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001603 for (ScopStmt *Stmt : *this)
1604 Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001605
1606 return Domain;
1607}
1608
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001609__isl_give isl_union_map *Scop::getMustWrites() {
1610 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1611
1612 for (ScopStmt *Stmt : *this) {
1613 for (MemoryAccess *MA : *Stmt) {
1614 if (!MA->isMustWrite())
1615 continue;
1616
1617 isl_set *Domain = Stmt->getDomain();
1618 isl_map *AccessDomain = MA->getAccessRelation();
1619 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1620 Write = isl_union_map_add_map(Write, AccessDomain);
1621 }
1622 }
1623 return isl_union_map_coalesce(Write);
1624}
1625
1626__isl_give isl_union_map *Scop::getMayWrites() {
1627 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1628
1629 for (ScopStmt *Stmt : *this) {
1630 for (MemoryAccess *MA : *Stmt) {
1631 if (!MA->isMayWrite())
1632 continue;
1633
1634 isl_set *Domain = Stmt->getDomain();
1635 isl_map *AccessDomain = MA->getAccessRelation();
1636 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1637 Write = isl_union_map_add_map(Write, AccessDomain);
1638 }
1639 }
1640 return isl_union_map_coalesce(Write);
1641}
1642
Tobias Grosser37eb4222014-02-20 21:43:54 +00001643__isl_give isl_union_map *Scop::getWrites() {
1644 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1645
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001646 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001647 for (MemoryAccess *MA : *Stmt) {
1648 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001649 continue;
1650
1651 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001652 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001653 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1654 Write = isl_union_map_add_map(Write, AccessDomain);
1655 }
1656 }
1657 return isl_union_map_coalesce(Write);
1658}
1659
1660__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001661 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001662
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001663 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001664 for (MemoryAccess *MA : *Stmt) {
1665 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001666 continue;
1667
1668 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001669 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001670
1671 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1672 Read = isl_union_map_add_map(Read, AccessDomain);
1673 }
1674 }
1675 return isl_union_map_coalesce(Read);
1676}
1677
1678__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001679 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001680
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001681 for (ScopStmt *Stmt : *this)
Tobias Grosser37eb4222014-02-20 21:43:54 +00001682 Schedule = isl_union_map_add_map(Schedule, Stmt->getScattering());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001683
Tobias Grosser37eb4222014-02-20 21:43:54 +00001684 return isl_union_map_coalesce(Schedule);
1685}
1686
1687bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1688 bool Changed = false;
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001689 for (ScopStmt *Stmt : *this) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00001690 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001691 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1692 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1693
1694 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1695 isl_union_set_free(StmtDomain);
1696 isl_union_set_free(NewStmtDomain);
1697 continue;
1698 }
1699
1700 Changed = true;
1701
1702 isl_union_set_free(StmtDomain);
1703 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1704
1705 if (isl_union_set_is_empty(NewStmtDomain)) {
1706 Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1707 isl_union_set_free(NewStmtDomain);
1708 } else
1709 Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1710 }
1711 isl_union_set_free(Domain);
1712 return Changed;
1713}
1714
Tobias Grosser75805372011-04-29 06:27:02 +00001715ScalarEvolution *Scop::getSE() const { return SE; }
1716
1717bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1718 if (tempScop.getAccessFunctions(BB))
1719 return false;
1720
1721 return true;
1722}
1723
Tobias Grosser74394f02013-01-14 22:40:23 +00001724void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
1725 SmallVectorImpl<Loop *> &NestLoops,
1726 SmallVectorImpl<unsigned> &Scatter, LoopInfo &LI) {
Tobias Grosser75805372011-04-29 06:27:02 +00001727 Loop *L = castToLoop(CurRegion, LI);
1728
1729 if (L)
1730 NestLoops.push_back(L);
1731
1732 unsigned loopDepth = NestLoops.size();
1733 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
1734
1735 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00001736 E = CurRegion.element_end();
1737 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +00001738 if (I->isSubRegion())
1739 buildScop(tempScop, *(I->getNodeAs<Region>()), NestLoops, Scatter, LI);
1740 else {
1741 BasicBlock *BB = I->getNodeAs<BasicBlock>();
1742
1743 if (isTrivialBB(BB, tempScop))
1744 continue;
1745
Johannes Doerfert7c494212014-10-31 23:13:39 +00001746 ScopStmt *Stmt =
1747 new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, Scatter);
1748
1749 // Insert all statements into the statement map and the statement vector.
1750 StmtMap[BB] = Stmt;
1751 Stmts.push_back(Stmt);
Tobias Grosser75805372011-04-29 06:27:02 +00001752
1753 // Increasing the Scattering function is OK for the moment, because
1754 // we are using a depth first iterator and the program is well structured.
1755 ++Scatter[loopDepth];
1756 }
1757
1758 if (!L)
1759 return;
1760
1761 // Exiting a loop region.
1762 Scatter[loopDepth] = 0;
1763 NestLoops.pop_back();
Tobias Grosser74394f02013-01-14 22:40:23 +00001764 ++Scatter[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00001765}
1766
Johannes Doerfert7c494212014-10-31 23:13:39 +00001767ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
1768 const auto &StmtMapIt = StmtMap.find(BB);
1769 if (StmtMapIt == StmtMap.end())
1770 return nullptr;
1771 return StmtMapIt->second;
1772}
1773
Tobias Grosser75805372011-04-29 06:27:02 +00001774//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00001775ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
1776 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00001777 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001778}
1779
1780ScopInfo::~ScopInfo() {
1781 clear();
1782 isl_ctx_free(ctx);
1783}
1784
Tobias Grosser75805372011-04-29 06:27:02 +00001785void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1786 AU.addRequired<LoopInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001787 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001788 AU.addRequired<ScalarEvolution>();
1789 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001790 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00001791 AU.setPreservesAll();
1792}
1793
1794bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
1795 LoopInfo &LI = getAnalysis<LoopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001796 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00001797 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1798
1799 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
1800
1801 // This region is no Scop.
1802 if (!tempScop) {
1803 scop = 0;
1804 return false;
1805 }
1806
Tobias Grosserb76f38532011-08-20 11:11:25 +00001807 scop = new Scop(*tempScop, LI, SE, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001808
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001809 if (!PollyUseRuntimeAliasChecks) {
1810 // Statistics.
1811 ++ScopFound;
1812 if (scop->getMaxLoopDepth() > 0)
1813 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001814 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001815 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001816
Johannes Doerfert9143d672014-09-27 11:02:39 +00001817 // If a problem occurs while building the alias groups we need to delete
1818 // this SCoP and pretend it wasn't valid in the first place.
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001819 if (scop->buildAliasGroups(AA)) {
1820 // Statistics.
1821 ++ScopFound;
1822 if (scop->getMaxLoopDepth() > 0)
1823 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001824 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001825 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001826
1827 DEBUG(dbgs()
1828 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
1829 << " could not be created as the number of parameters involved is too "
1830 "high. The SCoP will be "
1831 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
1832 "maximal number of parameters but be advised that the compile time "
1833 "might increase exponentially.\n\n");
1834
1835 delete scop;
1836 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00001837 return false;
1838}
1839
1840char ScopInfo::ID = 0;
1841
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001842Pass *polly::createScopInfoPass() { return new ScopInfo(); }
1843
Tobias Grosser73600b82011-10-08 00:30:40 +00001844INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
1845 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001846 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001847INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001848INITIALIZE_PASS_DEPENDENCY(LoopInfo);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001849INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001850INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1851INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00001852INITIALIZE_PASS_END(ScopInfo, "polly-scops",
1853 "Polly - Create polyhedral description of Scops", false,
1854 false)