blob: a8c74917b7f1ba8888ace856f94c2c8d83db67f6 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000021#include "polly/ScopInfo.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000026#include "polly/TempScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000027#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000028#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000029#include "llvm/ADT/StringExtras.h"
Tobias Grosser83628182013-05-07 08:11:54 +000030#include "llvm/Analysis/LoopInfo.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000031#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser83628182013-05-07 08:11:54 +000032#include "llvm/Analysis/RegionIterator.h"
33#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000034#include "llvm/Support/Debug.h"
35
36#include "isl/constraint.h"
37#include "isl/set.h"
38#include "isl/map.h"
Tobias Grosser37eb4222014-02-20 21:43:54 +000039#include "isl/union_map.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000040#include "isl/aff.h"
41#include "isl/printer.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000042#include "isl/local_space.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000043#include "isl/options.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000044#include "isl/val.h"
Chandler Carruth95fef942014-04-22 03:30:19 +000045
Tobias Grosser75805372011-04-29 06:27:02 +000046#include <sstream>
47#include <string>
48#include <vector>
49
50using namespace llvm;
51using namespace polly;
52
Chandler Carruth95fef942014-04-22 03:30:19 +000053#define DEBUG_TYPE "polly-scops"
54
Tobias Grosser74394f02013-01-14 22:40:23 +000055STATISTIC(ScopFound, "Number of valid Scops");
56STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000057
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000058// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000059// operations can overflow easily. Additive reductions and bit operations
60// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000061static cl::opt<bool> DisableMultiplicativeReductions(
62 "polly-disable-multiplicative-reductions",
63 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
64 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000065
Johannes Doerfert9143d672014-09-27 11:02:39 +000066static cl::opt<unsigned> RunTimeChecksMaxParameters(
67 "polly-rtc-max-parameters",
68 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
69 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
70
Tobias Grosser71500722015-03-28 15:11:14 +000071static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
72 "polly-rtc-max-arrays-per-group",
73 cl::desc("The maximal number of arrays to compare in each alias group."),
74 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
75
Tobias Grosser0695ee42013-09-17 03:30:31 +000076/// Translate a 'const SCEV *' expression in an isl_pw_aff.
Tobias Grosserabfbe632013-02-05 12:09:06 +000077struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
Tobias Grosser0695ee42013-09-17 03:30:31 +000078public:
Tobias Grosser0695ee42013-09-17 03:30:31 +000079 /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
80 ///
81 /// @param Stmt The location at which the scalar evolution expression
82 /// is evaluated.
83 /// @param Expr The expression that is translated.
84 static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
85
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000086private:
Tobias Grosser3cc99742012-06-06 16:33:15 +000087 isl_ctx *Ctx;
Tobias Grosserf5338802011-10-06 00:03:35 +000088 int NbLoopSpaces;
Tobias Grosser3cc99742012-06-06 16:33:15 +000089 const Scop *S;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000090
Tobias Grosser0695ee42013-09-17 03:30:31 +000091 SCEVAffinator(const ScopStmt *Stmt);
92 int getLoopDepth(const Loop *L);
Tobias Grosser60b54f12011-11-08 15:41:28 +000093
Tobias Grosser0695ee42013-09-17 03:30:31 +000094 __isl_give isl_pw_aff *visit(const SCEV *Expr);
95 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
96 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
97 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
98 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
99 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
100 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
101 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
102 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
103 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
104 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
105 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000106 __isl_give isl_pw_aff *visitSDivInstruction(Instruction *SDiv);
Tobias Grosser60b54f12011-11-08 15:41:28 +0000107
Tobias Grosser0695ee42013-09-17 03:30:31 +0000108 friend struct SCEVVisitor<SCEVAffinator, isl_pw_aff *>;
109};
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000110
Tobias Grosser0695ee42013-09-17 03:30:31 +0000111SCEVAffinator::SCEVAffinator(const ScopStmt *Stmt)
112 : Ctx(Stmt->getIslCtx()), NbLoopSpaces(Stmt->getNumIterators()),
113 S(Stmt->getParent()) {}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000114
Tobias Grosser0695ee42013-09-17 03:30:31 +0000115__isl_give isl_pw_aff *SCEVAffinator::getPwAff(ScopStmt *Stmt,
116 const SCEV *Scev) {
117 Scop *S = Stmt->getParent();
118 const Region *Reg = &S->getRegion();
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000119
Tobias Grosser0695ee42013-09-17 03:30:31 +0000120 S->addParams(getParamsInAffineExpr(Reg, Scev, *S->getSE()));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000121
Tobias Grosser0695ee42013-09-17 03:30:31 +0000122 SCEVAffinator Affinator(Stmt);
123 return Affinator.visit(Scev);
124}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000125
Tobias Grosser0695ee42013-09-17 03:30:31 +0000126__isl_give isl_pw_aff *SCEVAffinator::visit(const SCEV *Expr) {
127 // In case the scev is a valid parameter, we do not further analyze this
128 // expression, but create a new parameter in the isl_pw_aff. This allows us
129 // to treat subexpressions that we cannot translate into an piecewise affine
130 // expression, as constant parameters of the piecewise affine expression.
131 if (isl_id *Id = S->getIdForParam(Expr)) {
132 isl_space *Space = isl_space_set_alloc(Ctx, 1, NbLoopSpaces);
133 Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000134
Tobias Grosser0695ee42013-09-17 03:30:31 +0000135 isl_set *Domain = isl_set_universe(isl_space_copy(Space));
136 isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
137 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000138
139 return isl_pw_aff_alloc(Domain, Affine);
140 }
141
Tobias Grosser0695ee42013-09-17 03:30:31 +0000142 return SCEVVisitor<SCEVAffinator, isl_pw_aff *>::visit(Expr);
143}
144
Tobias Grosser0d170132013-10-03 13:09:19 +0000145__isl_give isl_pw_aff *SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
Tobias Grosser0695ee42013-09-17 03:30:31 +0000146 ConstantInt *Value = Expr->getValue();
147 isl_val *v;
148
149 // LLVM does not define if an integer value is interpreted as a signed or
150 // unsigned value. Hence, without further information, it is unknown how
151 // this value needs to be converted to GMP. At the moment, we only support
152 // signed operations. So we just interpret it as signed. Later, there are
153 // two options:
154 //
155 // 1. We always interpret any value as signed and convert the values on
156 // demand.
157 // 2. We pass down the signedness of the calculation and use it to interpret
158 // this constant correctly.
159 v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
160
161 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
Johannes Doerfert9c147372014-11-19 15:36:59 +0000162 isl_local_space *ls = isl_local_space_from_space(Space);
163 return isl_pw_aff_from_aff(isl_aff_val_on_domain(ls, v));
Tobias Grosser0695ee42013-09-17 03:30:31 +0000164}
165
166__isl_give isl_pw_aff *
167SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
168 llvm_unreachable("SCEVTruncateExpr not yet supported");
169}
170
171__isl_give isl_pw_aff *
172SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
173 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
174}
175
176__isl_give isl_pw_aff *
177SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
178 // Assuming the value is signed, a sign extension is basically a noop.
179 // TODO: Reconsider this as soon as we support unsigned values.
180 return visit(Expr->getOperand());
181}
182
183__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
184 isl_pw_aff *Sum = visit(Expr->getOperand(0));
185
186 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
187 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
188 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000189 }
190
Tobias Grosser0695ee42013-09-17 03:30:31 +0000191 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000192
Tobias Grosser0695ee42013-09-17 03:30:31 +0000193 return Sum;
194}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000195
Tobias Grosser0695ee42013-09-17 03:30:31 +0000196__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
Johannes Doerfertbe409962015-03-29 20:45:09 +0000197 // Divide Expr into a constant part and the rest. Then visit both and multiply
198 // the result to obtain the representation for Expr. While the second part of
199 // ConstantAndLeftOverPair might still be a SCEVMulExpr we will not get to
200 // this point again. The reason is that if it is a multiplication it consists
201 // only of parameters and we will stop in the visit(const SCEV *) function and
202 // return the isl_pw_aff for that parameter.
203 auto ConstantAndLeftOverPair = extractConstantFactor(Expr, *S->getSE());
204 return isl_pw_aff_mul(visit(ConstantAndLeftOverPair.first),
205 visit(ConstantAndLeftOverPair.second));
Tobias Grosser0695ee42013-09-17 03:30:31 +0000206}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000207
Tobias Grosser0695ee42013-09-17 03:30:31 +0000208__isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
209 llvm_unreachable("SCEVUDivExpr not yet supported");
210}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000211
Tobias Grosser0695ee42013-09-17 03:30:31 +0000212__isl_give isl_pw_aff *
213SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
214 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000215
Tobias Grosser0695ee42013-09-17 03:30:31 +0000216 // Directly generate isl_pw_aff for Expr if 'start' is zero.
217 if (Expr->getStart()->isZero()) {
218 assert(S->getRegion().contains(Expr->getLoop()) &&
219 "Scop does not contain the loop referenced in this AddRec");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000220
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000221 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser0695ee42013-09-17 03:30:31 +0000222 isl_pw_aff *Step = visit(Expr->getOperand(1));
223 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
224 isl_local_space *LocalSpace = isl_local_space_from_space(Space);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000225
Tobias Grosser0695ee42013-09-17 03:30:31 +0000226 int loopDimension = getLoopDepth(Expr->getLoop());
227
228 isl_aff *LAff = isl_aff_set_coefficient_si(
229 isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
230 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
231
232 // TODO: Do we need to check for NSW and NUW?
233 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000234 }
235
Tobias Grosser0695ee42013-09-17 03:30:31 +0000236 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
237 // if 'start' is not zero.
238 ScalarEvolution &SE = *S->getSE();
239 const SCEV *ZeroStartExpr = SE.getAddRecExpr(
240 SE.getConstant(Expr->getStart()->getType(), 0),
241 Expr->getStepRecurrence(SE), Expr->getLoop(), SCEV::FlagAnyWrap);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000242
Tobias Grosser0695ee42013-09-17 03:30:31 +0000243 isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
244 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000245
Tobias Grosser0695ee42013-09-17 03:30:31 +0000246 return isl_pw_aff_add(ZeroStartResult, Start);
247}
248
249__isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
250 isl_pw_aff *Max = visit(Expr->getOperand(0));
251
252 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
253 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
254 Max = isl_pw_aff_max(Max, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000255 }
256
Tobias Grosser0695ee42013-09-17 03:30:31 +0000257 return Max;
258}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000259
Tobias Grosser0695ee42013-09-17 03:30:31 +0000260__isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
261 llvm_unreachable("SCEVUMaxExpr not yet supported");
262}
263
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000264__isl_give isl_pw_aff *SCEVAffinator::visitSDivInstruction(Instruction *SDiv) {
265 assert(SDiv->getOpcode() == Instruction::SDiv && "Assumed SDiv instruction!");
266 auto *SE = S->getSE();
267
268 auto *Divisor = SDiv->getOperand(1);
269 auto *DivisorSCEV = SE->getSCEV(Divisor);
270 auto *DivisorPWA = visit(DivisorSCEV);
271 assert(isa<ConstantInt>(Divisor) &&
272 "SDiv is no parameter but has a non-constant RHS.");
273
274 auto *Dividend = SDiv->getOperand(0);
275 auto *DividendSCEV = SE->getSCEV(Dividend);
276 auto *DividendPWA = visit(DividendSCEV);
277 return isl_pw_aff_tdiv_q(DividendPWA, DivisorPWA);
278}
279
Tobias Grosser0695ee42013-09-17 03:30:31 +0000280__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000281 if (Instruction *I = dyn_cast<Instruction>(Expr->getValue())) {
282 switch (I->getOpcode()) {
283 case Instruction::SDiv:
284 return visitSDivInstruction(I);
285 default:
286 break; // Fall through.
287 }
288 }
289
290 llvm_unreachable(
291 "Unknowns SCEV was neither parameter nor a valid instruction.");
Tobias Grosser0695ee42013-09-17 03:30:31 +0000292}
293
294int SCEVAffinator::getLoopDepth(const Loop *L) {
295 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
296 assert(outerLoop && "Scop does not contain this loop");
297 return L->getLoopDepth() - outerLoop->getLoopDepth();
298}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000299
Johannes Doerferte7044942015-02-24 11:58:30 +0000300/// @brief Add the bounds of @p Range to the set @p S for dimension @p dim.
301static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
302 const ConstantRange &Range,
303 int dim,
304 enum isl_dim_type type) {
305 isl_val *V;
306 isl_ctx *ctx = isl_set_get_ctx(S);
307
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000308 bool isWrapping = Range.isSignWrappedSet();
309 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
310 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000311 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
312
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000313 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
314 V = isl_valFromAPInt(ctx, UB, true);
315 if (isWrapping)
316 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000317 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
318
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000319 if (isWrapping)
Johannes Doerferte7044942015-02-24 11:58:30 +0000320 return isl_set_union(SLB, SUB);
321 else
322 return isl_set_intersect(SLB, SUB);
323}
324
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000325ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *AccessType, isl_ctx *Ctx,
326 const SmallVector<const SCEV *, 4> &DimensionSizes)
327 : BasePtr(BasePtr), AccessType(AccessType), DimensionSizes(DimensionSizes) {
328 const std::string BasePtrName = getIslCompatibleName("MemRef_", BasePtr, "");
329 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
330}
331
332ScopArrayInfo::~ScopArrayInfo() { isl_id_free(Id); }
333
334isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
335
336void ScopArrayInfo::dump() const { print(errs()); }
337
338void ScopArrayInfo::print(raw_ostream &OS) const {
339 OS << "ScopArrayInfo:\n";
340 OS << " Base: " << *getBasePtr() << "\n";
341 OS << " Type: " << *getType() << "\n";
342 OS << " Dimension Sizes:\n";
343 for (unsigned u = 0; u < getNumberOfDimensions(); u++)
344 OS << " " << u << ") " << *DimensionSizes[u] << "\n";
345 OS << "\n";
346}
347
348const ScopArrayInfo *
349ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
350 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
351 assert(Id && "Output dimension didn't have an ID");
352 return getFromId(Id);
353}
354
355const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
356 void *User = isl_id_get_user(Id);
357 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
358 isl_id_free(Id);
359 return SAI;
360}
361
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000362const std::string
363MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
364 switch (RT) {
365 case MemoryAccess::RT_NONE:
366 llvm_unreachable("Requested a reduction operator string for a memory "
367 "access which isn't a reduction");
368 case MemoryAccess::RT_ADD:
369 return "+";
370 case MemoryAccess::RT_MUL:
371 return "*";
372 case MemoryAccess::RT_BOR:
373 return "|";
374 case MemoryAccess::RT_BXOR:
375 return "^";
376 case MemoryAccess::RT_BAND:
377 return "&";
378 }
379 llvm_unreachable("Unknown reduction type");
380 return "";
381}
382
Johannes Doerfertf6183392014-07-01 20:52:51 +0000383/// @brief Return the reduction type for a given binary operator
384static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
385 const Instruction *Load) {
386 if (!BinOp)
387 return MemoryAccess::RT_NONE;
388 switch (BinOp->getOpcode()) {
389 case Instruction::FAdd:
390 if (!BinOp->hasUnsafeAlgebra())
391 return MemoryAccess::RT_NONE;
392 // Fall through
393 case Instruction::Add:
394 return MemoryAccess::RT_ADD;
395 case Instruction::Or:
396 return MemoryAccess::RT_BOR;
397 case Instruction::Xor:
398 return MemoryAccess::RT_BXOR;
399 case Instruction::And:
400 return MemoryAccess::RT_BAND;
401 case Instruction::FMul:
402 if (!BinOp->hasUnsafeAlgebra())
403 return MemoryAccess::RT_NONE;
404 // Fall through
405 case Instruction::Mul:
406 if (DisableMultiplicativeReductions)
407 return MemoryAccess::RT_NONE;
408 return MemoryAccess::RT_MUL;
409 default:
410 return MemoryAccess::RT_NONE;
411 }
412}
Tobias Grosser75805372011-04-29 06:27:02 +0000413//===----------------------------------------------------------------------===//
414
415MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000416 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000417 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000418}
419
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000420static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
421 switch (Access.getType()) {
422 case IRAccess::READ:
423 return MemoryAccess::READ;
424 case IRAccess::MUST_WRITE:
425 return MemoryAccess::MUST_WRITE;
426 case IRAccess::MAY_WRITE:
427 return MemoryAccess::MAY_WRITE;
428 }
429 llvm_unreachable("Unknown IRAccess type!");
430}
431
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000432const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
433 isl_id *ArrayId = getArrayId();
434 void *User = isl_id_get_user(ArrayId);
435 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
436 isl_id_free(ArrayId);
437 return SAI;
438}
439
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000440__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000441 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
442}
443
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000444__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
445 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000446 isl_map *Schedule, *ScheduledAccRel;
447 isl_union_set *UDomain;
448
449 UDomain = isl_union_set_from_set(getStatement()->getDomain());
450 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
451 Schedule = isl_map_from_union_map(USchedule);
452 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
453 return isl_pw_multi_aff_from_map(ScheduledAccRel);
454}
455
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000456__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000457 return isl_map_copy(AccessRelation);
458}
459
Johannes Doerferta99130f2014-10-13 12:58:03 +0000460std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000461 return stringFromIslObj(AccessRelation);
462}
463
Johannes Doerferta99130f2014-10-13 12:58:03 +0000464__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000465 return isl_map_get_space(AccessRelation);
466}
467
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000468__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000469 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000470}
471
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000472__isl_give isl_basic_map *
473MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000474 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000475 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000476
Tobias Grosser084d8f72012-05-29 09:29:44 +0000477 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000478 isl_basic_set_universe(Statement->getDomainSpace()),
479 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000480}
481
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000482// Formalize no out-of-bound access assumption
483//
484// When delinearizing array accesses we optimistically assume that the
485// delinearized accesses do not access out of bound locations (the subscript
486// expression of each array evaluates for each statement instance that is
487// executed to a value that is larger than zero and strictly smaller than the
488// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000489// dimension for which we do not need to assume any upper bound. At this point
490// we formalize this assumption to ensure that at code generation time the
491// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000492//
493// To find the set of constraints necessary to avoid out of bound accesses, we
494// first build the set of data locations that are not within array bounds. We
495// then apply the reverse access relation to obtain the set of iterations that
496// may contain invalid accesses and reduce this set of iterations to the ones
497// that are actually executed by intersecting them with the domain of the
498// statement. If we now project out all loop dimensions, we obtain a set of
499// parameters that may cause statement instances to be executed that may
500// possibly yield out of bound memory accesses. The complement of these
501// constraints is the set of constraints that needs to be assumed to ensure such
502// statement instances are never executed.
503void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000504 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000505 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000506 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000507 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
508 isl_pw_aff *Var =
509 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
510 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
511
512 isl_set *DimOutside;
513
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000514 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
515 isl_pw_aff *SizeE = SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000516
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000517 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
518 Statement->getNumIterators());
519 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
520 isl_space_dim(Space, isl_dim_set));
521 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
522 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000523
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000524 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000525
526 Outside = isl_set_union(Outside, DimOutside);
527 }
528
529 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
530 Outside = isl_set_intersect(Outside, Statement->getDomain());
531 Outside = isl_set_params(Outside);
532 Outside = isl_set_complement(Outside);
533 Statement->getParent()->addAssumption(Outside);
534 isl_space_free(Space);
535}
536
Johannes Doerferte7044942015-02-24 11:58:30 +0000537void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
538 ScalarEvolution *SE = Statement->getParent()->getSE();
539
540 Value *Ptr = getPointerOperand(*getAccessInstruction());
541 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
542 return;
543
544 auto *PtrSCEV = SE->getSCEV(Ptr);
545 if (isa<SCEVCouldNotCompute>(PtrSCEV))
546 return;
547
548 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
549 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
550 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
551
552 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
553 if (Range.isFullSet())
554 return;
555
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000556 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000557 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000558 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
559 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
560
561 auto Min = LB.sdiv(APInt(BW, ElementSize));
562 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000563
564 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
565 AccessRange =
566 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
567 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
568}
569
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000570MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000571 ScopStmt *Statement, const ScopArrayInfo *SAI)
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000572 : AccType(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000573 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000574
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000575 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000576 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000577 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000578
579 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000580
Tobias Grossera1879642011-12-20 10:43:14 +0000581 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000582 // We overapproximate non-affine accesses with a possible access to the
583 // whole array. For read accesses it does not make a difference, if an
584 // access must or may happen. However, for write accesses it is important to
585 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000586 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000587 AccessRelation =
588 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000589
590 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000591 return;
592 }
593
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000594 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000595 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000596
Tobias Grosser79baa212014-04-10 08:38:02 +0000597 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000598 isl_pw_aff *Affine =
599 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000600
Sebastian Pop422e33f2014-06-03 18:16:31 +0000601 if (Size == 1) {
602 // For the non delinearized arrays, divide the access function of the last
603 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000604 //
605 // A stride one array access in C expressed as A[i] is expressed in
606 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
607 // two subsequent values of 'i' index two values that are stored next to
608 // each other in memory. By this division we make this characteristic
609 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000610 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000611 Affine = isl_pw_aff_scale_down_val(Affine, v);
612 }
613
614 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
615
Tobias Grosser79baa212014-04-10 08:38:02 +0000616 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000617 }
618
Tobias Grosser79baa212014-04-10 08:38:02 +0000619 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000620 AccessRelation = isl_map_set_tuple_id(
621 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000622 AccessRelation =
623 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
624
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000625 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000626 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000627 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000628}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000629
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000630void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000631 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000632 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000633}
634
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000635const std::string MemoryAccess::getReductionOperatorStr() const {
636 return MemoryAccess::getReductionOperatorStr(getReductionType());
637}
638
Johannes Doerfertf6183392014-07-01 20:52:51 +0000639raw_ostream &polly::operator<<(raw_ostream &OS,
640 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000641 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000642 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000643 else
644 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000645 return OS;
646}
647
Tobias Grosser75805372011-04-29 06:27:02 +0000648void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000649 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000650 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000651 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000652 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000653 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000654 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000655 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000656 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000657 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000658 break;
659 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000660 OS << "[Reduction Type: " << getReductionType() << "] ";
661 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000662 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000663}
664
Tobias Grosser74394f02013-01-14 22:40:23 +0000665void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000666
667// Create a map in the size of the provided set domain, that maps from the
668// one element of the provided set domain to another element of the provided
669// set domain.
670// The mapping is limited to all points that are equal in all but the last
671// dimension and for which the last dimension of the input is strict smaller
672// than the last dimension of the output.
673//
674// getEqualAndLarger(set[i0, i1, ..., iX]):
675//
676// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
677// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
678//
Tobias Grosserf5338802011-10-06 00:03:35 +0000679static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000680 isl_space *Space = isl_space_map_from_set(setDomain);
681 isl_map *Map = isl_map_universe(isl_space_copy(Space));
682 isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000683 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000684
685 // Set all but the last dimension to be equal for the input and output
686 //
687 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
688 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000689 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000690 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000691
692 // Set the last dimension of the input to be strict smaller than the
693 // last dimension of the output.
694 //
695 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
696 //
Tobias Grosseredab1352013-06-21 06:41:31 +0000697 isl_val *v;
698 isl_ctx *Ctx = isl_map_get_ctx(Map);
Tobias Grosserf5338802011-10-06 00:03:35 +0000699 isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
Tobias Grosseredab1352013-06-21 06:41:31 +0000700 v = isl_val_int_from_si(Ctx, -1);
701 c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
702 v = isl_val_int_from_si(Ctx, 1);
703 c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
704 v = isl_val_int_from_si(Ctx, -1);
705 c = isl_constraint_set_constant_val(c, v);
Tobias Grosser75805372011-04-29 06:27:02 +0000706
Tobias Grosserc327932c2012-02-01 14:23:36 +0000707 Map = isl_map_add_constraint(Map, c);
Tobias Grosser75805372011-04-29 06:27:02 +0000708
Tobias Grosser23b36662011-10-17 08:32:36 +0000709 isl_local_space_free(MapLocalSpace);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000710 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000711}
712
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000713__isl_give isl_set *
714MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000715 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000716 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000717 isl_space *Space = isl_space_range(isl_map_get_space(S));
718 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000719
Sebastian Popa00a0292012-12-18 07:46:06 +0000720 S = isl_map_reverse(S);
721 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000722
Sebastian Popa00a0292012-12-18 07:46:06 +0000723 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
724 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
725 NextScatt = isl_map_apply_domain(NextScatt, S);
726 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000727
Sebastian Popa00a0292012-12-18 07:46:06 +0000728 isl_set *Deltas = isl_map_deltas(NextScatt);
729 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000730}
731
Sebastian Popa00a0292012-12-18 07:46:06 +0000732bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000733 int StrideWidth) const {
734 isl_set *Stride, *StrideX;
735 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000736
Sebastian Popa00a0292012-12-18 07:46:06 +0000737 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000738 StrideX = isl_set_universe(isl_set_get_space(Stride));
739 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
740 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000741
Tobias Grosser28dd4862012-01-24 16:42:16 +0000742 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000743 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000744
Tobias Grosser28dd4862012-01-24 16:42:16 +0000745 return IsStrideX;
746}
747
Sebastian Popa00a0292012-12-18 07:46:06 +0000748bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
749 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000750}
751
Tobias Grosser79baa212014-04-10 08:38:02 +0000752bool MemoryAccess::isScalar() const {
753 return isl_map_n_out(AccessRelation) == 0;
754}
755
Sebastian Popa00a0292012-12-18 07:46:06 +0000756bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
757 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000758}
759
Tobias Grosser5d453812011-10-06 00:04:11 +0000760void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000761 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000762 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000763}
Tobias Grosser75805372011-04-29 06:27:02 +0000764
765//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000766
Tobias Grosser74394f02013-01-14 22:40:23 +0000767isl_map *ScopStmt::getScattering() const { return isl_map_copy(Scattering); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000768
Tobias Grosser37eb4222014-02-20 21:43:54 +0000769void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
770 assert(isl_set_is_subset(NewDomain, Domain) &&
771 "New domain is not a subset of old domain!");
772 isl_set_free(Domain);
773 Domain = NewDomain;
774 Scattering = isl_map_intersect_domain(Scattering, isl_set_copy(Domain));
775}
776
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000777void ScopStmt::setScattering(__isl_take isl_map *NewScattering) {
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000778 assert(NewScattering && "New scattering is nullptr");
Tobias Grosserb76f38532011-08-20 11:11:25 +0000779 isl_map_free(Scattering);
Tobias Grossercf3942d2011-10-06 00:04:05 +0000780 Scattering = NewScattering;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000781}
782
Tobias Grosser75805372011-04-29 06:27:02 +0000783void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000784 unsigned NbIterators = getNumIterators();
785 unsigned NbScatteringDims = Parent.getMaxLoopDepth() * 2 + 1;
786
Tobias Grosser084d8f72012-05-29 09:29:44 +0000787 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScatteringDims);
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000788
Tobias Grosser084d8f72012-05-29 09:29:44 +0000789 Scattering = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
790 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000791
792 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000793 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosserabfbe632013-02-05 12:09:06 +0000794 Scattering =
795 isl_map_equate(Scattering, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000796
797 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000798 for (unsigned i = 0; i < NbIterators + 1; ++i)
799 Scattering = isl_map_fix_si(Scattering, isl_dim_out, 2 * i, Scatter[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000800
801 // Fill scattering dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000802 for (unsigned i = 2 * NbIterators + 1; i < NbScatteringDims; ++i)
803 Scattering = isl_map_fix_si(Scattering, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000804
Tobias Grosser37487052011-10-06 00:03:42 +0000805 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000806}
807
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000808void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
809 bool isApproximated) {
810 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
811 if (!AFS)
812 return;
813
814 for (auto &AccessPair : *AFS) {
815 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000816 Instruction *AccessInst = AccessPair.second;
817
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000818 Type *AccessType = getAccessInstType(AccessInst)->getPointerTo();
819 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
820 Access.getBase(), AccessType, Access.Sizes);
821
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000822 if (isApproximated && Access.isWrite())
823 Access.setMayWrite();
824
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000825 MemAccs.push_back(new MemoryAccess(Access, AccessInst, this, SAI));
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000826
827 // We do not track locations for scalar memory accesses at the moment.
828 //
829 // We do not have a use for this information at the moment. If we need this
830 // at some point, the "instruction -> access" mapping needs to be enhanced
831 // as a single instruction could then possibly perform multiple accesses.
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000832 if (!Access.isScalar()) {
833 assert(!InstructionToAccess.count(AccessInst) &&
Tobias Grosser3fc91542014-02-20 21:43:45 +0000834 "Unexpected 1-to-N mapping on instruction to access map!");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000835 InstructionToAccess[AccessInst] = MemAccs.back();
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000836 }
Tobias Grosser75805372011-04-29 06:27:02 +0000837 }
838}
839
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000840void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000841 for (MemoryAccess *MA : *this)
842 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000843
844 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
845 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
846}
847
Tobias Grosser65b00582011-11-08 15:41:19 +0000848__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000849 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
850 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000851
Tobias Grosserd2795d02011-08-18 07:51:40 +0000852 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000853 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000854 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000855 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000856 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000857 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000858 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000859 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000860 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000861 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000862 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000863 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000864 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000865 case ICmpInst::ICMP_ULT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000866 return isl_pw_aff_lt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000867 case ICmpInst::ICMP_UGT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000868 return isl_pw_aff_gt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000869 case ICmpInst::ICMP_ULE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000870 return isl_pw_aff_le_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000871 case ICmpInst::ICMP_UGE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000872 return isl_pw_aff_ge_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000873 default:
874 llvm_unreachable("Non integer predicate not supported");
875 }
Tobias Grosser75805372011-04-29 06:27:02 +0000876}
877
Tobias Grossere19661e2011-10-07 08:46:57 +0000878__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000879 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000880 isl_space *Space;
881 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000882
Tobias Grossere19661e2011-10-07 08:46:57 +0000883 Space = isl_set_get_space(Domain);
884 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000885
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000886 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000887 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000888 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000889 isl_pw_aff *IV =
890 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000891
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000892 // 0 <= IV.
893 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
894 Domain = isl_set_intersect(Domain, LowerBound);
895
896 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000897 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000898 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000899 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
900 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000901 Domain = isl_set_intersect(Domain, UpperBoundSet);
902 }
903
Tobias Grosserf5338802011-10-06 00:03:35 +0000904 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000905 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000906}
907
Tobias Grossere602a072013-05-07 07:30:56 +0000908__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
909 TempScop &tempScop,
910 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000911 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000912 *CurrentRegion = &CurRegion;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000913 const BasicBlock *BranchingBB = BB ? BB : R->getEntry();
Tobias Grosser75805372011-04-29 06:27:02 +0000914
Tobias Grosser75805372011-04-29 06:27:02 +0000915 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000916 if (BranchingBB != CurrentRegion->getEntry()) {
917 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000918 for (const auto &C : *Condition) {
919 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000920 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000921 }
922 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000923 BranchingBB = CurrentRegion->getEntry();
924 CurrentRegion = CurrentRegion->getParent();
925 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000926
Tobias Grossere19661e2011-10-07 08:46:57 +0000927 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000928}
929
Tobias Grossere602a072013-05-07 07:30:56 +0000930__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
931 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000932 isl_space *Space;
933 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000934 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000935
936 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
937
Tobias Grosser084d8f72012-05-29 09:29:44 +0000938 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
939
Tobias Grossere19661e2011-10-07 08:46:57 +0000940 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000941 Domain = addLoopBoundsToDomain(Domain, tempScop);
942 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000943 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000944
945 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000946}
947
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000948void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
949 int Dimension = 0;
950 isl_ctx *Ctx = Parent.getIslCtx();
951 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
952 Type *Ty = GEP->getPointerOperandType();
953 ScalarEvolution &SE = *Parent.getSE();
954
955 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
956 Dimension = 1;
957 Ty = PtrTy->getElementType();
958 }
959
960 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
961 unsigned int Operand = 1 + Dimension;
962
963 if (GEP->getNumOperands() <= Operand)
964 break;
965
966 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
967
968 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
969 isl_pw_aff *AccessOffset = SCEVAffinator::getPwAff(this, Expr);
970 AccessOffset =
971 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
972
973 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
974 isl_local_space_copy(LSpace),
975 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
976
977 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
978 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
979 OutOfBound = isl_set_params(OutOfBound);
980 isl_set *InBound = isl_set_complement(OutOfBound);
981 isl_set *Executed = isl_set_params(getDomain());
982
983 // A => B == !A or B
984 isl_set *InBoundIfExecuted =
985 isl_set_union(isl_set_complement(Executed), InBound);
986
987 Parent.addAssumption(InBoundIfExecuted);
988 }
989
990 Dimension += 1;
991 Ty = ArrayTy->getElementType();
992 }
993
994 isl_local_space_free(LSpace);
995}
996
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000997void ScopStmt::deriveAssumptions(BasicBlock *Block) {
998 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000999 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1000 deriveAssumptionsFromGEP(GEP);
1001}
1002
Tobias Grosser74394f02013-01-14 22:40:23 +00001003ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001004 Region &R, SmallVectorImpl<Loop *> &Nest,
1005 SmallVectorImpl<unsigned> &Scatter)
1006 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
1007 NestLoops(Nest.size()) {
1008 // Setup the induction variables.
1009 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
1010 NestLoops[i] = Nest[i];
1011
1012 BaseName = getIslCompatibleName("Stmt_(", R.getNameStr(), ")");
1013
1014 Domain = buildDomain(tempScop, CurRegion);
1015 buildScattering(Scatter);
1016
1017 BasicBlock *EntryBB = R.getEntry();
1018 for (BasicBlock *Block : R.blocks()) {
1019 buildAccesses(tempScop, Block, Block != EntryBB);
1020 deriveAssumptions(Block);
1021 }
1022 checkForReductions();
1023}
1024
1025ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +00001026 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser75805372011-04-29 06:27:02 +00001027 SmallVectorImpl<unsigned> &Scatter)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001028 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
1029 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +00001030 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +00001031 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +00001032 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +00001033
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001034 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001035
Tobias Grossere19661e2011-10-07 08:46:57 +00001036 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001037 buildScattering(Scatter);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001038 buildAccesses(tempScop, BB);
1039 deriveAssumptions(BB);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001040 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001041}
1042
Johannes Doerferte58a0122014-06-27 20:31:28 +00001043/// @brief Collect loads which might form a reduction chain with @p StoreMA
1044///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001045/// Check if the stored value for @p StoreMA is a binary operator with one or
1046/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001047/// used only once (by @p StoreMA) and its load operands are also used only
1048/// once, we have found a possible reduction chain. It starts at an operand
1049/// load and includes the binary operator and @p StoreMA.
1050///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001051/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001052/// escape this block or into any other store except @p StoreMA.
1053void ScopStmt::collectCandiateReductionLoads(
1054 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1055 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1056 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001057 return;
1058
1059 // Skip if there is not one binary operator between the load and the store
1060 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001061 if (!BinOp)
1062 return;
1063
1064 // Skip if the binary operators has multiple uses
1065 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001066 return;
1067
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001068 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001069 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1070 return;
1071
Johannes Doerfert9890a052014-07-01 00:32:29 +00001072 // Skip if the binary operator is outside the current SCoP
1073 if (BinOp->getParent() != Store->getParent())
1074 return;
1075
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001076 // Skip if it is a multiplicative reduction and we disabled them
1077 if (DisableMultiplicativeReductions &&
1078 (BinOp->getOpcode() == Instruction::Mul ||
1079 BinOp->getOpcode() == Instruction::FMul))
1080 return;
1081
Johannes Doerferte58a0122014-06-27 20:31:28 +00001082 // Check the binary operator operands for a candidate load
1083 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1084 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1085 if (!PossibleLoad0 && !PossibleLoad1)
1086 return;
1087
1088 // A load is only a candidate if it cannot escape (thus has only this use)
1089 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001090 if (PossibleLoad0->getParent() == Store->getParent())
1091 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001092 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001093 if (PossibleLoad1->getParent() == Store->getParent())
1094 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001095}
1096
1097/// @brief Check for reductions in this ScopStmt
1098///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001099/// Iterate over all store memory accesses and check for valid binary reduction
1100/// like chains. For all candidates we check if they have the same base address
1101/// and there are no other accesses which overlap with them. The base address
1102/// check rules out impossible reductions candidates early. The overlap check,
1103/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001104/// guarantees that none of the intermediate results will escape during
1105/// execution of the loop nest. We basically check here that no other memory
1106/// access can access the same memory as the potential reduction.
1107void ScopStmt::checkForReductions() {
1108 SmallVector<MemoryAccess *, 2> Loads;
1109 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1110
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001111 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001112 // stores and collecting possible reduction loads.
1113 for (MemoryAccess *StoreMA : MemAccs) {
1114 if (StoreMA->isRead())
1115 continue;
1116
1117 Loads.clear();
1118 collectCandiateReductionLoads(StoreMA, Loads);
1119 for (MemoryAccess *LoadMA : Loads)
1120 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1121 }
1122
1123 // Then check each possible candidate pair.
1124 for (const auto &CandidatePair : Candidates) {
1125 bool Valid = true;
1126 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1127 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1128
1129 // Skip those with obviously unequal base addresses.
1130 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1131 isl_map_free(LoadAccs);
1132 isl_map_free(StoreAccs);
1133 continue;
1134 }
1135
1136 // And check if the remaining for overlap with other memory accesses.
1137 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1138 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1139 isl_set *AllAccs = isl_map_range(AllAccsRel);
1140
1141 for (MemoryAccess *MA : MemAccs) {
1142 if (MA == CandidatePair.first || MA == CandidatePair.second)
1143 continue;
1144
1145 isl_map *AccRel =
1146 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1147 isl_set *Accs = isl_map_range(AccRel);
1148
1149 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1150 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1151 Valid = Valid && isl_set_is_empty(OverlapAccs);
1152 isl_set_free(OverlapAccs);
1153 }
1154 }
1155
1156 isl_set_free(AllAccs);
1157 if (!Valid)
1158 continue;
1159
Johannes Doerfertf6183392014-07-01 20:52:51 +00001160 const LoadInst *Load =
1161 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1162 MemoryAccess::ReductionType RT =
1163 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1164
Johannes Doerferte58a0122014-06-27 20:31:28 +00001165 // If no overlapping access was found we mark the load and store as
1166 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001167 CandidatePair.first->markAsReductionLike(RT);
1168 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001169 }
Tobias Grosser75805372011-04-29 06:27:02 +00001170}
1171
Tobias Grosser74394f02013-01-14 22:40:23 +00001172std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001173
1174std::string ScopStmt::getScatteringStr() const {
Tobias Grossercf3942d2011-10-06 00:04:05 +00001175 return stringFromIslObj(Scattering);
Tobias Grosser75805372011-04-29 06:27:02 +00001176}
1177
Tobias Grosser74394f02013-01-14 22:40:23 +00001178unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001179
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001180unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001181
1182unsigned ScopStmt::getNumScattering() const {
1183 return isl_map_dim(Scattering, isl_dim_out);
1184}
1185
1186const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1187
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001188const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001189 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001190}
1191
Tobias Grosser74394f02013-01-14 22:40:23 +00001192isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001193
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001194__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001195
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001196_isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001197 return isl_set_get_space(Domain);
1198}
1199
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001200__isl_give isl_id *ScopStmt::getDomainId() const {
1201 return isl_set_get_tuple_id(Domain);
1202}
Tobias Grossercd95b772012-08-30 11:49:38 +00001203
Tobias Grosser75805372011-04-29 06:27:02 +00001204ScopStmt::~ScopStmt() {
1205 while (!MemAccs.empty()) {
1206 delete MemAccs.back();
1207 MemAccs.pop_back();
1208 }
1209
1210 isl_set_free(Domain);
1211 isl_map_free(Scattering);
1212}
1213
1214void ScopStmt::print(raw_ostream &OS) const {
1215 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001216 OS.indent(12) << "Domain :=\n";
1217
1218 if (Domain) {
1219 OS.indent(16) << getDomainStr() << ";\n";
1220 } else
1221 OS.indent(16) << "n/a\n";
1222
1223 OS.indent(12) << "Scattering :=\n";
1224
1225 if (Domain) {
1226 OS.indent(16) << getScatteringStr() << ";\n";
1227 } else
1228 OS.indent(16) << "n/a\n";
1229
Tobias Grosser083d3d32014-06-28 08:59:45 +00001230 for (MemoryAccess *Access : MemAccs)
1231 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001232}
1233
1234void ScopStmt::dump() const { print(dbgs()); }
1235
1236//===----------------------------------------------------------------------===//
1237/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001238
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001239void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001240 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1241 isl_set_free(Context);
1242 Context = NewContext;
1243}
1244
Tobias Grosserabfbe632013-02-05 12:09:06 +00001245void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001246 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001247 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001248 if (ParameterIds.find(Parameter) != ParameterIds.end())
1249 continue;
1250
1251 int dimension = Parameters.size();
1252
1253 Parameters.push_back(Parameter);
1254 ParameterIds[Parameter] = dimension;
1255 }
1256}
1257
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001258__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1259 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001260
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001261 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001262 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001263
Tobias Grosser8f99c162011-11-15 11:38:55 +00001264 std::string ParameterName;
1265
1266 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1267 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001268 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001269 }
1270
1271 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001272 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001273
Tobias Grosser20532b82014-04-11 17:56:49 +00001274 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1275 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001276}
Tobias Grosser75805372011-04-29 06:27:02 +00001277
Tobias Grosser6be480c2011-11-08 15:41:13 +00001278void Scop::buildContext() {
1279 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001280 Context = isl_set_universe(isl_space_copy(Space));
1281 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001282}
1283
Tobias Grosser18daaca2012-05-22 10:47:27 +00001284void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001285 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001286 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001287
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001288 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001289
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001290 // TODO: Find a case where the full set is actually helpful.
1291 if (SRange.isFullSet())
Tobias Grosser55bc4c02015-01-08 19:26:53 +00001292 continue;
1293
Johannes Doerferte7044942015-02-24 11:58:30 +00001294 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001295 }
1296}
1297
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001298void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001299 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001300 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001301
Tobias Grosser083d3d32014-06-28 08:59:45 +00001302 for (const auto &ParamID : ParameterIds) {
1303 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001304 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001305 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001306 }
1307
1308 // Align the parameters of all data structures to the model.
1309 Context = isl_set_align_params(Context, Space);
1310
Tobias Grosser083d3d32014-06-28 08:59:45 +00001311 for (ScopStmt *Stmt : *this)
1312 Stmt->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001313}
1314
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001315void Scop::simplifyAssumedContext() {
1316 // The parameter constraints of the iteration domains give us a set of
1317 // constraints that need to hold for all cases where at least a single
1318 // statement iteration is executed in the whole scop. We now simplify the
1319 // assumed context under the assumption that such constraints hold and at
1320 // least a single statement iteration is executed. For cases where no
1321 // statement instances are executed, the assumptions we have taken about
1322 // the executed code do not matter and can be changed.
1323 //
1324 // WARNING: This only holds if the assumptions we have taken do not reduce
1325 // the set of statement instances that are executed. Otherwise we
1326 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001327 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001328 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001329 // performed. In such a case, modifying the run-time conditions and
1330 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001331 // to not be executed.
1332 //
1333 // Example:
1334 //
1335 // When delinearizing the following code:
1336 //
1337 // for (long i = 0; i < 100; i++)
1338 // for (long j = 0; j < m; j++)
1339 // A[i+p][j] = 1.0;
1340 //
1341 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001342 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001343 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1344 AssumedContext =
1345 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001346 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001347}
1348
Johannes Doerfertb164c792014-09-18 11:17:17 +00001349/// @brief Add the minimal/maximal access in @p Set to @p User.
1350static int buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
1351 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1352 isl_pw_multi_aff *MinPMA, *MaxPMA;
1353 isl_pw_aff *LastDimAff;
1354 isl_aff *OneAff;
1355 unsigned Pos;
1356
Johannes Doerfert9143d672014-09-27 11:02:39 +00001357 // Restrict the number of parameters involved in the access as the lexmin/
1358 // lexmax computation will take too long if this number is high.
1359 //
1360 // Experiments with a simple test case using an i7 4800MQ:
1361 //
1362 // #Parameters involved | Time (in sec)
1363 // 6 | 0.01
1364 // 7 | 0.04
1365 // 8 | 0.12
1366 // 9 | 0.40
1367 // 10 | 1.54
1368 // 11 | 6.78
1369 // 12 | 30.38
1370 //
1371 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1372 unsigned InvolvedParams = 0;
1373 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1374 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1375 InvolvedParams++;
1376
1377 if (InvolvedParams > RunTimeChecksMaxParameters) {
1378 isl_set_free(Set);
1379 return -1;
1380 }
1381 }
1382
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001383 Set = isl_set_remove_divs(Set);
1384
Johannes Doerfertb164c792014-09-18 11:17:17 +00001385 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1386 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1387
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001388 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1389 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1390
Johannes Doerfertb164c792014-09-18 11:17:17 +00001391 // Adjust the last dimension of the maximal access by one as we want to
1392 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1393 // we test during code generation might now point after the end of the
1394 // allocated array but we will never dereference it anyway.
1395 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1396 "Assumed at least one output dimension");
1397 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1398 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1399 OneAff = isl_aff_zero_on_domain(
1400 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1401 OneAff = isl_aff_add_constant_si(OneAff, 1);
1402 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1403 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1404
1405 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1406
1407 isl_set_free(Set);
1408 return 0;
1409}
1410
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001411static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1412 isl_set *Domain = MA->getStatement()->getDomain();
1413 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1414 return isl_set_reset_tuple_id(Domain);
1415}
1416
Johannes Doerfert9143d672014-09-27 11:02:39 +00001417bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001418 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001419 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001420 // for all memory accesses inside the SCoP.
1421 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001422 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001423 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001424 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001425 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001426 // if their access domains intersect, otherwise they are in different
1427 // ones.
Johannes Doerfert13771732014-10-01 12:40:46 +00001428 // o) We split groups such that they contain at most one read only base
1429 // address.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001430 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfertb164c792014-09-18 11:17:17 +00001431 // and maximal accesses to each array in this group.
1432 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1433
1434 AliasSetTracker AST(AA);
1435
1436 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001437 DenseSet<Value *> HasWriteAccess;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001438 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001439
1440 // Skip statements with an empty domain as they will never be executed.
1441 isl_set *StmtDomain = Stmt->getDomain();
1442 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1443 isl_set_free(StmtDomain);
1444 if (StmtDomainEmpty)
1445 continue;
1446
Johannes Doerfertb164c792014-09-18 11:17:17 +00001447 for (MemoryAccess *MA : *Stmt) {
1448 if (MA->isScalar())
1449 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001450 if (!MA->isRead())
1451 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001452 Instruction *Acc = MA->getAccessInstruction();
1453 PtrToAcc[getPointerOperand(*Acc)] = MA;
1454 AST.add(Acc);
1455 }
1456 }
1457
1458 SmallVector<AliasGroupTy, 4> AliasGroups;
1459 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001460 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001461 continue;
1462 AliasGroupTy AG;
1463 for (auto PR : AS)
1464 AG.push_back(PtrToAcc[PR.getValue()]);
1465 assert(AG.size() > 1 &&
1466 "Alias groups should contain at least two accesses");
1467 AliasGroups.push_back(std::move(AG));
1468 }
1469
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001470 // Split the alias groups based on their domain.
1471 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1472 AliasGroupTy NewAG;
1473 AliasGroupTy &AG = AliasGroups[u];
1474 AliasGroupTy::iterator AGI = AG.begin();
1475 isl_set *AGDomain = getAccessDomain(*AGI);
1476 while (AGI != AG.end()) {
1477 MemoryAccess *MA = *AGI;
1478 isl_set *MADomain = getAccessDomain(MA);
1479 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1480 NewAG.push_back(MA);
1481 AGI = AG.erase(AGI);
1482 isl_set_free(MADomain);
1483 } else {
1484 AGDomain = isl_set_union(AGDomain, MADomain);
1485 AGI++;
1486 }
1487 }
1488 if (NewAG.size() > 1)
1489 AliasGroups.push_back(std::move(NewAG));
1490 isl_set_free(AGDomain);
1491 }
1492
Johannes Doerfert13771732014-10-01 12:40:46 +00001493 DenseMap<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
1494 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1495 for (AliasGroupTy &AG : AliasGroups) {
1496 NonReadOnlyBaseValues.clear();
1497 ReadOnlyPairs.clear();
1498
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001499 if (AG.size() < 2) {
1500 AG.clear();
1501 continue;
1502 }
1503
Johannes Doerfert13771732014-10-01 12:40:46 +00001504 for (auto II = AG.begin(); II != AG.end();) {
1505 Value *BaseAddr = (*II)->getBaseAddr();
1506 if (HasWriteAccess.count(BaseAddr)) {
1507 NonReadOnlyBaseValues.insert(BaseAddr);
1508 II++;
1509 } else {
1510 ReadOnlyPairs[BaseAddr].insert(*II);
1511 II = AG.erase(II);
1512 }
1513 }
1514
1515 // If we don't have read only pointers check if there are at least two
1516 // non read only pointers, otherwise clear the alias group.
1517 if (ReadOnlyPairs.empty()) {
1518 if (NonReadOnlyBaseValues.size() <= 1)
1519 AG.clear();
1520 continue;
1521 }
1522
1523 // If we don't have non read only pointers clear the alias group.
1524 if (NonReadOnlyBaseValues.empty()) {
1525 AG.clear();
1526 continue;
1527 }
1528
1529 // If we have both read only and non read only base pointers we combine
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001530 // the non read only ones with exactly one read only one at a time into a
Johannes Doerfert13771732014-10-01 12:40:46 +00001531 // new alias group and clear the old alias group in the end.
1532 for (const auto &ReadOnlyPair : ReadOnlyPairs) {
1533 AliasGroupTy AGNonReadOnly = AG;
1534 for (MemoryAccess *MA : ReadOnlyPair.second)
1535 AGNonReadOnly.push_back(MA);
1536 AliasGroups.push_back(std::move(AGNonReadOnly));
1537 }
1538 AG.clear();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001539 }
1540
1541 for (AliasGroupTy &AG : AliasGroups) {
Johannes Doerfert13771732014-10-01 12:40:46 +00001542 if (AG.empty())
1543 continue;
1544
Johannes Doerfertb164c792014-09-18 11:17:17 +00001545 MinMaxVectorTy *MinMaxAccesses = new MinMaxVectorTy();
1546 MinMaxAccesses->reserve(AG.size());
1547
1548 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
1549 for (MemoryAccess *MA : AG)
1550 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1551 Accesses = isl_union_map_intersect_domain(Accesses, getDomains());
1552
1553 isl_union_set *Locations = isl_union_map_range(Accesses);
1554 Locations = isl_union_set_intersect_params(Locations, getAssumedContext());
1555 Locations = isl_union_set_coalesce(Locations);
1556 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001557 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
1558 MinMaxAccesses));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001559 isl_union_set_free(Locations);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001560 MinMaxAliasGroups.push_back(MinMaxAccesses);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001561
1562 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001563 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001564 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001565
Tobias Grosser71500722015-03-28 15:11:14 +00001566 // Bail out if the number of values we need to compare is too large.
1567 // This is important as the number of comparisions grows quadratically with
1568 // the number of values we need to compare.
1569 for (const auto *Values : MinMaxAliasGroups)
1570 if (Values->size() > RunTimeChecksMaxArraysPerGroup)
1571 return false;
1572
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001573 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001574}
1575
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001576static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI) {
1577 unsigned MinLD = INT_MAX, MaxLD = 0;
1578 for (BasicBlock *BB : R.blocks()) {
1579 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001580 if (!R.contains(L))
1581 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001582 unsigned LD = L->getLoopDepth();
1583 MinLD = std::min(MinLD, LD);
1584 MaxLD = std::max(MaxLD, LD);
1585 }
1586 }
1587
1588 // Handle the case that there is no loop in the SCoP first.
1589 if (MaxLD == 0)
1590 return 1;
1591
1592 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1593 assert(MaxLD >= MinLD &&
1594 "Maximal loop depth was smaller than mininaml loop depth?");
1595 return MaxLD - MinLD + 1;
1596}
1597
Tobias Grosser3f296192015-01-01 23:01:11 +00001598void Scop::dropConstantScheduleDims() {
1599 isl_union_map *FullSchedule = getSchedule();
1600
1601 if (isl_union_map_n_map(FullSchedule) == 0) {
1602 isl_union_map_free(FullSchedule);
1603 return;
1604 }
1605
1606 isl_set *ScheduleSpace =
1607 isl_set_from_union_set(isl_union_map_range(FullSchedule));
1608 isl_map *DropDimMap = isl_set_identity(isl_set_copy(ScheduleSpace));
1609
1610 int NumDimsDropped = 0;
Johannes Doerfert3f21e272015-03-04 22:23:21 +00001611 for (unsigned i = 0; i < isl_set_dim(ScheduleSpace, isl_dim_set); i += 2) {
1612 isl_val *FixedVal =
1613 isl_set_plain_get_val_if_fixed(ScheduleSpace, isl_dim_set, i);
1614 if (isl_val_is_int(FixedVal)) {
1615 DropDimMap =
1616 isl_map_project_out(DropDimMap, isl_dim_out, i - NumDimsDropped, 1);
1617 NumDimsDropped++;
Tobias Grosser3f296192015-01-01 23:01:11 +00001618 }
Johannes Doerfert3f21e272015-03-04 22:23:21 +00001619 isl_val_free(FixedVal);
1620 }
Tobias Grosser3f296192015-01-01 23:01:11 +00001621
Tobias Grosser3f296192015-01-01 23:01:11 +00001622 for (auto *S : *this) {
1623 isl_map *Schedule = S->getScattering();
1624 Schedule = isl_map_apply_range(Schedule, isl_map_copy(DropDimMap));
1625 S->setScattering(Schedule);
1626 }
1627 isl_set_free(ScheduleSpace);
1628 isl_map_free(DropDimMap);
1629}
1630
Tobias Grosser0e27e242011-10-06 00:03:48 +00001631Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001632 ScopDetection &SD, isl_ctx *Context)
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001633 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()), IsOptimized(false),
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001634 MaxLoopDepth(getMaxLoopDepthInRegion(tempScop.getMaxRegion(), LI)) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001635 IslCtx = Context;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001636
Tobias Grosser6be480c2011-11-08 15:41:13 +00001637 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001638
Tobias Grosserabfbe632013-02-05 12:09:06 +00001639 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001640 SmallVector<unsigned, 8> Scatter;
1641
1642 Scatter.assign(MaxLoopDepth + 1, 0);
1643
1644 // Build the iteration domain, access functions and scattering functions
1645 // traversing the region tree.
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001646 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI, SD);
Tobias Grosser75805372011-04-29 06:27:02 +00001647
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001648 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001649 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001650 simplifyAssumedContext();
Tobias Grosser3f296192015-01-01 23:01:11 +00001651 dropConstantScheduleDims();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001652
Tobias Grosser75805372011-04-29 06:27:02 +00001653 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1654}
1655
1656Scop::~Scop() {
1657 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001658 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001659
1660 // Free the statements;
Tobias Grosser083d3d32014-06-28 08:59:45 +00001661 for (ScopStmt *Stmt : *this)
1662 delete Stmt;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001663
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001664 // Free the ScopArrayInfo objects.
1665 for (auto &ScopArrayInfoPair : ScopArrayInfoMap)
1666 delete ScopArrayInfoPair.second;
1667
Johannes Doerfertb164c792014-09-18 11:17:17 +00001668 // Free the alias groups
1669 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1670 for (MinMaxAccessTy &MMA : *MinMaxAccesses) {
1671 isl_pw_multi_aff_free(MMA.first);
1672 isl_pw_multi_aff_free(MMA.second);
1673 }
1674 delete MinMaxAccesses;
1675 }
Tobias Grosser75805372011-04-29 06:27:02 +00001676}
1677
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001678const ScopArrayInfo *
1679Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
1680 const SmallVector<const SCEV *, 4> &Sizes) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001681 const ScopArrayInfo *&SAI = ScopArrayInfoMap[BasePtr];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001682 if (!SAI)
1683 SAI = new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001684 return SAI;
1685}
1686
1687const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr) {
1688 const SCEV *PtrSCEV = SE->getSCEV(BasePtr);
1689 const SCEVUnknown *PtrBaseSCEV =
1690 cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
1691 const ScopArrayInfo *SAI = ScopArrayInfoMap[PtrBaseSCEV->getValue()];
1692 assert(SAI && "No ScopArrayInfo available for this base pointer");
1693 return SAI;
1694}
1695
Tobias Grosser74394f02013-01-14 22:40:23 +00001696std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001697std::string Scop::getAssumedContextStr() const {
1698 return stringFromIslObj(AssumedContext);
1699}
Tobias Grosser75805372011-04-29 06:27:02 +00001700
1701std::string Scop::getNameStr() const {
1702 std::string ExitName, EntryName;
1703 raw_string_ostream ExitStr(ExitName);
1704 raw_string_ostream EntryStr(EntryName);
1705
Tobias Grosserf240b482014-01-09 10:42:15 +00001706 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001707 EntryStr.str();
1708
1709 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001710 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001711 ExitStr.str();
1712 } else
1713 ExitName = "FunctionExit";
1714
1715 return EntryName + "---" + ExitName;
1716}
1717
Tobias Grosser74394f02013-01-14 22:40:23 +00001718__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001719__isl_give isl_space *Scop::getParamSpace() const {
1720 return isl_set_get_space(this->Context);
1721}
1722
Tobias Grossere86109f2013-10-29 21:05:49 +00001723__isl_give isl_set *Scop::getAssumedContext() const {
1724 return isl_set_copy(AssumedContext);
1725}
1726
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001727void Scop::addAssumption(__isl_take isl_set *Set) {
1728 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001729 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001730}
1731
Tobias Grosser75805372011-04-29 06:27:02 +00001732void Scop::printContext(raw_ostream &OS) const {
1733 OS << "Context:\n";
1734
1735 if (!Context) {
1736 OS.indent(4) << "n/a\n\n";
1737 return;
1738 }
1739
1740 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001741
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001742 OS.indent(4) << "Assumed Context:\n";
1743 if (!AssumedContext) {
1744 OS.indent(4) << "n/a\n\n";
1745 return;
1746 }
1747
1748 OS.indent(4) << getAssumedContextStr() << "\n";
1749
Tobias Grosser083d3d32014-06-28 08:59:45 +00001750 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001751 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001752 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1753 }
Tobias Grosser75805372011-04-29 06:27:02 +00001754}
1755
Johannes Doerfertb164c792014-09-18 11:17:17 +00001756void Scop::printAliasAssumptions(raw_ostream &OS) const {
1757 OS.indent(4) << "Alias Groups (" << MinMaxAliasGroups.size() << "):\n";
1758 if (MinMaxAliasGroups.empty()) {
1759 OS.indent(8) << "n/a\n";
1760 return;
1761 }
1762 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1763 OS.indent(8) << "[[";
1764 for (MinMaxAccessTy &MinMacAccess : *MinMaxAccesses)
1765 OS << " <" << MinMacAccess.first << ", " << MinMacAccess.second << ">";
1766 OS << " ]]\n";
1767 }
1768}
1769
Tobias Grosser75805372011-04-29 06:27:02 +00001770void Scop::printStatements(raw_ostream &OS) const {
1771 OS << "Statements {\n";
1772
Tobias Grosser083d3d32014-06-28 08:59:45 +00001773 for (ScopStmt *Stmt : *this)
1774 OS.indent(4) << *Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001775
1776 OS.indent(4) << "}\n";
1777}
1778
Tobias Grosser75805372011-04-29 06:27:02 +00001779void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001780 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1781 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001782 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00001783 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001784 printContext(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001785 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001786 printStatements(OS.indent(4));
1787}
1788
1789void Scop::dump() const { print(dbgs()); }
1790
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001791isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001792
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001793__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001794 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001795
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001796 for (ScopStmt *Stmt : *this)
1797 Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001798
1799 return Domain;
1800}
1801
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001802__isl_give isl_union_map *Scop::getMustWrites() {
1803 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1804
1805 for (ScopStmt *Stmt : *this) {
1806 for (MemoryAccess *MA : *Stmt) {
1807 if (!MA->isMustWrite())
1808 continue;
1809
1810 isl_set *Domain = Stmt->getDomain();
1811 isl_map *AccessDomain = MA->getAccessRelation();
1812 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1813 Write = isl_union_map_add_map(Write, AccessDomain);
1814 }
1815 }
1816 return isl_union_map_coalesce(Write);
1817}
1818
1819__isl_give isl_union_map *Scop::getMayWrites() {
1820 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1821
1822 for (ScopStmt *Stmt : *this) {
1823 for (MemoryAccess *MA : *Stmt) {
1824 if (!MA->isMayWrite())
1825 continue;
1826
1827 isl_set *Domain = Stmt->getDomain();
1828 isl_map *AccessDomain = MA->getAccessRelation();
1829 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1830 Write = isl_union_map_add_map(Write, AccessDomain);
1831 }
1832 }
1833 return isl_union_map_coalesce(Write);
1834}
1835
Tobias Grosser37eb4222014-02-20 21:43:54 +00001836__isl_give isl_union_map *Scop::getWrites() {
1837 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1838
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001839 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001840 for (MemoryAccess *MA : *Stmt) {
1841 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001842 continue;
1843
1844 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001845 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001846 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1847 Write = isl_union_map_add_map(Write, AccessDomain);
1848 }
1849 }
1850 return isl_union_map_coalesce(Write);
1851}
1852
1853__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001854 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001855
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001856 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001857 for (MemoryAccess *MA : *Stmt) {
1858 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001859 continue;
1860
1861 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001862 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001863
1864 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1865 Read = isl_union_map_add_map(Read, AccessDomain);
1866 }
1867 }
1868 return isl_union_map_coalesce(Read);
1869}
1870
1871__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001872 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001873
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001874 for (ScopStmt *Stmt : *this)
Tobias Grosser37eb4222014-02-20 21:43:54 +00001875 Schedule = isl_union_map_add_map(Schedule, Stmt->getScattering());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001876
Tobias Grosser37eb4222014-02-20 21:43:54 +00001877 return isl_union_map_coalesce(Schedule);
1878}
1879
1880bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1881 bool Changed = false;
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001882 for (ScopStmt *Stmt : *this) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00001883 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001884 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1885 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1886
1887 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1888 isl_union_set_free(StmtDomain);
1889 isl_union_set_free(NewStmtDomain);
1890 continue;
1891 }
1892
1893 Changed = true;
1894
1895 isl_union_set_free(StmtDomain);
1896 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1897
1898 if (isl_union_set_is_empty(NewStmtDomain)) {
1899 Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1900 isl_union_set_free(NewStmtDomain);
1901 } else
1902 Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1903 }
1904 isl_union_set_free(Domain);
1905 return Changed;
1906}
1907
Tobias Grosser75805372011-04-29 06:27:02 +00001908ScalarEvolution *Scop::getSE() const { return SE; }
1909
1910bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1911 if (tempScop.getAccessFunctions(BB))
1912 return false;
1913
1914 return true;
1915}
1916
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001917void Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
1918 const Region &CurRegion,
1919 SmallVectorImpl<Loop *> &NestLoops,
1920 SmallVectorImpl<unsigned> &Scatter) {
1921 ScopStmt *Stmt;
1922
1923 if (BB) {
1924 Stmt = new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, Scatter);
1925 StmtMap[BB] = Stmt;
1926 } else {
1927 assert(R && "Either a basic block or a region is needed to "
1928 "create a new SCoP stmt.");
1929 Stmt = new ScopStmt(*this, tempScop, CurRegion, *R, NestLoops, Scatter);
1930 for (BasicBlock *BB : R->blocks())
1931 StmtMap[BB] = Stmt;
1932 }
1933
1934 // Insert all statements into the statement map and the statement vector.
1935 Stmts.push_back(Stmt);
1936
1937 // Increasing the Scattering function is OK for the moment, because
1938 // we are using a depth first iterator and the program is well structured.
1939 ++Scatter[NestLoops.size()];
1940}
1941
Tobias Grosser74394f02013-01-14 22:40:23 +00001942void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
1943 SmallVectorImpl<Loop *> &NestLoops,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001944 SmallVectorImpl<unsigned> &Scatter, LoopInfo &LI,
1945 ScopDetection &SD) {
1946 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion()))
1947 return addScopStmt(nullptr, const_cast<Region *>(&CurRegion), tempScop,
1948 CurRegion, NestLoops, Scatter);
1949
Tobias Grosser75805372011-04-29 06:27:02 +00001950 Loop *L = castToLoop(CurRegion, LI);
1951
1952 if (L)
1953 NestLoops.push_back(L);
1954
1955 unsigned loopDepth = NestLoops.size();
1956 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
1957
1958 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00001959 E = CurRegion.element_end();
1960 I != E; ++I)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001961 if (I->isSubRegion()) {
1962 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, Scatter, LI, SD);
1963 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001964 BasicBlock *BB = I->getNodeAs<BasicBlock>();
1965
1966 if (isTrivialBB(BB, tempScop))
1967 continue;
1968
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001969 addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops, Scatter);
Tobias Grosser75805372011-04-29 06:27:02 +00001970 }
1971
1972 if (!L)
1973 return;
1974
1975 // Exiting a loop region.
1976 Scatter[loopDepth] = 0;
1977 NestLoops.pop_back();
Tobias Grosser74394f02013-01-14 22:40:23 +00001978 ++Scatter[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00001979}
1980
Johannes Doerfert7c494212014-10-31 23:13:39 +00001981ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
1982 const auto &StmtMapIt = StmtMap.find(BB);
1983 if (StmtMapIt == StmtMap.end())
1984 return nullptr;
1985 return StmtMapIt->second;
1986}
1987
Tobias Grosser75805372011-04-29 06:27:02 +00001988//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00001989ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
1990 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00001991 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001992}
1993
1994ScopInfo::~ScopInfo() {
1995 clear();
1996 isl_ctx_free(ctx);
1997}
1998
Tobias Grosser75805372011-04-29 06:27:02 +00001999void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002000 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002001 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00002002 AU.addRequired<ScalarEvolution>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002003 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002004 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002005 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00002006 AU.setPreservesAll();
2007}
2008
2009bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002010 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002011 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002012 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002013 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
2014
2015 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
2016
2017 // This region is no Scop.
2018 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002019 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002020 return false;
2021 }
2022
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002023 scop = new Scop(*tempScop, LI, SE, SD, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002024
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002025 if (!PollyUseRuntimeAliasChecks) {
2026 // Statistics.
2027 ++ScopFound;
2028 if (scop->getMaxLoopDepth() > 0)
2029 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002030 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002031 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002032
Johannes Doerfert9143d672014-09-27 11:02:39 +00002033 // If a problem occurs while building the alias groups we need to delete
2034 // this SCoP and pretend it wasn't valid in the first place.
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002035 if (scop->buildAliasGroups(AA)) {
2036 // Statistics.
2037 ++ScopFound;
2038 if (scop->getMaxLoopDepth() > 0)
2039 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002040 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002041 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002042
2043 DEBUG(dbgs()
2044 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002045 << " could not be created as the number of parameters involved is too "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002046 "high. The SCoP will be "
2047 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002048 "maximal number of parameters but be advised that the compile time "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002049 "might increase exponentially.\n\n");
2050
2051 delete scop;
2052 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002053 return false;
2054}
2055
2056char ScopInfo::ID = 0;
2057
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002058Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2059
Tobias Grosser73600b82011-10-08 00:30:40 +00002060INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2061 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002062 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002063INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002064INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002065INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002066INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002067INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002068INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00002069INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2070 "Polly - Create polyhedral description of Scops", false,
2071 false)