blob: ac4c4e742eed3ae4a260fd2e6f4e495b88f4e3d8 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000026#include "polly/TempScopInfo.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000028#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "llvm/ADT/Statistic.h"
Johannes Doerfertecff11d2015-05-22 23:43:58 +000030#include "llvm/ADT/STLExtras.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000033#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000034#include "llvm/Analysis/RegionIterator.h"
35#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000036#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000037#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000038#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000039#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000040#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000041#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000043#include "isl/schedule.h"
44#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000045#include "isl/set.h"
46#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000047#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000048#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include <sstream>
50#include <string>
51#include <vector>
52
53using namespace llvm;
54using namespace polly;
55
Chandler Carruth95fef942014-04-22 03:30:19 +000056#define DEBUG_TYPE "polly-scops"
57
Tobias Grosser74394f02013-01-14 22:40:23 +000058STATISTIC(ScopFound, "Number of valid Scops");
59STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000060
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000061// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000062// operations can overflow easily. Additive reductions and bit operations
63// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000064static cl::opt<bool> DisableMultiplicativeReductions(
65 "polly-disable-multiplicative-reductions",
66 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
67 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000068
Johannes Doerfert9143d672014-09-27 11:02:39 +000069static cl::opt<unsigned> RunTimeChecksMaxParameters(
70 "polly-rtc-max-parameters",
71 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
72 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
73
Tobias Grosser71500722015-03-28 15:11:14 +000074static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
75 "polly-rtc-max-arrays-per-group",
76 cl::desc("The maximal number of arrays to compare in each alias group."),
77 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000078static cl::opt<std::string> UserContextStr(
79 "polly-context", cl::value_desc("isl parameter set"),
80 cl::desc("Provide additional constraints on the context parameters"),
81 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000082
Tobias Grosserd83b8a82015-08-20 19:08:11 +000083static cl::opt<bool> DetectReductions("polly-detect-reductions",
84 cl::desc("Detect and exploit reductions"),
85 cl::Hidden, cl::ZeroOrMore,
86 cl::init(true), cl::cat(PollyCategory));
87
Michael Kruse046dde42015-08-10 13:01:57 +000088// Create a sequence of two schedules. Either argument may be null and is
89// interpreted as the empty schedule. Can also return null if both schedules are
90// empty.
91static __isl_give isl_schedule *
92combineInSequence(__isl_take isl_schedule *Prev,
93 __isl_take isl_schedule *Succ) {
94 if (!Prev)
95 return Succ;
96 if (!Succ)
97 return Prev;
98
99 return isl_schedule_sequence(Prev, Succ);
100}
101
Johannes Doerferte7044942015-02-24 11:58:30 +0000102static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
103 const ConstantRange &Range,
104 int dim,
105 enum isl_dim_type type) {
106 isl_val *V;
107 isl_ctx *ctx = isl_set_get_ctx(S);
108
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000109 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
110 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000111 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000112 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
113
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000114 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000115 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000116 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000117 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000118 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
119
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000120 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000121 return isl_set_union(SLB, SUB);
122 else
123 return isl_set_intersect(SLB, SUB);
124}
125
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000126static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
127 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
128 if (!BasePtrLI)
129 return nullptr;
130
131 if (!S->getRegion().contains(BasePtrLI))
132 return nullptr;
133
134 ScalarEvolution &SE = *S->getSE();
135
136 auto *OriginBaseSCEV =
137 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
138 if (!OriginBaseSCEV)
139 return nullptr;
140
141 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
142 if (!OriginBaseSCEVUnknown)
143 return nullptr;
144
145 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
146}
147
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000148ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser92245222015-07-28 14:53:44 +0000149 const SmallVector<const SCEV *, 4> &DimensionSizes,
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000150 bool IsPHI, Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000151 : BasePtr(BasePtr), ElementType(ElementType),
Tobias Grosser92245222015-07-28 14:53:44 +0000152 DimensionSizes(DimensionSizes), IsPHI(IsPHI) {
153 std::string BasePtrName =
154 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000155 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000156 for (const SCEV *Expr : DimensionSizes) {
157 isl_pw_aff *Size = S->getPwAff(Expr);
158 DimensionSizesPw.push_back(Size);
159 }
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000160
161 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
162 if (BasePtrOriginSAI)
163 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000164}
165
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000166ScopArrayInfo::~ScopArrayInfo() {
167 isl_id_free(Id);
168 for (isl_pw_aff *Size : DimensionSizesPw)
169 isl_pw_aff_free(Size);
170}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000171
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000172std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
173
174int ScopArrayInfo::getElemSizeInBytes() const {
175 return ElementType->getPrimitiveSizeInBits() / 8;
176}
177
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000178isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
179
180void ScopArrayInfo::dump() const { print(errs()); }
181
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000182void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000183 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000184 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
185 OS << "[";
186
187 if (SizeAsPwAff)
188 OS << " " << DimensionSizesPw[u] << " ";
189 else
190 OS << *DimensionSizes[u];
191
192 OS << "]";
193 }
194
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000195 if (BasePtrOriginSAI)
196 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
197
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000198 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000199}
200
201const ScopArrayInfo *
202ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
203 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
204 assert(Id && "Output dimension didn't have an ID");
205 return getFromId(Id);
206}
207
208const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
209 void *User = isl_id_get_user(Id);
210 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
211 isl_id_free(Id);
212 return SAI;
213}
214
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000215const std::string
216MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
217 switch (RT) {
218 case MemoryAccess::RT_NONE:
219 llvm_unreachable("Requested a reduction operator string for a memory "
220 "access which isn't a reduction");
221 case MemoryAccess::RT_ADD:
222 return "+";
223 case MemoryAccess::RT_MUL:
224 return "*";
225 case MemoryAccess::RT_BOR:
226 return "|";
227 case MemoryAccess::RT_BXOR:
228 return "^";
229 case MemoryAccess::RT_BAND:
230 return "&";
231 }
232 llvm_unreachable("Unknown reduction type");
233 return "";
234}
235
Johannes Doerfertf6183392014-07-01 20:52:51 +0000236/// @brief Return the reduction type for a given binary operator
237static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
238 const Instruction *Load) {
239 if (!BinOp)
240 return MemoryAccess::RT_NONE;
241 switch (BinOp->getOpcode()) {
242 case Instruction::FAdd:
243 if (!BinOp->hasUnsafeAlgebra())
244 return MemoryAccess::RT_NONE;
245 // Fall through
246 case Instruction::Add:
247 return MemoryAccess::RT_ADD;
248 case Instruction::Or:
249 return MemoryAccess::RT_BOR;
250 case Instruction::Xor:
251 return MemoryAccess::RT_BXOR;
252 case Instruction::And:
253 return MemoryAccess::RT_BAND;
254 case Instruction::FMul:
255 if (!BinOp->hasUnsafeAlgebra())
256 return MemoryAccess::RT_NONE;
257 // Fall through
258 case Instruction::Mul:
259 if (DisableMultiplicativeReductions)
260 return MemoryAccess::RT_NONE;
261 return MemoryAccess::RT_MUL;
262 default:
263 return MemoryAccess::RT_NONE;
264 }
265}
Tobias Grosser75805372011-04-29 06:27:02 +0000266//===----------------------------------------------------------------------===//
267
268MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000269 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000270 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000271 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000272}
273
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000274static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
275 switch (Access.getType()) {
276 case IRAccess::READ:
277 return MemoryAccess::READ;
278 case IRAccess::MUST_WRITE:
279 return MemoryAccess::MUST_WRITE;
280 case IRAccess::MAY_WRITE:
281 return MemoryAccess::MAY_WRITE;
282 }
283 llvm_unreachable("Unknown IRAccess type!");
284}
285
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000286const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
287 isl_id *ArrayId = getArrayId();
288 void *User = isl_id_get_user(ArrayId);
289 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
290 isl_id_free(ArrayId);
291 return SAI;
292}
293
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000294__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000295 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
296}
297
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000298__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
299 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000300 isl_map *Schedule, *ScheduledAccRel;
301 isl_union_set *UDomain;
302
303 UDomain = isl_union_set_from_set(getStatement()->getDomain());
304 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
305 Schedule = isl_map_from_union_map(USchedule);
306 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
307 return isl_pw_multi_aff_from_map(ScheduledAccRel);
308}
309
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000310__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000311 return isl_map_copy(AccessRelation);
312}
313
Johannes Doerferta99130f2014-10-13 12:58:03 +0000314std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000315 return stringFromIslObj(AccessRelation);
316}
317
Johannes Doerferta99130f2014-10-13 12:58:03 +0000318__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000319 return isl_map_get_space(AccessRelation);
320}
321
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000322__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000323 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000324}
325
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000326__isl_give isl_basic_map *
327MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000328 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000329 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000330
Tobias Grosser084d8f72012-05-29 09:29:44 +0000331 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000332 isl_basic_set_universe(Statement->getDomainSpace()),
333 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000334}
335
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000336// Formalize no out-of-bound access assumption
337//
338// When delinearizing array accesses we optimistically assume that the
339// delinearized accesses do not access out of bound locations (the subscript
340// expression of each array evaluates for each statement instance that is
341// executed to a value that is larger than zero and strictly smaller than the
342// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000343// dimension for which we do not need to assume any upper bound. At this point
344// we formalize this assumption to ensure that at code generation time the
345// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000346//
347// To find the set of constraints necessary to avoid out of bound accesses, we
348// first build the set of data locations that are not within array bounds. We
349// then apply the reverse access relation to obtain the set of iterations that
350// may contain invalid accesses and reduce this set of iterations to the ones
351// that are actually executed by intersecting them with the domain of the
352// statement. If we now project out all loop dimensions, we obtain a set of
353// parameters that may cause statement instances to be executed that may
354// possibly yield out of bound memory accesses. The complement of these
355// constraints is the set of constraints that needs to be assumed to ensure such
356// statement instances are never executed.
357void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000358 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000359 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000360 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000361 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
362 isl_pw_aff *Var =
363 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
364 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
365
366 isl_set *DimOutside;
367
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000368 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000369 isl_pw_aff *SizeE = Statement->getPwAff(Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000370
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000371 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
372 Statement->getNumIterators());
373 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
374 isl_space_dim(Space, isl_dim_set));
375 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
376 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000377
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000378 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000379
380 Outside = isl_set_union(Outside, DimOutside);
381 }
382
383 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
384 Outside = isl_set_intersect(Outside, Statement->getDomain());
385 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000386
387 // Remove divs to avoid the construction of overly complicated assumptions.
388 // Doing so increases the set of parameter combinations that are assumed to
389 // not appear. This is always save, but may make the resulting run-time check
390 // bail out more often than strictly necessary.
391 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000392 Outside = isl_set_complement(Outside);
393 Statement->getParent()->addAssumption(Outside);
394 isl_space_free(Space);
395}
396
Johannes Doerferte7044942015-02-24 11:58:30 +0000397void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
398 ScalarEvolution *SE = Statement->getParent()->getSE();
399
400 Value *Ptr = getPointerOperand(*getAccessInstruction());
401 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
402 return;
403
404 auto *PtrSCEV = SE->getSCEV(Ptr);
405 if (isa<SCEVCouldNotCompute>(PtrSCEV))
406 return;
407
408 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
409 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
410 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
411
412 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
413 if (Range.isFullSet())
414 return;
415
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000416 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000417 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000418 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
419 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
420
421 auto Min = LB.sdiv(APInt(BW, ElementSize));
422 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000423
424 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
425 AccessRange =
426 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
427 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
428}
429
Tobias Grosser619190d2015-03-30 17:22:28 +0000430__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
431 __isl_take isl_map *AccessRelation,
432 ScopStmt *Statement) {
433 int Size = Access.Subscripts.size();
434
435 for (int i = Size - 2; i >= 0; --i) {
436 isl_space *Space;
437 isl_map *MapOne, *MapTwo;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000438 isl_pw_aff *DimSize = Statement->getPwAff(Access.Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000439
440 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
441 isl_pw_aff_free(DimSize);
442 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
443
444 Space = isl_map_get_space(AccessRelation);
445 Space = isl_space_map_from_set(isl_space_range(Space));
446 Space = isl_space_align_params(Space, SpaceSize);
447
448 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
449 isl_id_free(ParamId);
450
451 MapOne = isl_map_universe(isl_space_copy(Space));
452 for (int j = 0; j < Size; ++j)
453 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
454 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
455
456 MapTwo = isl_map_universe(isl_space_copy(Space));
457 for (int j = 0; j < Size; ++j)
458 if (j < i || j > i + 1)
459 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
460
461 isl_local_space *LS = isl_local_space_from_space(Space);
462 isl_constraint *C;
463 C = isl_equality_alloc(isl_local_space_copy(LS));
464 C = isl_constraint_set_constant_si(C, -1);
465 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
466 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
467 MapTwo = isl_map_add_constraint(MapTwo, C);
468 C = isl_equality_alloc(LS);
469 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
470 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
471 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
472 MapTwo = isl_map_add_constraint(MapTwo, C);
473 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
474
475 MapOne = isl_map_union(MapOne, MapTwo);
476 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
477 }
478 return AccessRelation;
479}
480
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000481MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000482 ScopStmt *Statement, const ScopArrayInfo *SAI,
483 int Identifier)
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000484 : AccType(getMemoryAccessType(Access)), Statement(Statement),
485 AccessInstruction(AccInst), AccessValue(Access.getAccessValue()),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000486 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000487
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000488 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000489 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000490 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000491
492 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000493
Tobias Grosserac3a95f2015-08-03 17:53:21 +0000494 auto IdName = "__polly_array_ref_" + std::to_string(Identifier);
Tobias Grossere29d31c2015-05-15 12:24:09 +0000495 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000496
Tobias Grossera1879642011-12-20 10:43:14 +0000497 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000498 // We overapproximate non-affine accesses with a possible access to the
499 // whole array. For read accesses it does not make a difference, if an
500 // access must or may happen. However, for write accesses it is important to
501 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000502 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000503 AccessRelation =
504 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000505
506 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000507 return;
508 }
509
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000510 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000511 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000512
Tobias Grosser79baa212014-04-10 08:38:02 +0000513 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000514 isl_pw_aff *Affine = Statement->getPwAff(Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000515
Sebastian Pop422e33f2014-06-03 18:16:31 +0000516 if (Size == 1) {
517 // For the non delinearized arrays, divide the access function of the last
518 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000519 //
520 // A stride one array access in C expressed as A[i] is expressed in
521 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
522 // two subsequent values of 'i' index two values that are stored next to
523 // each other in memory. By this division we make this characteristic
524 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000525 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000526 Affine = isl_pw_aff_scale_down_val(Affine, v);
527 }
528
529 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
530
Tobias Grosser79baa212014-04-10 08:38:02 +0000531 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000532 }
533
Tobias Grosser619190d2015-03-30 17:22:28 +0000534 AccessRelation = foldAccess(Access, AccessRelation, Statement);
535
Tobias Grosser79baa212014-04-10 08:38:02 +0000536 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000537 AccessRelation = isl_map_set_tuple_id(
538 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000539 AccessRelation =
540 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
541
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000542 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000543 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000544 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000545}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000546
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000547void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000548 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000549 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000550}
551
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000552const std::string MemoryAccess::getReductionOperatorStr() const {
553 return MemoryAccess::getReductionOperatorStr(getReductionType());
554}
555
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000556__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
557
Johannes Doerfertf6183392014-07-01 20:52:51 +0000558raw_ostream &polly::operator<<(raw_ostream &OS,
559 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000560 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000561 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000562 else
563 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000564 return OS;
565}
566
Tobias Grosser75805372011-04-29 06:27:02 +0000567void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000568 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000569 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000570 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000571 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000572 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000573 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000574 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000575 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000576 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000577 break;
578 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000579 OS << "[Reduction Type: " << getReductionType() << "] ";
580 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000581 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000582}
583
Tobias Grosser74394f02013-01-14 22:40:23 +0000584void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000585
586// Create a map in the size of the provided set domain, that maps from the
587// one element of the provided set domain to another element of the provided
588// set domain.
589// The mapping is limited to all points that are equal in all but the last
590// dimension and for which the last dimension of the input is strict smaller
591// than the last dimension of the output.
592//
593// getEqualAndLarger(set[i0, i1, ..., iX]):
594//
595// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
596// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
597//
Tobias Grosserf5338802011-10-06 00:03:35 +0000598static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000599 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000600 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000601 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000602
603 // Set all but the last dimension to be equal for the input and output
604 //
605 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
606 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000607 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000608 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000609
610 // Set the last dimension of the input to be strict smaller than the
611 // last dimension of the output.
612 //
613 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000614 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
615 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000616 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000617}
618
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000619__isl_give isl_set *
620MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000621 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000622 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000623 isl_space *Space = isl_space_range(isl_map_get_space(S));
624 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000625
Sebastian Popa00a0292012-12-18 07:46:06 +0000626 S = isl_map_reverse(S);
627 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000628
Sebastian Popa00a0292012-12-18 07:46:06 +0000629 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
630 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
631 NextScatt = isl_map_apply_domain(NextScatt, S);
632 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000633
Sebastian Popa00a0292012-12-18 07:46:06 +0000634 isl_set *Deltas = isl_map_deltas(NextScatt);
635 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000636}
637
Sebastian Popa00a0292012-12-18 07:46:06 +0000638bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000639 int StrideWidth) const {
640 isl_set *Stride, *StrideX;
641 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000642
Sebastian Popa00a0292012-12-18 07:46:06 +0000643 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000644 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000645 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
646 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
647 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
648 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000649 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000650
Tobias Grosser28dd4862012-01-24 16:42:16 +0000651 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000652 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000653
Tobias Grosser28dd4862012-01-24 16:42:16 +0000654 return IsStrideX;
655}
656
Sebastian Popa00a0292012-12-18 07:46:06 +0000657bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
658 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000659}
660
Tobias Grosser79baa212014-04-10 08:38:02 +0000661bool MemoryAccess::isScalar() const {
662 return isl_map_n_out(AccessRelation) == 0;
663}
664
Sebastian Popa00a0292012-12-18 07:46:06 +0000665bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
666 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000667}
668
Tobias Grosser5d453812011-10-06 00:04:11 +0000669void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000670 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000671 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000672}
Tobias Grosser75805372011-04-29 06:27:02 +0000673
674//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000675
Tobias Grosser808cd692015-07-14 09:33:13 +0000676isl_map *ScopStmt::getSchedule() const {
677 isl_set *Domain = getDomain();
678 if (isl_set_is_empty(Domain)) {
679 isl_set_free(Domain);
680 return isl_map_from_aff(
681 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
682 }
683 auto *Schedule = getParent()->getSchedule();
684 Schedule = isl_union_map_intersect_domain(
685 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
686 if (isl_union_map_is_empty(Schedule)) {
687 isl_set_free(Domain);
688 isl_union_map_free(Schedule);
689 return isl_map_from_aff(
690 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
691 }
692 auto *M = isl_map_from_union_map(Schedule);
693 M = isl_map_coalesce(M);
694 M = isl_map_gist_domain(M, Domain);
695 M = isl_map_coalesce(M);
696 return M;
697}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000698
Johannes Doerfert574182d2015-08-12 10:19:50 +0000699__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
700 return getParent()->getPwAff(E, this);
701}
702
Tobias Grosser37eb4222014-02-20 21:43:54 +0000703void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
704 assert(isl_set_is_subset(NewDomain, Domain) &&
705 "New domain is not a subset of old domain!");
706 isl_set_free(Domain);
707 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000708}
709
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000710void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
711 bool isApproximated) {
712 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
713 if (!AFS)
714 return;
715
716 for (auto &AccessPair : *AFS) {
717 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000718 Instruction *AccessInst = AccessPair.second;
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000719 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000720
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000721 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser92245222015-07-28 14:53:44 +0000722 Access.getBase(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000723
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000724 if (isApproximated && Access.isWrite())
725 Access.setMayWrite();
726
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000727 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
728 if (!MAL)
729 MAL = new MemoryAccessList();
730 MAL->emplace_front(Access, AccessInst, this, SAI, MemAccs.size());
731 MemAccs.push_back(&MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000732 }
733}
734
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000735void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000736 for (MemoryAccess *MA : *this)
737 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000738
739 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000740}
741
Tobias Grosser65b00582011-11-08 15:41:19 +0000742__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000743 isl_pw_aff *L = getPwAff(Comp.getLHS());
744 isl_pw_aff *R = getPwAff(Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000745
Tobias Grosserd2795d02011-08-18 07:51:40 +0000746 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000747 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000748 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000749 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000750 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000751 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000752 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000753 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000754 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000755 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000756 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000757 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000758 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000759 case ICmpInst::ICMP_ULT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000760 return isl_pw_aff_lt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000761 case ICmpInst::ICMP_UGT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000762 return isl_pw_aff_gt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000763 case ICmpInst::ICMP_ULE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000764 return isl_pw_aff_le_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000765 case ICmpInst::ICMP_UGE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000766 return isl_pw_aff_ge_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000767 default:
768 llvm_unreachable("Non integer predicate not supported");
769 }
Tobias Grosser75805372011-04-29 06:27:02 +0000770}
771
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000772void ScopStmt::addLoopBoundsToDomain(TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000773 isl_space *Space;
774 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000775
Tobias Grossere19661e2011-10-07 08:46:57 +0000776 Space = isl_set_get_space(Domain);
777 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000778
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000779 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000780 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000781 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000782 isl_pw_aff *IV =
783 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000784
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000785 // 0 <= IV.
786 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
787 Domain = isl_set_intersect(Domain, LowerBound);
788
789 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000790 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000791 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000792 isl_pw_aff *UpperBound = getPwAff(LatchExecutions);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000793 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000794 Domain = isl_set_intersect(Domain, UpperBoundSet);
795 }
796
Tobias Grosserf5338802011-10-06 00:03:35 +0000797 isl_local_space_free(LocalSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000798}
799
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000800void ScopStmt::addConditionsToDomain(TempScop &tempScop,
801 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000802 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000803 *CurrentRegion = &CurRegion;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000804 const BasicBlock *BranchingBB = BB ? BB : R->getEntry();
Tobias Grosser75805372011-04-29 06:27:02 +0000805
Tobias Grosser75805372011-04-29 06:27:02 +0000806 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000807 if (BranchingBB != CurrentRegion->getEntry()) {
808 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000809 for (const auto &C : *Condition) {
810 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000811 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000812 }
813 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000814 BranchingBB = CurrentRegion->getEntry();
815 CurrentRegion = CurrentRegion->getParent();
816 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000817}
818
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000819void ScopStmt::buildDomain(TempScop &tempScop, const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000820 isl_space *Space;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000821 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000822
823 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
824
Tobias Grosser084d8f72012-05-29 09:29:44 +0000825 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
826
Tobias Grossere19661e2011-10-07 08:46:57 +0000827 Domain = isl_set_universe(Space);
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000828 addLoopBoundsToDomain(tempScop);
829 addConditionsToDomain(tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000830 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000831}
832
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000833void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
834 int Dimension = 0;
835 isl_ctx *Ctx = Parent.getIslCtx();
836 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
837 Type *Ty = GEP->getPointerOperandType();
838 ScalarEvolution &SE = *Parent.getSE();
839
840 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
841 Dimension = 1;
842 Ty = PtrTy->getElementType();
843 }
844
845 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
846 unsigned int Operand = 1 + Dimension;
847
848 if (GEP->getNumOperands() <= Operand)
849 break;
850
851 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
852
853 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000854 isl_pw_aff *AccessOffset = getPwAff(Expr);
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000855 AccessOffset =
856 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
857
858 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
859 isl_local_space_copy(LSpace),
860 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
861
862 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
863 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
864 OutOfBound = isl_set_params(OutOfBound);
865 isl_set *InBound = isl_set_complement(OutOfBound);
866 isl_set *Executed = isl_set_params(getDomain());
867
868 // A => B == !A or B
869 isl_set *InBoundIfExecuted =
870 isl_set_union(isl_set_complement(Executed), InBound);
871
872 Parent.addAssumption(InBoundIfExecuted);
873 }
874
875 Dimension += 1;
876 Ty = ArrayTy->getElementType();
877 }
878
879 isl_local_space_free(LSpace);
880}
881
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000882void ScopStmt::deriveAssumptions(BasicBlock *Block) {
883 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000884 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
885 deriveAssumptionsFromGEP(GEP);
886}
887
Tobias Grosser74394f02013-01-14 22:40:23 +0000888ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000889 Region &R, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000890 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
891 NestLoops(Nest.size()) {
892 // Setup the induction variables.
893 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
894 NestLoops[i] = Nest[i];
895
Tobias Grosser16c44032015-07-09 07:31:45 +0000896 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000897
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000898 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000899
900 BasicBlock *EntryBB = R.getEntry();
901 for (BasicBlock *Block : R.blocks()) {
902 buildAccesses(tempScop, Block, Block != EntryBB);
903 deriveAssumptions(Block);
904 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000905 if (DetectReductions)
906 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000907}
908
909ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000910 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000911 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
912 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000913 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +0000914 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +0000915 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000916
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000917 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +0000918
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000919 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000920 buildAccesses(tempScop, BB);
921 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000922 if (DetectReductions)
923 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000924}
925
Johannes Doerferte58a0122014-06-27 20:31:28 +0000926/// @brief Collect loads which might form a reduction chain with @p StoreMA
927///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000928/// Check if the stored value for @p StoreMA is a binary operator with one or
929/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +0000930/// used only once (by @p StoreMA) and its load operands are also used only
931/// once, we have found a possible reduction chain. It starts at an operand
932/// load and includes the binary operator and @p StoreMA.
933///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000934/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +0000935/// escape this block or into any other store except @p StoreMA.
936void ScopStmt::collectCandiateReductionLoads(
937 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
938 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
939 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000940 return;
941
942 // Skip if there is not one binary operator between the load and the store
943 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +0000944 if (!BinOp)
945 return;
946
947 // Skip if the binary operators has multiple uses
948 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000949 return;
950
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000951 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000952 if (!BinOp->isCommutative() || !BinOp->isAssociative())
953 return;
954
Johannes Doerfert9890a052014-07-01 00:32:29 +0000955 // Skip if the binary operator is outside the current SCoP
956 if (BinOp->getParent() != Store->getParent())
957 return;
958
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000959 // Skip if it is a multiplicative reduction and we disabled them
960 if (DisableMultiplicativeReductions &&
961 (BinOp->getOpcode() == Instruction::Mul ||
962 BinOp->getOpcode() == Instruction::FMul))
963 return;
964
Johannes Doerferte58a0122014-06-27 20:31:28 +0000965 // Check the binary operator operands for a candidate load
966 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
967 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
968 if (!PossibleLoad0 && !PossibleLoad1)
969 return;
970
971 // A load is only a candidate if it cannot escape (thus has only this use)
972 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000973 if (PossibleLoad0->getParent() == Store->getParent())
974 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000975 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000976 if (PossibleLoad1->getParent() == Store->getParent())
977 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000978}
979
980/// @brief Check for reductions in this ScopStmt
981///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000982/// Iterate over all store memory accesses and check for valid binary reduction
983/// like chains. For all candidates we check if they have the same base address
984/// and there are no other accesses which overlap with them. The base address
985/// check rules out impossible reductions candidates early. The overlap check,
986/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +0000987/// guarantees that none of the intermediate results will escape during
988/// execution of the loop nest. We basically check here that no other memory
989/// access can access the same memory as the potential reduction.
990void ScopStmt::checkForReductions() {
991 SmallVector<MemoryAccess *, 2> Loads;
992 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
993
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000994 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +0000995 // stores and collecting possible reduction loads.
996 for (MemoryAccess *StoreMA : MemAccs) {
997 if (StoreMA->isRead())
998 continue;
999
1000 Loads.clear();
1001 collectCandiateReductionLoads(StoreMA, Loads);
1002 for (MemoryAccess *LoadMA : Loads)
1003 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1004 }
1005
1006 // Then check each possible candidate pair.
1007 for (const auto &CandidatePair : Candidates) {
1008 bool Valid = true;
1009 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1010 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1011
1012 // Skip those with obviously unequal base addresses.
1013 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1014 isl_map_free(LoadAccs);
1015 isl_map_free(StoreAccs);
1016 continue;
1017 }
1018
1019 // And check if the remaining for overlap with other memory accesses.
1020 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1021 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1022 isl_set *AllAccs = isl_map_range(AllAccsRel);
1023
1024 for (MemoryAccess *MA : MemAccs) {
1025 if (MA == CandidatePair.first || MA == CandidatePair.second)
1026 continue;
1027
1028 isl_map *AccRel =
1029 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1030 isl_set *Accs = isl_map_range(AccRel);
1031
1032 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1033 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1034 Valid = Valid && isl_set_is_empty(OverlapAccs);
1035 isl_set_free(OverlapAccs);
1036 }
1037 }
1038
1039 isl_set_free(AllAccs);
1040 if (!Valid)
1041 continue;
1042
Johannes Doerfertf6183392014-07-01 20:52:51 +00001043 const LoadInst *Load =
1044 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1045 MemoryAccess::ReductionType RT =
1046 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1047
Johannes Doerferte58a0122014-06-27 20:31:28 +00001048 // If no overlapping access was found we mark the load and store as
1049 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001050 CandidatePair.first->markAsReductionLike(RT);
1051 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001052 }
Tobias Grosser75805372011-04-29 06:27:02 +00001053}
1054
Tobias Grosser74394f02013-01-14 22:40:23 +00001055std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001056
Tobias Grosser54839312015-04-21 11:37:25 +00001057std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001058 auto *S = getSchedule();
1059 auto Str = stringFromIslObj(S);
1060 isl_map_free(S);
1061 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001062}
1063
Tobias Grosser74394f02013-01-14 22:40:23 +00001064unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001065
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001066unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001067
Tobias Grosser75805372011-04-29 06:27:02 +00001068const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1069
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001070const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001071 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001072}
1073
Tobias Grosser74394f02013-01-14 22:40:23 +00001074isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001075
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001076__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001077
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001078__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001079 return isl_set_get_space(Domain);
1080}
1081
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001082__isl_give isl_id *ScopStmt::getDomainId() const {
1083 return isl_set_get_tuple_id(Domain);
1084}
Tobias Grossercd95b772012-08-30 11:49:38 +00001085
Tobias Grosser75805372011-04-29 06:27:02 +00001086ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001087 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001088 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001089}
1090
1091void ScopStmt::print(raw_ostream &OS) const {
1092 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001093 OS.indent(12) << "Domain :=\n";
1094
1095 if (Domain) {
1096 OS.indent(16) << getDomainStr() << ";\n";
1097 } else
1098 OS.indent(16) << "n/a\n";
1099
Tobias Grosser54839312015-04-21 11:37:25 +00001100 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001101
1102 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001103 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001104 } else
1105 OS.indent(16) << "n/a\n";
1106
Tobias Grosser083d3d32014-06-28 08:59:45 +00001107 for (MemoryAccess *Access : MemAccs)
1108 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001109}
1110
1111void ScopStmt::dump() const { print(dbgs()); }
1112
1113//===----------------------------------------------------------------------===//
1114/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001115
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001116void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001117 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1118 isl_set_free(Context);
1119 Context = NewContext;
1120}
1121
Tobias Grosserabfbe632013-02-05 12:09:06 +00001122void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001123 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001124 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001125 if (ParameterIds.find(Parameter) != ParameterIds.end())
1126 continue;
1127
1128 int dimension = Parameters.size();
1129
1130 Parameters.push_back(Parameter);
1131 ParameterIds[Parameter] = dimension;
1132 }
1133}
1134
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001135__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1136 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001137
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001138 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001139 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001140
Tobias Grosser8f99c162011-11-15 11:38:55 +00001141 std::string ParameterName;
1142
1143 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1144 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001145 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001146 }
1147
1148 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001149 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001150
Tobias Grosser20532b82014-04-11 17:56:49 +00001151 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1152 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001153}
Tobias Grosser75805372011-04-29 06:27:02 +00001154
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001155isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1156 isl_set *DomainContext = isl_union_set_params(getDomains());
1157 return isl_set_intersect_params(C, DomainContext);
1158}
1159
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001160void Scop::addUserContext() {
1161 if (UserContextStr.empty())
1162 return;
1163
1164 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1165 isl_space *Space = getParamSpace();
1166 if (isl_space_dim(Space, isl_dim_param) !=
1167 isl_set_dim(UserContext, isl_dim_param)) {
1168 auto SpaceStr = isl_space_to_str(Space);
1169 errs() << "Error: the context provided in -polly-context has not the same "
1170 << "number of dimensions than the computed context. Due to this "
1171 << "mismatch, the -polly-context option is ignored. Please provide "
1172 << "the context in the parameter space: " << SpaceStr << ".\n";
1173 free(SpaceStr);
1174 isl_set_free(UserContext);
1175 isl_space_free(Space);
1176 return;
1177 }
1178
1179 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1180 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1181 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1182
1183 if (strcmp(NameContext, NameUserContext) != 0) {
1184 auto SpaceStr = isl_space_to_str(Space);
1185 errs() << "Error: the name of dimension " << i
1186 << " provided in -polly-context "
1187 << "is '" << NameUserContext << "', but the name in the computed "
1188 << "context is '" << NameContext
1189 << "'. Due to this name mismatch, "
1190 << "the -polly-context option is ignored. Please provide "
1191 << "the context in the parameter space: " << SpaceStr << ".\n";
1192 free(SpaceStr);
1193 isl_set_free(UserContext);
1194 isl_space_free(Space);
1195 return;
1196 }
1197
1198 UserContext =
1199 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1200 isl_space_get_dim_id(Space, isl_dim_param, i));
1201 }
1202
1203 Context = isl_set_intersect(Context, UserContext);
1204 isl_space_free(Space);
1205}
1206
Tobias Grosser6be480c2011-11-08 15:41:13 +00001207void Scop::buildContext() {
1208 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001209 Context = isl_set_universe(isl_space_copy(Space));
1210 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001211}
1212
Tobias Grosser18daaca2012-05-22 10:47:27 +00001213void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001214 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001215 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001216
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001217 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001218
Johannes Doerferte7044942015-02-24 11:58:30 +00001219 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001220 }
1221}
1222
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001223void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001224 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001225 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001226
Tobias Grosser083d3d32014-06-28 08:59:45 +00001227 for (const auto &ParamID : ParameterIds) {
1228 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001229 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001230 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001231 }
1232
1233 // Align the parameters of all data structures to the model.
1234 Context = isl_set_align_params(Context, Space);
1235
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001236 for (ScopStmt &Stmt : *this)
1237 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001238}
1239
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001240void Scop::simplifyAssumedContext() {
1241 // The parameter constraints of the iteration domains give us a set of
1242 // constraints that need to hold for all cases where at least a single
1243 // statement iteration is executed in the whole scop. We now simplify the
1244 // assumed context under the assumption that such constraints hold and at
1245 // least a single statement iteration is executed. For cases where no
1246 // statement instances are executed, the assumptions we have taken about
1247 // the executed code do not matter and can be changed.
1248 //
1249 // WARNING: This only holds if the assumptions we have taken do not reduce
1250 // the set of statement instances that are executed. Otherwise we
1251 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001252 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001253 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001254 // performed. In such a case, modifying the run-time conditions and
1255 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001256 // to not be executed.
1257 //
1258 // Example:
1259 //
1260 // When delinearizing the following code:
1261 //
1262 // for (long i = 0; i < 100; i++)
1263 // for (long j = 0; j < m; j++)
1264 // A[i+p][j] = 1.0;
1265 //
1266 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001267 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001268 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1269 AssumedContext =
1270 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001271 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001272}
1273
Johannes Doerfertb164c792014-09-18 11:17:17 +00001274/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001275static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001276 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1277 isl_pw_multi_aff *MinPMA, *MaxPMA;
1278 isl_pw_aff *LastDimAff;
1279 isl_aff *OneAff;
1280 unsigned Pos;
1281
Johannes Doerfert9143d672014-09-27 11:02:39 +00001282 // Restrict the number of parameters involved in the access as the lexmin/
1283 // lexmax computation will take too long if this number is high.
1284 //
1285 // Experiments with a simple test case using an i7 4800MQ:
1286 //
1287 // #Parameters involved | Time (in sec)
1288 // 6 | 0.01
1289 // 7 | 0.04
1290 // 8 | 0.12
1291 // 9 | 0.40
1292 // 10 | 1.54
1293 // 11 | 6.78
1294 // 12 | 30.38
1295 //
1296 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1297 unsigned InvolvedParams = 0;
1298 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1299 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1300 InvolvedParams++;
1301
1302 if (InvolvedParams > RunTimeChecksMaxParameters) {
1303 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001304 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001305 }
1306 }
1307
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001308 Set = isl_set_remove_divs(Set);
1309
Johannes Doerfertb164c792014-09-18 11:17:17 +00001310 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1311 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1312
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001313 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1314 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1315
Johannes Doerfertb164c792014-09-18 11:17:17 +00001316 // Adjust the last dimension of the maximal access by one as we want to
1317 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1318 // we test during code generation might now point after the end of the
1319 // allocated array but we will never dereference it anyway.
1320 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1321 "Assumed at least one output dimension");
1322 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1323 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1324 OneAff = isl_aff_zero_on_domain(
1325 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1326 OneAff = isl_aff_add_constant_si(OneAff, 1);
1327 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1328 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1329
1330 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1331
1332 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001333 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001334}
1335
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001336static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1337 isl_set *Domain = MA->getStatement()->getDomain();
1338 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1339 return isl_set_reset_tuple_id(Domain);
1340}
1341
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001342/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1343static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001344 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001345 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001346
1347 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1348 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001349 Locations = isl_union_set_coalesce(Locations);
1350 Locations = isl_union_set_detect_equalities(Locations);
1351 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001352 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001353 isl_union_set_free(Locations);
1354 return Valid;
1355}
1356
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001357void Scop::buildAliasChecks(AliasAnalysis &AA) {
1358 if (!PollyUseRuntimeAliasChecks)
1359 return;
1360
1361 if (buildAliasGroups(AA))
1362 return;
1363
1364 // If a problem occurs while building the alias groups we need to delete
1365 // this SCoP and pretend it wasn't valid in the first place. To this end
1366 // we make the assumed context infeasible.
1367 addAssumption(isl_set_empty(getParamSpace()));
1368
1369 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1370 << " could not be created as the number of parameters involved "
1371 "is too high. The SCoP will be "
1372 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1373 "the maximal number of parameters but be advised that the "
1374 "compile time might increase exponentially.\n\n");
1375}
1376
Johannes Doerfert9143d672014-09-27 11:02:39 +00001377bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001378 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001379 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001380 // for all memory accesses inside the SCoP.
1381 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001382 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001383 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001384 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001385 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001386 // if their access domains intersect, otherwise they are in different
1387 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001388 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001389 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001390 // and maximal accesses to each array of a group in read only and non
1391 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001392 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1393
1394 AliasSetTracker AST(AA);
1395
1396 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001397 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001398 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001399
1400 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001401 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001402 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1403 isl_set_free(StmtDomain);
1404 if (StmtDomainEmpty)
1405 continue;
1406
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001407 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001408 if (MA->isScalar())
1409 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001410 if (!MA->isRead())
1411 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001412 Instruction *Acc = MA->getAccessInstruction();
1413 PtrToAcc[getPointerOperand(*Acc)] = MA;
1414 AST.add(Acc);
1415 }
1416 }
1417
1418 SmallVector<AliasGroupTy, 4> AliasGroups;
1419 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001420 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001421 continue;
1422 AliasGroupTy AG;
1423 for (auto PR : AS)
1424 AG.push_back(PtrToAcc[PR.getValue()]);
1425 assert(AG.size() > 1 &&
1426 "Alias groups should contain at least two accesses");
1427 AliasGroups.push_back(std::move(AG));
1428 }
1429
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001430 // Split the alias groups based on their domain.
1431 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1432 AliasGroupTy NewAG;
1433 AliasGroupTy &AG = AliasGroups[u];
1434 AliasGroupTy::iterator AGI = AG.begin();
1435 isl_set *AGDomain = getAccessDomain(*AGI);
1436 while (AGI != AG.end()) {
1437 MemoryAccess *MA = *AGI;
1438 isl_set *MADomain = getAccessDomain(MA);
1439 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1440 NewAG.push_back(MA);
1441 AGI = AG.erase(AGI);
1442 isl_set_free(MADomain);
1443 } else {
1444 AGDomain = isl_set_union(AGDomain, MADomain);
1445 AGI++;
1446 }
1447 }
1448 if (NewAG.size() > 1)
1449 AliasGroups.push_back(std::move(NewAG));
1450 isl_set_free(AGDomain);
1451 }
1452
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001453 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001454 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1455 for (AliasGroupTy &AG : AliasGroups) {
1456 NonReadOnlyBaseValues.clear();
1457 ReadOnlyPairs.clear();
1458
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001459 if (AG.size() < 2) {
1460 AG.clear();
1461 continue;
1462 }
1463
Johannes Doerfert13771732014-10-01 12:40:46 +00001464 for (auto II = AG.begin(); II != AG.end();) {
1465 Value *BaseAddr = (*II)->getBaseAddr();
1466 if (HasWriteAccess.count(BaseAddr)) {
1467 NonReadOnlyBaseValues.insert(BaseAddr);
1468 II++;
1469 } else {
1470 ReadOnlyPairs[BaseAddr].insert(*II);
1471 II = AG.erase(II);
1472 }
1473 }
1474
1475 // If we don't have read only pointers check if there are at least two
1476 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00001477 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001478 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00001479 continue;
1480 }
1481
1482 // If we don't have non read only pointers clear the alias group.
1483 if (NonReadOnlyBaseValues.empty()) {
1484 AG.clear();
1485 continue;
1486 }
1487
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001488 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001489 MinMaxAliasGroups.emplace_back();
1490 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
1491 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
1492 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
1493 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001494
1495 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001496
1497 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001498 for (MemoryAccess *MA : AG)
1499 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001500
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00001501 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
1502 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001503
1504 // Bail out if the number of values we need to compare is too large.
1505 // This is important as the number of comparisions grows quadratically with
1506 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001507 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
1508 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001509 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001510
1511 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001512 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001513 Accesses = isl_union_map_empty(getParamSpace());
1514
1515 for (const auto &ReadOnlyPair : ReadOnlyPairs)
1516 for (MemoryAccess *MA : ReadOnlyPair.second)
1517 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1518
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00001519 Valid =
1520 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001521
1522 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001523 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001524 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001525
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001526 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001527}
1528
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001529static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1530 ScopDetection &SD) {
1531
1532 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1533
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001534 unsigned MinLD = INT_MAX, MaxLD = 0;
1535 for (BasicBlock *BB : R.blocks()) {
1536 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001537 if (!R.contains(L))
1538 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001539 if (BoxedLoops && BoxedLoops->count(L))
1540 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001541 unsigned LD = L->getLoopDepth();
1542 MinLD = std::min(MinLD, LD);
1543 MaxLD = std::max(MaxLD, LD);
1544 }
1545 }
1546
1547 // Handle the case that there is no loop in the SCoP first.
1548 if (MaxLD == 0)
1549 return 1;
1550
1551 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1552 assert(MaxLD >= MinLD &&
1553 "Maximal loop depth was smaller than mininaml loop depth?");
1554 return MaxLD - MinLD + 1;
1555}
1556
Michael Kruse471a5e32015-07-30 19:27:04 +00001557Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, isl_ctx *Context,
1558 unsigned MaxLoopDepth)
1559 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Johannes Doerfert574182d2015-08-12 10:19:50 +00001560 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001561
Tobias Grosser40985012015-08-20 19:08:05 +00001562void Scop::initFromTempScop(TempScop &TempScop, LoopInfo &LI, ScopDetection &SD,
1563 AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001564 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001565
Tobias Grosserabfbe632013-02-05 12:09:06 +00001566 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001567
Tobias Grosser54839312015-04-21 11:37:25 +00001568 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001569 // traversing the region tree.
Michael Kruse471a5e32015-07-30 19:27:04 +00001570 Schedule = buildScop(TempScop, getRegion(), NestLoops, LI, SD);
Tobias Grosser808cd692015-07-14 09:33:13 +00001571 if (!Schedule)
1572 Schedule = isl_schedule_empty(getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +00001573
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001574 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001575 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001576 addUserContext();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001577 simplifyAssumedContext();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001578 buildAliasChecks(AA);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001579
Tobias Grosser75805372011-04-29 06:27:02 +00001580 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1581}
1582
Michael Kruse471a5e32015-07-30 19:27:04 +00001583Scop *Scop::createFromTempScop(TempScop &TempScop, LoopInfo &LI,
1584 ScalarEvolution &SE, ScopDetection &SD,
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001585 AliasAnalysis &AA, isl_ctx *ctx) {
Michael Kruse471a5e32015-07-30 19:27:04 +00001586 auto &R = TempScop.getMaxRegion();
1587 auto MaxLoopDepth = getMaxLoopDepthInRegion(R, LI, SD);
1588 auto S = new Scop(R, SE, ctx, MaxLoopDepth);
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001589 S->initFromTempScop(TempScop, LI, SD, AA);
1590
Michael Kruse471a5e32015-07-30 19:27:04 +00001591 return S;
1592}
1593
Tobias Grosser75805372011-04-29 06:27:02 +00001594Scop::~Scop() {
1595 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001596 isl_set_free(AssumedContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00001597 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001598
Johannes Doerfertb164c792014-09-18 11:17:17 +00001599 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001600 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001601 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001602 isl_pw_multi_aff_free(MMA.first);
1603 isl_pw_multi_aff_free(MMA.second);
1604 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001605 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001606 isl_pw_multi_aff_free(MMA.first);
1607 isl_pw_multi_aff_free(MMA.second);
1608 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001609 }
Tobias Grosser75805372011-04-29 06:27:02 +00001610}
1611
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001612const ScopArrayInfo *
1613Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser92245222015-07-28 14:53:44 +00001614 const SmallVector<const SCEV *, 4> &Sizes,
1615 bool IsPHI) {
1616 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001617 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001618 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
1619 this));
Tobias Grosserab671442015-05-23 05:58:27 +00001620 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001621}
1622
Tobias Grosser92245222015-07-28 14:53:44 +00001623const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
1624 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001625 assert(SAI && "No ScopArrayInfo available for this base pointer");
1626 return SAI;
1627}
1628
Tobias Grosser74394f02013-01-14 22:40:23 +00001629std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001630std::string Scop::getAssumedContextStr() const {
1631 return stringFromIslObj(AssumedContext);
1632}
Tobias Grosser75805372011-04-29 06:27:02 +00001633
1634std::string Scop::getNameStr() const {
1635 std::string ExitName, EntryName;
1636 raw_string_ostream ExitStr(ExitName);
1637 raw_string_ostream EntryStr(EntryName);
1638
Tobias Grosserf240b482014-01-09 10:42:15 +00001639 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001640 EntryStr.str();
1641
1642 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001643 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001644 ExitStr.str();
1645 } else
1646 ExitName = "FunctionExit";
1647
1648 return EntryName + "---" + ExitName;
1649}
1650
Tobias Grosser74394f02013-01-14 22:40:23 +00001651__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001652__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001653 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00001654}
1655
Tobias Grossere86109f2013-10-29 21:05:49 +00001656__isl_give isl_set *Scop::getAssumedContext() const {
1657 return isl_set_copy(AssumedContext);
1658}
1659
Johannes Doerfert43788c52015-08-20 05:58:56 +00001660__isl_give isl_set *Scop::getRuntimeCheckContext() const {
1661 isl_set *RuntimeCheckContext = getAssumedContext();
1662 return RuntimeCheckContext;
1663}
1664
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001665bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00001666 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001667 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00001668 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
1669 isl_set_free(RuntimeCheckContext);
1670 return IsFeasible;
1671}
1672
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001673void Scop::addAssumption(__isl_take isl_set *Set) {
1674 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001675 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001676}
1677
Tobias Grosser75805372011-04-29 06:27:02 +00001678void Scop::printContext(raw_ostream &OS) const {
1679 OS << "Context:\n";
1680
1681 if (!Context) {
1682 OS.indent(4) << "n/a\n\n";
1683 return;
1684 }
1685
1686 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001687
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001688 OS.indent(4) << "Assumed Context:\n";
1689 if (!AssumedContext) {
1690 OS.indent(4) << "n/a\n\n";
1691 return;
1692 }
1693
1694 OS.indent(4) << getAssumedContextStr() << "\n";
1695
Tobias Grosser083d3d32014-06-28 08:59:45 +00001696 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001697 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001698 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1699 }
Tobias Grosser75805372011-04-29 06:27:02 +00001700}
1701
Johannes Doerfertb164c792014-09-18 11:17:17 +00001702void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001703 int noOfGroups = 0;
1704 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001705 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001706 noOfGroups += 1;
1707 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001708 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001709 }
1710
Tobias Grosserbb853c22015-07-25 12:31:03 +00001711 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00001712 if (MinMaxAliasGroups.empty()) {
1713 OS.indent(8) << "n/a\n";
1714 return;
1715 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001716
Tobias Grosserbb853c22015-07-25 12:31:03 +00001717 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001718
1719 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001720 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001721 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001722 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001723 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1724 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001725 }
1726 OS << " ]]\n";
1727 }
1728
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001729 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001730 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00001731 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001732 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001733 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1734 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001735 }
1736 OS << " ]]\n";
1737 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001738 }
1739}
1740
Tobias Grosser75805372011-04-29 06:27:02 +00001741void Scop::printStatements(raw_ostream &OS) const {
1742 OS << "Statements {\n";
1743
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001744 for (const ScopStmt &Stmt : *this)
1745 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001746
1747 OS.indent(4) << "}\n";
1748}
1749
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001750void Scop::printArrayInfo(raw_ostream &OS) const {
1751 OS << "Arrays {\n";
1752
Tobias Grosserab671442015-05-23 05:58:27 +00001753 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001754 Array.second->print(OS);
1755
1756 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001757
1758 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
1759
1760 for (auto &Array : arrays())
1761 Array.second->print(OS, /* SizeAsPwAff */ true);
1762
1763 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001764}
1765
Tobias Grosser75805372011-04-29 06:27:02 +00001766void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001767 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1768 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001769 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00001770 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001771 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001772 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001773 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001774 printStatements(OS.indent(4));
1775}
1776
1777void Scop::dump() const { print(dbgs()); }
1778
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001779isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001780
Johannes Doerfert574182d2015-08-12 10:19:50 +00001781__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, ScopStmt *Stmt) {
1782 return Affinator.getPwAff(E, Stmt);
1783}
1784
Tobias Grosser808cd692015-07-14 09:33:13 +00001785__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001786 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001787
Tobias Grosser808cd692015-07-14 09:33:13 +00001788 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001789 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001790
1791 return Domain;
1792}
1793
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001794__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001795 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001796
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001797 for (ScopStmt &Stmt : *this) {
1798 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001799 if (!MA->isMustWrite())
1800 continue;
1801
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001802 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001803 isl_map *AccessDomain = MA->getAccessRelation();
1804 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1805 Write = isl_union_map_add_map(Write, AccessDomain);
1806 }
1807 }
1808 return isl_union_map_coalesce(Write);
1809}
1810
1811__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001812 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001813
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001814 for (ScopStmt &Stmt : *this) {
1815 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001816 if (!MA->isMayWrite())
1817 continue;
1818
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001819 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001820 isl_map *AccessDomain = MA->getAccessRelation();
1821 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1822 Write = isl_union_map_add_map(Write, AccessDomain);
1823 }
1824 }
1825 return isl_union_map_coalesce(Write);
1826}
1827
Tobias Grosser37eb4222014-02-20 21:43:54 +00001828__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001829 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001830
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001831 for (ScopStmt &Stmt : *this) {
1832 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001833 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001834 continue;
1835
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001836 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001837 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001838 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1839 Write = isl_union_map_add_map(Write, AccessDomain);
1840 }
1841 }
1842 return isl_union_map_coalesce(Write);
1843}
1844
1845__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001846 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001847
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001848 for (ScopStmt &Stmt : *this) {
1849 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001850 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001851 continue;
1852
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001853 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001854 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001855
1856 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1857 Read = isl_union_map_add_map(Read, AccessDomain);
1858 }
1859 }
1860 return isl_union_map_coalesce(Read);
1861}
1862
Tobias Grosser808cd692015-07-14 09:33:13 +00001863__isl_give isl_union_map *Scop::getSchedule() const {
1864 auto Tree = getScheduleTree();
1865 auto S = isl_schedule_get_map(Tree);
1866 isl_schedule_free(Tree);
1867 return S;
1868}
Tobias Grosser37eb4222014-02-20 21:43:54 +00001869
Tobias Grosser808cd692015-07-14 09:33:13 +00001870__isl_give isl_schedule *Scop::getScheduleTree() const {
1871 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
1872 getDomains());
1873}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001874
Tobias Grosser808cd692015-07-14 09:33:13 +00001875void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
1876 auto *S = isl_schedule_from_domain(getDomains());
1877 S = isl_schedule_insert_partial_schedule(
1878 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
1879 isl_schedule_free(Schedule);
1880 Schedule = S;
1881}
1882
1883void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
1884 isl_schedule_free(Schedule);
1885 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00001886}
1887
1888bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1889 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001890 for (ScopStmt &Stmt : *this) {
1891 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001892 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1893 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1894
1895 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1896 isl_union_set_free(StmtDomain);
1897 isl_union_set_free(NewStmtDomain);
1898 continue;
1899 }
1900
1901 Changed = true;
1902
1903 isl_union_set_free(StmtDomain);
1904 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1905
1906 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001907 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001908 isl_union_set_free(NewStmtDomain);
1909 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001910 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001911 }
1912 isl_union_set_free(Domain);
1913 return Changed;
1914}
1915
Tobias Grosser75805372011-04-29 06:27:02 +00001916ScalarEvolution *Scop::getSE() const { return SE; }
1917
1918bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1919 if (tempScop.getAccessFunctions(BB))
1920 return false;
1921
1922 return true;
1923}
1924
Tobias Grosser808cd692015-07-14 09:33:13 +00001925struct MapToDimensionDataTy {
1926 int N;
1927 isl_union_pw_multi_aff *Res;
1928};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001929
Tobias Grosser808cd692015-07-14 09:33:13 +00001930// @brief Create a function that maps the elements of 'Set' to its N-th
1931// dimension.
1932//
1933// The result is added to 'User->Res'.
1934//
1935// @param Set The input set.
1936// @param N The dimension to map to.
1937//
1938// @returns Zero if no error occurred, non-zero otherwise.
1939static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
1940 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
1941 int Dim;
1942 isl_space *Space;
1943 isl_pw_multi_aff *PMA;
1944
1945 Dim = isl_set_dim(Set, isl_dim_set);
1946 Space = isl_set_get_space(Set);
1947 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
1948 Dim - Data->N);
1949 if (Data->N > 1)
1950 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
1951 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
1952
1953 isl_set_free(Set);
1954
1955 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001956}
1957
Tobias Grosser808cd692015-07-14 09:33:13 +00001958// @brief Create a function that maps the elements of Domain to their Nth
1959// dimension.
1960//
1961// @param Domain The set of elements to map.
1962// @param N The dimension to map to.
1963static __isl_give isl_multi_union_pw_aff *
1964mapToDimension(__isl_take isl_union_set *Domain, int N) {
1965 struct MapToDimensionDataTy Data;
1966 isl_space *Space;
1967
1968 Space = isl_union_set_get_space(Domain);
1969 Data.N = N;
1970 Data.Res = isl_union_pw_multi_aff_empty(Space);
1971 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
1972 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
1973
1974 isl_union_set_free(Domain);
1975 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
1976}
1977
1978ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
1979 const Region &CurRegion,
1980 SmallVectorImpl<Loop *> &NestLoops) {
1981 ScopStmt *Stmt;
1982 if (BB) {
1983 Stmts.emplace_back(*this, tempScop, CurRegion, *BB, NestLoops);
1984 Stmt = &Stmts.back();
1985 StmtMap[BB] = Stmt;
1986 } else {
1987 assert(R && "Either basic block or a region expected.");
1988 Stmts.emplace_back(*this, tempScop, CurRegion, *R, NestLoops);
1989 Stmt = &Stmts.back();
1990 for (BasicBlock *BB : R->blocks())
1991 StmtMap[BB] = Stmt;
1992 }
1993 return Stmt;
1994}
1995
Michael Kruse046dde42015-08-10 13:01:57 +00001996__isl_give isl_schedule *
1997Scop::buildBBScopStmt(BasicBlock *BB, TempScop &tempScop,
1998 const Region &CurRegion,
1999 SmallVectorImpl<Loop *> &NestLoops) {
2000 if (isTrivialBB(BB, tempScop))
2001 return nullptr;
2002
2003 auto *Stmt = addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops);
2004 auto *Domain = Stmt->getDomain();
2005 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2006}
2007
Tobias Grosser808cd692015-07-14 09:33:13 +00002008__isl_give isl_schedule *Scop::buildScop(TempScop &tempScop,
2009 const Region &CurRegion,
2010 SmallVectorImpl<Loop *> &NestLoops,
2011 LoopInfo &LI, ScopDetection &SD) {
2012 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion())) {
2013 auto *Stmt = addScopStmt(nullptr, const_cast<Region *>(&CurRegion),
2014 tempScop, CurRegion, NestLoops);
2015 auto *Domain = Stmt->getDomain();
2016 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2017 }
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002018
Tobias Grosser75805372011-04-29 06:27:02 +00002019 Loop *L = castToLoop(CurRegion, LI);
2020
2021 if (L)
2022 NestLoops.push_back(L);
2023
2024 unsigned loopDepth = NestLoops.size();
Tobias Grosser808cd692015-07-14 09:33:13 +00002025 isl_schedule *Schedule = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002026
2027 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00002028 E = CurRegion.element_end();
Tobias Grosser808cd692015-07-14 09:33:13 +00002029 I != E; ++I) {
2030 isl_schedule *StmtSchedule = nullptr;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002031 if (I->isSubRegion()) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002032 StmtSchedule =
2033 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, LI, SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002034 } else {
Michael Kruse046dde42015-08-10 13:01:57 +00002035 StmtSchedule = buildBBScopStmt(I->getNodeAs<BasicBlock>(), tempScop,
2036 CurRegion, NestLoops);
Tobias Grosser75805372011-04-29 06:27:02 +00002037 }
Michael Kruse046dde42015-08-10 13:01:57 +00002038 Schedule = combineInSequence(Schedule, StmtSchedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00002039 }
Tobias Grosser75805372011-04-29 06:27:02 +00002040
Tobias Grosser808cd692015-07-14 09:33:13 +00002041 if (!L)
2042 return Schedule;
2043
2044 auto *Domain = isl_schedule_get_domain(Schedule);
2045 if (!isl_union_set_is_empty(Domain)) {
2046 auto *MUPA = mapToDimension(isl_union_set_copy(Domain), loopDepth);
2047 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
2048 }
2049 isl_union_set_free(Domain);
2050
Tobias Grosser75805372011-04-29 06:27:02 +00002051 NestLoops.pop_back();
Tobias Grosser808cd692015-07-14 09:33:13 +00002052 return Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00002053}
2054
Johannes Doerfert7c494212014-10-31 23:13:39 +00002055ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002056 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002057 if (StmtMapIt == StmtMap.end())
2058 return nullptr;
2059 return StmtMapIt->second;
2060}
2061
Tobias Grosser75805372011-04-29 06:27:02 +00002062//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00002063ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
2064 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002065 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002066}
2067
2068ScopInfo::~ScopInfo() {
2069 clear();
2070 isl_ctx_free(ctx);
2071}
2072
Tobias Grosser75805372011-04-29 06:27:02 +00002073void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002074 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002075 AU.addRequired<RegionInfoPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002076 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002077 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002078 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002079 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00002080 AU.setPreservesAll();
2081}
2082
2083bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002084 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002085 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002086 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002087 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Tobias Grosser75805372011-04-29 06:27:02 +00002088
Michael Kruse82a1c7d2015-08-14 20:10:27 +00002089 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop();
Tobias Grosser75805372011-04-29 06:27:02 +00002090
2091 // This region is no Scop.
2092 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002093 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002094 return false;
2095 }
2096
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002097 scop = Scop::createFromTempScop(*tempScop, LI, SE, SD, AA, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002098
Tobias Grosserd6a50b32015-05-30 06:26:21 +00002099 DEBUG(scop->print(dbgs()));
2100
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002101 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002102 delete scop;
2103 scop = nullptr;
2104 return false;
2105 }
2106
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002107 // Statistics.
2108 ++ScopFound;
2109 if (scop->getMaxLoopDepth() > 0)
2110 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00002111 return false;
2112}
2113
2114char ScopInfo::ID = 0;
2115
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002116Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2117
Tobias Grosser73600b82011-10-08 00:30:40 +00002118INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2119 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002120 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002121INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002122INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002123INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002124INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002125INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002126INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00002127INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2128 "Polly - Create polyhedral description of Scops", false,
2129 false)