blob: d6fa4c96d93802e4df72ad191e396221a5ef534c [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 Doerfert96425c22015-08-30 21:13:53 +000032#include "llvm/ADT/PostOrderIterator.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000033#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000034#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000035#include "llvm/Analysis/RegionIterator.h"
36#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000037#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000038#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000039#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000040#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000041#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000042#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000044#include "isl/schedule.h"
45#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/set.h"
47#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000048#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000049#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000050#include <sstream>
51#include <string>
52#include <vector>
53
54using namespace llvm;
55using namespace polly;
56
Chandler Carruth95fef942014-04-22 03:30:19 +000057#define DEBUG_TYPE "polly-scops"
58
Tobias Grosser74394f02013-01-14 22:40:23 +000059STATISTIC(ScopFound, "Number of valid Scops");
60STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000061
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000062// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000063// operations can overflow easily. Additive reductions and bit operations
64// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000065static cl::opt<bool> DisableMultiplicativeReductions(
66 "polly-disable-multiplicative-reductions",
67 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
68 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000069
Johannes Doerfert9143d672014-09-27 11:02:39 +000070static cl::opt<unsigned> RunTimeChecksMaxParameters(
71 "polly-rtc-max-parameters",
72 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
73 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
74
Tobias Grosser71500722015-03-28 15:11:14 +000075static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
76 "polly-rtc-max-arrays-per-group",
77 cl::desc("The maximal number of arrays to compare in each alias group."),
78 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000079static cl::opt<std::string> UserContextStr(
80 "polly-context", cl::value_desc("isl parameter set"),
81 cl::desc("Provide additional constraints on the context parameters"),
82 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000083
Tobias Grosserd83b8a82015-08-20 19:08:11 +000084static cl::opt<bool> DetectReductions("polly-detect-reductions",
85 cl::desc("Detect and exploit reductions"),
86 cl::Hidden, cl::ZeroOrMore,
87 cl::init(true), cl::cat(PollyCategory));
88
Michael Kruse046dde42015-08-10 13:01:57 +000089// Create a sequence of two schedules. Either argument may be null and is
90// interpreted as the empty schedule. Can also return null if both schedules are
91// empty.
92static __isl_give isl_schedule *
93combineInSequence(__isl_take isl_schedule *Prev,
94 __isl_take isl_schedule *Succ) {
95 if (!Prev)
96 return Succ;
97 if (!Succ)
98 return Prev;
99
100 return isl_schedule_sequence(Prev, Succ);
101}
102
Johannes Doerferte7044942015-02-24 11:58:30 +0000103static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
104 const ConstantRange &Range,
105 int dim,
106 enum isl_dim_type type) {
107 isl_val *V;
108 isl_ctx *ctx = isl_set_get_ctx(S);
109
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000110 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
111 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000112 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000113 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
114
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000115 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000116 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000117 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000118 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000119 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
120
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000121 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000122 return isl_set_union(SLB, SUB);
123 else
124 return isl_set_intersect(SLB, SUB);
125}
126
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000127static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
128 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
129 if (!BasePtrLI)
130 return nullptr;
131
132 if (!S->getRegion().contains(BasePtrLI))
133 return nullptr;
134
135 ScalarEvolution &SE = *S->getSE();
136
137 auto *OriginBaseSCEV =
138 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
139 if (!OriginBaseSCEV)
140 return nullptr;
141
142 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
143 if (!OriginBaseSCEVUnknown)
144 return nullptr;
145
146 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
147}
148
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000149ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser92245222015-07-28 14:53:44 +0000150 const SmallVector<const SCEV *, 4> &DimensionSizes,
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000151 bool IsPHI, Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000152 : BasePtr(BasePtr), ElementType(ElementType),
Tobias Grosser92245222015-07-28 14:53:44 +0000153 DimensionSizes(DimensionSizes), IsPHI(IsPHI) {
154 std::string BasePtrName =
155 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000156 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000157 for (const SCEV *Expr : DimensionSizes) {
158 isl_pw_aff *Size = S->getPwAff(Expr);
159 DimensionSizesPw.push_back(Size);
160 }
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000161
162 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
163 if (BasePtrOriginSAI)
164 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000165}
166
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000167ScopArrayInfo::~ScopArrayInfo() {
168 isl_id_free(Id);
169 for (isl_pw_aff *Size : DimensionSizesPw)
170 isl_pw_aff_free(Size);
171}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000172
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000173std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
174
175int ScopArrayInfo::getElemSizeInBytes() const {
176 return ElementType->getPrimitiveSizeInBits() / 8;
177}
178
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000179isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
180
181void ScopArrayInfo::dump() const { print(errs()); }
182
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000183void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000184 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000185 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
186 OS << "[";
187
188 if (SizeAsPwAff)
189 OS << " " << DimensionSizesPw[u] << " ";
190 else
191 OS << *DimensionSizes[u];
192
193 OS << "]";
194 }
195
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000196 if (BasePtrOriginSAI)
197 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
198
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000199 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000200}
201
202const ScopArrayInfo *
203ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
204 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
205 assert(Id && "Output dimension didn't have an ID");
206 return getFromId(Id);
207}
208
209const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
210 void *User = isl_id_get_user(Id);
211 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
212 isl_id_free(Id);
213 return SAI;
214}
215
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000216const std::string
217MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
218 switch (RT) {
219 case MemoryAccess::RT_NONE:
220 llvm_unreachable("Requested a reduction operator string for a memory "
221 "access which isn't a reduction");
222 case MemoryAccess::RT_ADD:
223 return "+";
224 case MemoryAccess::RT_MUL:
225 return "*";
226 case MemoryAccess::RT_BOR:
227 return "|";
228 case MemoryAccess::RT_BXOR:
229 return "^";
230 case MemoryAccess::RT_BAND:
231 return "&";
232 }
233 llvm_unreachable("Unknown reduction type");
234 return "";
235}
236
Johannes Doerfertf6183392014-07-01 20:52:51 +0000237/// @brief Return the reduction type for a given binary operator
238static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
239 const Instruction *Load) {
240 if (!BinOp)
241 return MemoryAccess::RT_NONE;
242 switch (BinOp->getOpcode()) {
243 case Instruction::FAdd:
244 if (!BinOp->hasUnsafeAlgebra())
245 return MemoryAccess::RT_NONE;
246 // Fall through
247 case Instruction::Add:
248 return MemoryAccess::RT_ADD;
249 case Instruction::Or:
250 return MemoryAccess::RT_BOR;
251 case Instruction::Xor:
252 return MemoryAccess::RT_BXOR;
253 case Instruction::And:
254 return MemoryAccess::RT_BAND;
255 case Instruction::FMul:
256 if (!BinOp->hasUnsafeAlgebra())
257 return MemoryAccess::RT_NONE;
258 // Fall through
259 case Instruction::Mul:
260 if (DisableMultiplicativeReductions)
261 return MemoryAccess::RT_NONE;
262 return MemoryAccess::RT_MUL;
263 default:
264 return MemoryAccess::RT_NONE;
265 }
266}
Tobias Grosser75805372011-04-29 06:27:02 +0000267//===----------------------------------------------------------------------===//
268
269MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000270 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000271 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000272 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000273}
274
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000275static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
276 switch (Access.getType()) {
277 case IRAccess::READ:
278 return MemoryAccess::READ;
279 case IRAccess::MUST_WRITE:
280 return MemoryAccess::MUST_WRITE;
281 case IRAccess::MAY_WRITE:
282 return MemoryAccess::MAY_WRITE;
283 }
284 llvm_unreachable("Unknown IRAccess type!");
285}
286
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000287const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
288 isl_id *ArrayId = getArrayId();
289 void *User = isl_id_get_user(ArrayId);
290 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
291 isl_id_free(ArrayId);
292 return SAI;
293}
294
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000295__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000296 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
297}
298
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000299__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
300 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000301 isl_map *Schedule, *ScheduledAccRel;
302 isl_union_set *UDomain;
303
304 UDomain = isl_union_set_from_set(getStatement()->getDomain());
305 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
306 Schedule = isl_map_from_union_map(USchedule);
307 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
308 return isl_pw_multi_aff_from_map(ScheduledAccRel);
309}
310
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000311__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000312 return isl_map_copy(AccessRelation);
313}
314
Johannes Doerferta99130f2014-10-13 12:58:03 +0000315std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000316 return stringFromIslObj(AccessRelation);
317}
318
Johannes Doerferta99130f2014-10-13 12:58:03 +0000319__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000320 return isl_map_get_space(AccessRelation);
321}
322
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000323__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000324 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000325}
326
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000327__isl_give isl_basic_map *
328MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000329 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000330 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000331
Tobias Grosser084d8f72012-05-29 09:29:44 +0000332 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000333 isl_basic_set_universe(Statement->getDomainSpace()),
334 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000335}
336
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000337// Formalize no out-of-bound access assumption
338//
339// When delinearizing array accesses we optimistically assume that the
340// delinearized accesses do not access out of bound locations (the subscript
341// expression of each array evaluates for each statement instance that is
342// executed to a value that is larger than zero and strictly smaller than the
343// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000344// dimension for which we do not need to assume any upper bound. At this point
345// we formalize this assumption to ensure that at code generation time the
346// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000347//
348// To find the set of constraints necessary to avoid out of bound accesses, we
349// first build the set of data locations that are not within array bounds. We
350// then apply the reverse access relation to obtain the set of iterations that
351// may contain invalid accesses and reduce this set of iterations to the ones
352// that are actually executed by intersecting them with the domain of the
353// statement. If we now project out all loop dimensions, we obtain a set of
354// parameters that may cause statement instances to be executed that may
355// possibly yield out of bound memory accesses. The complement of these
356// constraints is the set of constraints that needs to be assumed to ensure such
357// statement instances are never executed.
358void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000359 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000360 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000361 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000362 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
363 isl_pw_aff *Var =
364 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
365 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
366
367 isl_set *DimOutside;
368
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000369 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000370 isl_pw_aff *SizeE = Statement->getPwAff(Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000371
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000372 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
373 Statement->getNumIterators());
374 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
375 isl_space_dim(Space, isl_dim_set));
376 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
377 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000378
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000379 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000380
381 Outside = isl_set_union(Outside, DimOutside);
382 }
383
384 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
385 Outside = isl_set_intersect(Outside, Statement->getDomain());
386 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000387
388 // Remove divs to avoid the construction of overly complicated assumptions.
389 // Doing so increases the set of parameter combinations that are assumed to
390 // not appear. This is always save, but may make the resulting run-time check
391 // bail out more often than strictly necessary.
392 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000393 Outside = isl_set_complement(Outside);
394 Statement->getParent()->addAssumption(Outside);
395 isl_space_free(Space);
396}
397
Johannes Doerferte7044942015-02-24 11:58:30 +0000398void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
399 ScalarEvolution *SE = Statement->getParent()->getSE();
400
401 Value *Ptr = getPointerOperand(*getAccessInstruction());
402 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
403 return;
404
405 auto *PtrSCEV = SE->getSCEV(Ptr);
406 if (isa<SCEVCouldNotCompute>(PtrSCEV))
407 return;
408
409 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
410 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
411 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
412
413 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
414 if (Range.isFullSet())
415 return;
416
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000417 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000418 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000419 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
420 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
421
422 auto Min = LB.sdiv(APInt(BW, ElementSize));
423 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000424
425 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
426 AccessRange =
427 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
428 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
429}
430
Tobias Grosser619190d2015-03-30 17:22:28 +0000431__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
432 __isl_take isl_map *AccessRelation,
433 ScopStmt *Statement) {
434 int Size = Access.Subscripts.size();
435
436 for (int i = Size - 2; i >= 0; --i) {
437 isl_space *Space;
438 isl_map *MapOne, *MapTwo;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000439 isl_pw_aff *DimSize = Statement->getPwAff(Access.Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000440
441 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
442 isl_pw_aff_free(DimSize);
443 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
444
445 Space = isl_map_get_space(AccessRelation);
446 Space = isl_space_map_from_set(isl_space_range(Space));
447 Space = isl_space_align_params(Space, SpaceSize);
448
449 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
450 isl_id_free(ParamId);
451
452 MapOne = isl_map_universe(isl_space_copy(Space));
453 for (int j = 0; j < Size; ++j)
454 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
455 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
456
457 MapTwo = isl_map_universe(isl_space_copy(Space));
458 for (int j = 0; j < Size; ++j)
459 if (j < i || j > i + 1)
460 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
461
462 isl_local_space *LS = isl_local_space_from_space(Space);
463 isl_constraint *C;
464 C = isl_equality_alloc(isl_local_space_copy(LS));
465 C = isl_constraint_set_constant_si(C, -1);
466 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
467 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
468 MapTwo = isl_map_add_constraint(MapTwo, C);
469 C = isl_equality_alloc(LS);
470 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
471 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
472 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
473 MapTwo = isl_map_add_constraint(MapTwo, C);
474 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
475
476 MapOne = isl_map_union(MapOne, MapTwo);
477 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
478 }
479 return AccessRelation;
480}
481
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000482MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000483 ScopStmt *Statement, const ScopArrayInfo *SAI,
484 int Identifier)
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000485 : AccType(getMemoryAccessType(Access)), Statement(Statement),
486 AccessInstruction(AccInst), AccessValue(Access.getAccessValue()),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000487 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000488
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000489 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000490 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000491 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000492
493 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000494
Tobias Grosserac3a95f2015-08-03 17:53:21 +0000495 auto IdName = "__polly_array_ref_" + std::to_string(Identifier);
Tobias Grossere29d31c2015-05-15 12:24:09 +0000496 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000497
Tobias Grossera1879642011-12-20 10:43:14 +0000498 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000499 // We overapproximate non-affine accesses with a possible access to the
500 // whole array. For read accesses it does not make a difference, if an
501 // access must or may happen. However, for write accesses it is important to
502 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000503 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000504 AccessRelation =
505 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000506
507 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000508 return;
509 }
510
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000511 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000512 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000513
Tobias Grosser79baa212014-04-10 08:38:02 +0000514 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000515 isl_pw_aff *Affine = Statement->getPwAff(Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000516
Sebastian Pop422e33f2014-06-03 18:16:31 +0000517 if (Size == 1) {
518 // For the non delinearized arrays, divide the access function of the last
519 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000520 //
521 // A stride one array access in C expressed as A[i] is expressed in
522 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
523 // two subsequent values of 'i' index two values that are stored next to
524 // each other in memory. By this division we make this characteristic
525 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000526 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000527 Affine = isl_pw_aff_scale_down_val(Affine, v);
528 }
529
530 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
531
Tobias Grosser79baa212014-04-10 08:38:02 +0000532 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000533 }
534
Tobias Grosser619190d2015-03-30 17:22:28 +0000535 AccessRelation = foldAccess(Access, AccessRelation, Statement);
536
Tobias Grosser79baa212014-04-10 08:38:02 +0000537 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000538 AccessRelation = isl_map_set_tuple_id(
539 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000540 AccessRelation =
541 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
542
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000543 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000544 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000545 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000546}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000547
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000548void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000549 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000550 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000551}
552
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000553const std::string MemoryAccess::getReductionOperatorStr() const {
554 return MemoryAccess::getReductionOperatorStr(getReductionType());
555}
556
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000557__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
558
Johannes Doerfertf6183392014-07-01 20:52:51 +0000559raw_ostream &polly::operator<<(raw_ostream &OS,
560 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000561 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000562 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000563 else
564 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000565 return OS;
566}
567
Tobias Grosser75805372011-04-29 06:27:02 +0000568void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000569 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000570 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000571 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000572 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000573 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000574 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000575 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000576 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000577 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000578 break;
579 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000580 OS << "[Reduction Type: " << getReductionType() << "] ";
581 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000582 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000583}
584
Tobias Grosser74394f02013-01-14 22:40:23 +0000585void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000586
587// Create a map in the size of the provided set domain, that maps from the
588// one element of the provided set domain to another element of the provided
589// set domain.
590// The mapping is limited to all points that are equal in all but the last
591// dimension and for which the last dimension of the input is strict smaller
592// than the last dimension of the output.
593//
594// getEqualAndLarger(set[i0, i1, ..., iX]):
595//
596// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
597// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
598//
Tobias Grosserf5338802011-10-06 00:03:35 +0000599static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000600 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000601 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000602 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000603
604 // Set all but the last dimension to be equal for the input and output
605 //
606 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
607 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000608 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000609 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000610
611 // Set the last dimension of the input to be strict smaller than the
612 // last dimension of the output.
613 //
614 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000615 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
616 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000617 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000618}
619
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000620__isl_give isl_set *
621MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000622 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000623 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000624 isl_space *Space = isl_space_range(isl_map_get_space(S));
625 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000626
Sebastian Popa00a0292012-12-18 07:46:06 +0000627 S = isl_map_reverse(S);
628 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000629
Sebastian Popa00a0292012-12-18 07:46:06 +0000630 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
631 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
632 NextScatt = isl_map_apply_domain(NextScatt, S);
633 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000634
Sebastian Popa00a0292012-12-18 07:46:06 +0000635 isl_set *Deltas = isl_map_deltas(NextScatt);
636 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000637}
638
Sebastian Popa00a0292012-12-18 07:46:06 +0000639bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000640 int StrideWidth) const {
641 isl_set *Stride, *StrideX;
642 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000643
Sebastian Popa00a0292012-12-18 07:46:06 +0000644 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000645 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000646 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
647 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
648 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
649 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000650 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000651
Tobias Grosser28dd4862012-01-24 16:42:16 +0000652 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000653 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000654
Tobias Grosser28dd4862012-01-24 16:42:16 +0000655 return IsStrideX;
656}
657
Sebastian Popa00a0292012-12-18 07:46:06 +0000658bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
659 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000660}
661
Tobias Grosser79baa212014-04-10 08:38:02 +0000662bool MemoryAccess::isScalar() const {
663 return isl_map_n_out(AccessRelation) == 0;
664}
665
Sebastian Popa00a0292012-12-18 07:46:06 +0000666bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
667 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000668}
669
Tobias Grosser5d453812011-10-06 00:04:11 +0000670void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000671 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000672 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000673}
Tobias Grosser75805372011-04-29 06:27:02 +0000674
675//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000676
Tobias Grosser808cd692015-07-14 09:33:13 +0000677isl_map *ScopStmt::getSchedule() const {
678 isl_set *Domain = getDomain();
679 if (isl_set_is_empty(Domain)) {
680 isl_set_free(Domain);
681 return isl_map_from_aff(
682 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
683 }
684 auto *Schedule = getParent()->getSchedule();
685 Schedule = isl_union_map_intersect_domain(
686 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
687 if (isl_union_map_is_empty(Schedule)) {
688 isl_set_free(Domain);
689 isl_union_map_free(Schedule);
690 return isl_map_from_aff(
691 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
692 }
693 auto *M = isl_map_from_union_map(Schedule);
694 M = isl_map_coalesce(M);
695 M = isl_map_gist_domain(M, Domain);
696 M = isl_map_coalesce(M);
697 return M;
698}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000699
Johannes Doerfert574182d2015-08-12 10:19:50 +0000700__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertb409fdc2015-08-28 09:24:35 +0000701 return getParent()->getPwAff(E, Domain);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000702}
703
Tobias Grosser37eb4222014-02-20 21:43:54 +0000704void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
705 assert(isl_set_is_subset(NewDomain, Domain) &&
706 "New domain is not a subset of old domain!");
707 isl_set_free(Domain);
708 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000709}
710
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000711void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
712 bool isApproximated) {
713 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
714 if (!AFS)
715 return;
716
717 for (auto &AccessPair : *AFS) {
718 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000719 Instruction *AccessInst = AccessPair.second;
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000720 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000721
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000722 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser92245222015-07-28 14:53:44 +0000723 Access.getBase(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000724
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000725 if (isApproximated && Access.isWrite())
726 Access.setMayWrite();
727
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000728 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
729 if (!MAL)
730 MAL = new MemoryAccessList();
731 MAL->emplace_front(Access, AccessInst, this, SAI, MemAccs.size());
732 MemAccs.push_back(&MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000733 }
734}
735
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000736void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000737 for (MemoryAccess *MA : *this)
738 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000739
740 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000741}
742
Johannes Doerfert96425c22015-08-30 21:13:53 +0000743static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
744 isl_pw_aff *L, isl_pw_aff *R) {
745 switch (Pred) {
746 case ICmpInst::ICMP_EQ:
747 return isl_pw_aff_eq_set(L, R);
748 case ICmpInst::ICMP_NE:
749 return isl_pw_aff_ne_set(L, R);
750 case ICmpInst::ICMP_SLT:
751 return isl_pw_aff_lt_set(L, R);
752 case ICmpInst::ICMP_SLE:
753 return isl_pw_aff_le_set(L, R);
754 case ICmpInst::ICMP_SGT:
755 return isl_pw_aff_gt_set(L, R);
756 case ICmpInst::ICMP_SGE:
757 return isl_pw_aff_ge_set(L, R);
758 case ICmpInst::ICMP_ULT:
759 return isl_pw_aff_lt_set(L, R);
760 case ICmpInst::ICMP_UGT:
761 return isl_pw_aff_gt_set(L, R);
762 case ICmpInst::ICMP_ULE:
763 return isl_pw_aff_le_set(L, R);
764 case ICmpInst::ICMP_UGE:
765 return isl_pw_aff_ge_set(L, R);
766 default:
767 llvm_unreachable("Non integer predicate not supported");
768 }
769}
770
771/// @brief Build the conditions sets for the branch @p BI in the @p Domain.
772///
773/// This will fill @p ConditionSets with the conditions under which control
774/// will be moved from @p BI to its successors. Hence, @p ConditionSets will
775/// have as many elements as @p BI has successors.
776static void
777buildConditionSets(Scop &S, BranchInst *BI, Loop *L, __isl_keep isl_set *Domain,
778 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
779
780 if (BI->isUnconditional()) {
781 ConditionSets.push_back(isl_set_copy(Domain));
782 return;
783 }
784
785 Value *Condition = BI->getCondition();
786
787 isl_set *ConsequenceCondSet = nullptr;
788 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
789 if (CCond->isZero())
790 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
791 else
792 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
793 } else {
794 auto *ICond = dyn_cast<ICmpInst>(Condition);
795 assert(ICond &&
796 "Condition of exiting branch was neither constant nor ICmp!");
797
798 ScalarEvolution &SE = *S.getSE();
799 isl_pw_aff *LHS, *RHS;
800 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), Domain);
801 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), Domain);
802 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), LHS, RHS);
803 }
804
805 assert(ConsequenceCondSet);
806 isl_set *AlternativeCondSet =
807 isl_set_complement(isl_set_copy(ConsequenceCondSet));
808
809 ConditionSets.push_back(isl_set_coalesce(
810 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
811 ConditionSets.push_back(isl_set_coalesce(
812 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
813}
814
Johannes Doerfertd020b772015-08-27 06:53:52 +0000815void ScopStmt::addLoopTripCountToDomain(const Loop *L) {
816
Johannes Doerfert96425c22015-08-30 21:13:53 +0000817 int RelativeLoopDimension = getParent()->getRelativeLoopDepth(L);
818 assert(RelativeLoopDimension >= 0 &&
819 "Expected relative loop depth of L to be non-negative");
820 unsigned loopDimension = RelativeLoopDimension;
821
Johannes Doerfertd020b772015-08-27 06:53:52 +0000822 ScalarEvolution *SE = getParent()->getSE();
823 isl_space *DomSpace = isl_set_get_space(Domain);
824
825 isl_space *MapSpace = isl_space_map_from_set(isl_space_copy(DomSpace));
826 isl_multi_aff *LoopMAff = isl_multi_aff_identity(MapSpace);
827 isl_aff *LoopAff = isl_multi_aff_get_aff(LoopMAff, loopDimension);
828 LoopAff = isl_aff_add_constant_si(LoopAff, 1);
829 LoopMAff = isl_multi_aff_set_aff(LoopMAff, loopDimension, LoopAff);
830 isl_map *TranslationMap = isl_map_from_multi_aff(LoopMAff);
831
832 BasicBlock *ExitingBB = L->getExitingBlock();
833 assert(ExitingBB && "Loop has more than one exiting block");
834
835 BranchInst *Term = dyn_cast<BranchInst>(ExitingBB->getTerminator());
836 assert(Term && Term->isConditional() && "Terminator is not conditional");
837
838 const SCEV *LHS = nullptr;
839 const SCEV *RHS = nullptr;
840 Value *Cond = Term->getCondition();
841 CmpInst::Predicate Pred = CmpInst::Predicate::BAD_ICMP_PREDICATE;
842
843 ICmpInst *CondICmpInst = dyn_cast<ICmpInst>(Cond);
844 ConstantInt *CondConstant = dyn_cast<ConstantInt>(Cond);
845 if (CondICmpInst) {
846 LHS = SE->getSCEVAtScope(CondICmpInst->getOperand(0), L);
847 RHS = SE->getSCEVAtScope(CondICmpInst->getOperand(1), L);
848 Pred = CondICmpInst->getPredicate();
849 } else if (CondConstant) {
850 LHS = SE->getConstant(CondConstant);
851 RHS = SE->getConstant(ConstantInt::getTrue(SE->getContext()));
852 Pred = CmpInst::Predicate::ICMP_EQ;
853 } else {
854 llvm_unreachable("Condition is neither a ConstantInt nor a ICmpInst");
855 }
856
857 if (!L->contains(Term->getSuccessor(0)))
858 Pred = ICmpInst::getInversePredicate(Pred);
859 Comparison Comp(LHS, RHS, Pred);
860
Johannes Doerfert96425c22015-08-30 21:13:53 +0000861 isl_pw_aff *LPWA = getPwAff(Comp.getLHS());
862 isl_pw_aff *RPWA = getPwAff(Comp.getRHS());
863
864 isl_set *CondSet = buildConditionSet(Comp.getPred(), LPWA, RPWA);
Johannes Doerfertd020b772015-08-27 06:53:52 +0000865 isl_map *ForwardMap = isl_map_lex_le(isl_space_copy(DomSpace));
866 for (unsigned i = 0; i < isl_set_n_dim(Domain); i++)
867 if (i != loopDimension)
868 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
869
870 ForwardMap = isl_map_apply_range(ForwardMap, isl_map_copy(TranslationMap));
871 isl_set *CondDom = isl_set_subtract(isl_set_copy(Domain), CondSet);
872 isl_set *ForwardCond = isl_set_apply(CondDom, isl_map_copy(ForwardMap));
873 isl_set *ForwardDomain = isl_set_apply(isl_set_copy(Domain), ForwardMap);
874 ForwardCond = isl_set_gist(ForwardCond, ForwardDomain);
875 Domain = isl_set_subtract(Domain, ForwardCond);
876
877 isl_map_free(TranslationMap);
878 isl_space_free(DomSpace);
879}
880
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000881void ScopStmt::addLoopBoundsToDomain(TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000882 isl_space *Space;
883 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000884
Tobias Grossere19661e2011-10-07 08:46:57 +0000885 Space = isl_set_get_space(Domain);
886 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000887
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000888 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000889 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000890 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000891 isl_pw_aff *IV =
892 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000893
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000894 // 0 <= IV.
895 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
896 Domain = isl_set_intersect(Domain, LowerBound);
897
898 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000899 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000900 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Johannes Doerfertd020b772015-08-27 06:53:52 +0000901 if (!isa<SCEVCouldNotCompute>(LatchExecutions)) {
902 isl_pw_aff *UpperBound = getPwAff(LatchExecutions);
903 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
904 Domain = isl_set_intersect(Domain, UpperBoundSet);
905 } else {
906 // If SCEV cannot provide a loop trip count we compute it with ISL.
907 addLoopTripCountToDomain(L);
908 isl_pw_aff_free(IV);
909 }
Tobias Grosser75805372011-04-29 06:27:02 +0000910 }
911
Tobias Grosserf5338802011-10-06 00:03:35 +0000912 isl_local_space_free(LocalSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000913}
914
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000915void ScopStmt::buildDomain(TempScop &tempScop, const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000916 isl_space *Space;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000917 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000918
919 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
920
Tobias Grosser084d8f72012-05-29 09:29:44 +0000921 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
922
Tobias Grossere19661e2011-10-07 08:46:57 +0000923 Domain = isl_set_universe(Space);
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000924 addLoopBoundsToDomain(tempScop);
Johannes Doerfert96425c22015-08-30 21:13:53 +0000925 Domain = isl_set_intersect(Domain, getParent()->getDomainConditions(this));
926 Domain = isl_set_coalesce(Domain);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000927 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000928}
929
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000930void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
931 int Dimension = 0;
932 isl_ctx *Ctx = Parent.getIslCtx();
933 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
934 Type *Ty = GEP->getPointerOperandType();
935 ScalarEvolution &SE = *Parent.getSE();
936
937 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
938 Dimension = 1;
939 Ty = PtrTy->getElementType();
940 }
941
942 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
943 unsigned int Operand = 1 + Dimension;
944
945 if (GEP->getNumOperands() <= Operand)
946 break;
947
948 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
949
950 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000951 isl_pw_aff *AccessOffset = getPwAff(Expr);
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000952 AccessOffset =
953 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
954
955 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
956 isl_local_space_copy(LSpace),
957 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
958
959 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
960 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
961 OutOfBound = isl_set_params(OutOfBound);
962 isl_set *InBound = isl_set_complement(OutOfBound);
963 isl_set *Executed = isl_set_params(getDomain());
964
965 // A => B == !A or B
966 isl_set *InBoundIfExecuted =
967 isl_set_union(isl_set_complement(Executed), InBound);
968
969 Parent.addAssumption(InBoundIfExecuted);
970 }
971
972 Dimension += 1;
973 Ty = ArrayTy->getElementType();
974 }
975
976 isl_local_space_free(LSpace);
977}
978
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000979void ScopStmt::deriveAssumptions(BasicBlock *Block) {
980 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000981 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
982 deriveAssumptionsFromGEP(GEP);
983}
984
Tobias Grosser74394f02013-01-14 22:40:23 +0000985ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000986 Region &R, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000987 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
988 NestLoops(Nest.size()) {
989 // Setup the induction variables.
990 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
991 NestLoops[i] = Nest[i];
992
Tobias Grosser16c44032015-07-09 07:31:45 +0000993 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000994
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000995 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000996
997 BasicBlock *EntryBB = R.getEntry();
998 for (BasicBlock *Block : R.blocks()) {
999 buildAccesses(tempScop, Block, Block != EntryBB);
1000 deriveAssumptions(Block);
1001 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001002 if (DetectReductions)
1003 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001004}
1005
1006ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +00001007 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001008 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
1009 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +00001010 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +00001011 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +00001012 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +00001013
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001014 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001015
Johannes Doerfert45545ff2015-08-16 14:36:01 +00001016 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001017 buildAccesses(tempScop, BB);
1018 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001019 if (DetectReductions)
1020 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001021}
1022
Johannes Doerferte58a0122014-06-27 20:31:28 +00001023/// @brief Collect loads which might form a reduction chain with @p StoreMA
1024///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001025/// Check if the stored value for @p StoreMA is a binary operator with one or
1026/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001027/// used only once (by @p StoreMA) and its load operands are also used only
1028/// once, we have found a possible reduction chain. It starts at an operand
1029/// load and includes the binary operator and @p StoreMA.
1030///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001031/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001032/// escape this block or into any other store except @p StoreMA.
1033void ScopStmt::collectCandiateReductionLoads(
1034 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1035 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1036 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001037 return;
1038
1039 // Skip if there is not one binary operator between the load and the store
1040 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001041 if (!BinOp)
1042 return;
1043
1044 // Skip if the binary operators has multiple uses
1045 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001046 return;
1047
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001048 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001049 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1050 return;
1051
Johannes Doerfert9890a052014-07-01 00:32:29 +00001052 // Skip if the binary operator is outside the current SCoP
1053 if (BinOp->getParent() != Store->getParent())
1054 return;
1055
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001056 // Skip if it is a multiplicative reduction and we disabled them
1057 if (DisableMultiplicativeReductions &&
1058 (BinOp->getOpcode() == Instruction::Mul ||
1059 BinOp->getOpcode() == Instruction::FMul))
1060 return;
1061
Johannes Doerferte58a0122014-06-27 20:31:28 +00001062 // Check the binary operator operands for a candidate load
1063 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1064 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1065 if (!PossibleLoad0 && !PossibleLoad1)
1066 return;
1067
1068 // A load is only a candidate if it cannot escape (thus has only this use)
1069 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001070 if (PossibleLoad0->getParent() == Store->getParent())
1071 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001072 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001073 if (PossibleLoad1->getParent() == Store->getParent())
1074 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001075}
1076
1077/// @brief Check for reductions in this ScopStmt
1078///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001079/// Iterate over all store memory accesses and check for valid binary reduction
1080/// like chains. For all candidates we check if they have the same base address
1081/// and there are no other accesses which overlap with them. The base address
1082/// check rules out impossible reductions candidates early. The overlap check,
1083/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001084/// guarantees that none of the intermediate results will escape during
1085/// execution of the loop nest. We basically check here that no other memory
1086/// access can access the same memory as the potential reduction.
1087void ScopStmt::checkForReductions() {
1088 SmallVector<MemoryAccess *, 2> Loads;
1089 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1090
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001091 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001092 // stores and collecting possible reduction loads.
1093 for (MemoryAccess *StoreMA : MemAccs) {
1094 if (StoreMA->isRead())
1095 continue;
1096
1097 Loads.clear();
1098 collectCandiateReductionLoads(StoreMA, Loads);
1099 for (MemoryAccess *LoadMA : Loads)
1100 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1101 }
1102
1103 // Then check each possible candidate pair.
1104 for (const auto &CandidatePair : Candidates) {
1105 bool Valid = true;
1106 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1107 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1108
1109 // Skip those with obviously unequal base addresses.
1110 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1111 isl_map_free(LoadAccs);
1112 isl_map_free(StoreAccs);
1113 continue;
1114 }
1115
1116 // And check if the remaining for overlap with other memory accesses.
1117 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1118 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1119 isl_set *AllAccs = isl_map_range(AllAccsRel);
1120
1121 for (MemoryAccess *MA : MemAccs) {
1122 if (MA == CandidatePair.first || MA == CandidatePair.second)
1123 continue;
1124
1125 isl_map *AccRel =
1126 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1127 isl_set *Accs = isl_map_range(AccRel);
1128
1129 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1130 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1131 Valid = Valid && isl_set_is_empty(OverlapAccs);
1132 isl_set_free(OverlapAccs);
1133 }
1134 }
1135
1136 isl_set_free(AllAccs);
1137 if (!Valid)
1138 continue;
1139
Johannes Doerfertf6183392014-07-01 20:52:51 +00001140 const LoadInst *Load =
1141 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1142 MemoryAccess::ReductionType RT =
1143 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1144
Johannes Doerferte58a0122014-06-27 20:31:28 +00001145 // If no overlapping access was found we mark the load and store as
1146 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001147 CandidatePair.first->markAsReductionLike(RT);
1148 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001149 }
Tobias Grosser75805372011-04-29 06:27:02 +00001150}
1151
Tobias Grosser74394f02013-01-14 22:40:23 +00001152std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001153
Tobias Grosser54839312015-04-21 11:37:25 +00001154std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001155 auto *S = getSchedule();
1156 auto Str = stringFromIslObj(S);
1157 isl_map_free(S);
1158 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001159}
1160
Tobias Grosser74394f02013-01-14 22:40:23 +00001161unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001162
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001163unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001164
Tobias Grosser75805372011-04-29 06:27:02 +00001165const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1166
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001167const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001168 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001169}
1170
Tobias Grosser74394f02013-01-14 22:40:23 +00001171isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001172
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001173__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001174
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001175__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001176 return isl_set_get_space(Domain);
1177}
1178
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001179__isl_give isl_id *ScopStmt::getDomainId() const {
1180 return isl_set_get_tuple_id(Domain);
1181}
Tobias Grossercd95b772012-08-30 11:49:38 +00001182
Tobias Grosser75805372011-04-29 06:27:02 +00001183ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001184 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001185 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001186}
1187
1188void ScopStmt::print(raw_ostream &OS) const {
1189 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001190 OS.indent(12) << "Domain :=\n";
1191
1192 if (Domain) {
1193 OS.indent(16) << getDomainStr() << ";\n";
1194 } else
1195 OS.indent(16) << "n/a\n";
1196
Tobias Grosser54839312015-04-21 11:37:25 +00001197 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001198
1199 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001200 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001201 } else
1202 OS.indent(16) << "n/a\n";
1203
Tobias Grosser083d3d32014-06-28 08:59:45 +00001204 for (MemoryAccess *Access : MemAccs)
1205 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001206}
1207
1208void ScopStmt::dump() const { print(dbgs()); }
1209
1210//===----------------------------------------------------------------------===//
1211/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001212
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001213void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001214 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1215 isl_set_free(Context);
1216 Context = NewContext;
1217}
1218
Tobias Grosserabfbe632013-02-05 12:09:06 +00001219void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001220 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001221 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001222 if (ParameterIds.find(Parameter) != ParameterIds.end())
1223 continue;
1224
1225 int dimension = Parameters.size();
1226
1227 Parameters.push_back(Parameter);
1228 ParameterIds[Parameter] = dimension;
1229 }
1230}
1231
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001232__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1233 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001234
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001235 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001236 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001237
Tobias Grosser8f99c162011-11-15 11:38:55 +00001238 std::string ParameterName;
1239
1240 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1241 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001242 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001243 }
1244
1245 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001246 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001247
Tobias Grosser20532b82014-04-11 17:56:49 +00001248 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1249 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001250}
Tobias Grosser75805372011-04-29 06:27:02 +00001251
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001252isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1253 isl_set *DomainContext = isl_union_set_params(getDomains());
1254 return isl_set_intersect_params(C, DomainContext);
1255}
1256
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001257void Scop::addUserContext() {
1258 if (UserContextStr.empty())
1259 return;
1260
1261 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1262 isl_space *Space = getParamSpace();
1263 if (isl_space_dim(Space, isl_dim_param) !=
1264 isl_set_dim(UserContext, isl_dim_param)) {
1265 auto SpaceStr = isl_space_to_str(Space);
1266 errs() << "Error: the context provided in -polly-context has not the same "
1267 << "number of dimensions than the computed context. Due to this "
1268 << "mismatch, the -polly-context option is ignored. Please provide "
1269 << "the context in the parameter space: " << SpaceStr << ".\n";
1270 free(SpaceStr);
1271 isl_set_free(UserContext);
1272 isl_space_free(Space);
1273 return;
1274 }
1275
1276 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1277 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1278 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1279
1280 if (strcmp(NameContext, NameUserContext) != 0) {
1281 auto SpaceStr = isl_space_to_str(Space);
1282 errs() << "Error: the name of dimension " << i
1283 << " provided in -polly-context "
1284 << "is '" << NameUserContext << "', but the name in the computed "
1285 << "context is '" << NameContext
1286 << "'. Due to this name mismatch, "
1287 << "the -polly-context option is ignored. Please provide "
1288 << "the context in the parameter space: " << SpaceStr << ".\n";
1289 free(SpaceStr);
1290 isl_set_free(UserContext);
1291 isl_space_free(Space);
1292 return;
1293 }
1294
1295 UserContext =
1296 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1297 isl_space_get_dim_id(Space, isl_dim_param, i));
1298 }
1299
1300 Context = isl_set_intersect(Context, UserContext);
1301 isl_space_free(Space);
1302}
1303
Tobias Grosser6be480c2011-11-08 15:41:13 +00001304void Scop::buildContext() {
1305 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001306 Context = isl_set_universe(isl_space_copy(Space));
1307 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001308}
1309
Tobias Grosser18daaca2012-05-22 10:47:27 +00001310void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001311 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001312 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001313
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001314 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001315
Johannes Doerferte7044942015-02-24 11:58:30 +00001316 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001317 }
1318}
1319
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001320void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001321 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001322 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001323
Tobias Grosser083d3d32014-06-28 08:59:45 +00001324 for (const auto &ParamID : ParameterIds) {
1325 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001326 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001327 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001328 }
1329
1330 // Align the parameters of all data structures to the model.
1331 Context = isl_set_align_params(Context, Space);
1332
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001333 for (ScopStmt &Stmt : *this)
1334 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001335}
1336
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001337void Scop::simplifyAssumedContext() {
1338 // The parameter constraints of the iteration domains give us a set of
1339 // constraints that need to hold for all cases where at least a single
1340 // statement iteration is executed in the whole scop. We now simplify the
1341 // assumed context under the assumption that such constraints hold and at
1342 // least a single statement iteration is executed. For cases where no
1343 // statement instances are executed, the assumptions we have taken about
1344 // the executed code do not matter and can be changed.
1345 //
1346 // WARNING: This only holds if the assumptions we have taken do not reduce
1347 // the set of statement instances that are executed. Otherwise we
1348 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001349 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001350 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001351 // performed. In such a case, modifying the run-time conditions and
1352 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001353 // to not be executed.
1354 //
1355 // Example:
1356 //
1357 // When delinearizing the following code:
1358 //
1359 // for (long i = 0; i < 100; i++)
1360 // for (long j = 0; j < m; j++)
1361 // A[i+p][j] = 1.0;
1362 //
1363 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001364 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001365 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1366 AssumedContext =
1367 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001368 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001369}
1370
Johannes Doerfertb164c792014-09-18 11:17:17 +00001371/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001372static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001373 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1374 isl_pw_multi_aff *MinPMA, *MaxPMA;
1375 isl_pw_aff *LastDimAff;
1376 isl_aff *OneAff;
1377 unsigned Pos;
1378
Johannes Doerfert9143d672014-09-27 11:02:39 +00001379 // Restrict the number of parameters involved in the access as the lexmin/
1380 // lexmax computation will take too long if this number is high.
1381 //
1382 // Experiments with a simple test case using an i7 4800MQ:
1383 //
1384 // #Parameters involved | Time (in sec)
1385 // 6 | 0.01
1386 // 7 | 0.04
1387 // 8 | 0.12
1388 // 9 | 0.40
1389 // 10 | 1.54
1390 // 11 | 6.78
1391 // 12 | 30.38
1392 //
1393 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1394 unsigned InvolvedParams = 0;
1395 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1396 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1397 InvolvedParams++;
1398
1399 if (InvolvedParams > RunTimeChecksMaxParameters) {
1400 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001401 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001402 }
1403 }
1404
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001405 Set = isl_set_remove_divs(Set);
1406
Johannes Doerfertb164c792014-09-18 11:17:17 +00001407 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1408 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1409
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001410 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1411 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1412
Johannes Doerfertb164c792014-09-18 11:17:17 +00001413 // Adjust the last dimension of the maximal access by one as we want to
1414 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1415 // we test during code generation might now point after the end of the
1416 // allocated array but we will never dereference it anyway.
1417 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1418 "Assumed at least one output dimension");
1419 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1420 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1421 OneAff = isl_aff_zero_on_domain(
1422 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1423 OneAff = isl_aff_add_constant_si(OneAff, 1);
1424 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1425 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1426
1427 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1428
1429 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001430 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001431}
1432
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001433static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1434 isl_set *Domain = MA->getStatement()->getDomain();
1435 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1436 return isl_set_reset_tuple_id(Domain);
1437}
1438
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001439/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1440static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001441 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001442 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001443
1444 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1445 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001446 Locations = isl_union_set_coalesce(Locations);
1447 Locations = isl_union_set_detect_equalities(Locations);
1448 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001449 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001450 isl_union_set_free(Locations);
1451 return Valid;
1452}
1453
Johannes Doerfert96425c22015-08-30 21:13:53 +00001454/// @brief Helper to treat non-affine regions and basic blocks the same.
1455///
1456///{
1457
1458/// @brief Return the block that is the representing block for @p RN.
1459static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1460 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1461 : RN->getNodeAs<BasicBlock>();
1462}
1463
1464/// @brief Return the @p idx'th block that is executed after @p RN.
1465static inline BasicBlock *getRegionNodeSuccessor(RegionNode *RN, BranchInst *BI,
1466 unsigned idx) {
1467 if (RN->isSubRegion()) {
1468 assert(idx == 0);
1469 return RN->getNodeAs<Region>()->getExit();
1470 }
1471 return BI->getSuccessor(idx);
1472}
1473
1474/// @brief Return the smallest loop surrounding @p RN.
1475static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1476 if (!RN->isSubRegion())
1477 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1478
1479 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1480 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1481 while (L && NonAffineSubRegion->contains(L))
1482 L = L->getParentLoop();
1483 return L;
1484}
1485
1486///}
1487
1488isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1489 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1490 : Stmt->getRegion()->getEntry();
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001491 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001492}
1493
1494void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1495 DominatorTree &DT) {
1496
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001497 auto *EntryBB = R->getEntry();
1498 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1499 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
1500 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001501
1502 buildDomainsWithBranchConstraints(R, LI, SD, DT);
1503}
1504
1505void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1506 ScopDetection &SD,
1507 DominatorTree &DT) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001508 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001509
1510 // To create the domain for each block in R we iterate over all blocks and
1511 // subregions in R and propagate the conditions under which the current region
1512 // element is executed. To this end we iterate in reverse post order over R as
1513 // it ensures that we first visit all predecessors of a region node (either a
1514 // basic block or a subregion) before we visit the region node itself.
1515 // Initially, only the domain for the SCoP region entry block is set and from
1516 // there we propagate the current domain to all successors, however we add the
1517 // condition that the successor is actually executed next.
1518 // As we are only interested in non-loop carried constraints here we can
1519 // simply skip loop back edges.
1520
1521 ReversePostOrderTraversal<Region *> RTraversal(R);
1522 for (auto *RN : RTraversal) {
1523
1524 // Recurse for affine subregions but go on for basic blocks and non-affine
1525 // subregions.
1526 if (RN->isSubRegion()) {
1527 Region *SubRegion = RN->getNodeAs<Region>();
1528 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1529 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1530 continue;
1531 }
1532 }
1533
1534 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1535 isl_set *Domain = DomainMap[BB];
1536 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1537 assert(Domain && "Due to reverse post order traversal of the region all "
1538 "predecessor of the current region node should have been "
1539 "visited and a domain for this region node should have "
1540 "been set.");
1541
1542 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1543 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1544
1545 // Build the condition sets for the successor nodes of the current region
1546 // node. If it is a non-affine subregion we will always execute the single
1547 // exit node, hence the single entry node domain is the condition set. For
1548 // basic blocks we use the helper function buildConditionSets.
1549 SmallVector<isl_set *, 2> ConditionSets;
1550 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1551 if (RN->isSubRegion())
1552 ConditionSets.push_back(isl_set_copy(Domain));
1553 else
1554 buildConditionSets(*this, BI, BBLoop, Domain, ConditionSets);
1555
1556 // Now iterate over the successors and set their initial domain based on
1557 // their condition set. We skip back edges here and have to be careful when
1558 // we leave a loop not to keep constraints over a dimension that doesn't
1559 // exist anymore.
1560 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
1561 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, BI, u);
1562 isl_set *CondSet = ConditionSets[u];
1563
1564 // Skip back edges.
1565 if (DT.dominates(SuccBB, BB)) {
1566 isl_set_free(CondSet);
1567 continue;
1568 }
1569
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001570 // Do not adjust the number of dimensions if we enter a boxed loop or are
1571 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001572 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001573 Region *SuccRegion = RI.getRegionFor(SuccBB);
1574 if (BBLoop != SuccBBLoop && !RN->isSubRegion() &&
1575 !(SD.isNonAffineSubRegion(SuccRegion, &getRegion()) &&
1576 SuccRegion->contains(SuccBBLoop))) {
1577
1578 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1579 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1580 // and enter a new one we need to drop the old constraints.
1581 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
1582 assert(std::abs(BBLoopDepth - SuccBBLoopDepth) <= 1);
1583 if (BBLoopDepth > SuccBBLoopDepth)
1584 CondSet = isl_set_remove_dims(CondSet, isl_dim_set, BBLoopDepth, 1);
1585 else if (SuccBBLoopDepth > BBLoopDepth)
1586 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
1587 else if (BBLoopDepth >= 0)
1588 CondSet = isl_set_drop_constraints_involving_dims(
1589 CondSet, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001590 }
1591
1592 // Set the domain for the successor or merge it with an existing domain in
1593 // case there are multiple paths (without loop back edges) to the
1594 // successor block.
1595 isl_set *&SuccDomain = DomainMap[SuccBB];
1596 if (!SuccDomain)
1597 SuccDomain = CondSet;
1598 else
1599 SuccDomain = isl_set_union(SuccDomain, CondSet);
1600
1601 SuccDomain = isl_set_coalesce(SuccDomain);
1602 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1603 << "\n");
1604 }
1605 }
1606}
1607
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001608void Scop::buildAliasChecks(AliasAnalysis &AA) {
1609 if (!PollyUseRuntimeAliasChecks)
1610 return;
1611
1612 if (buildAliasGroups(AA))
1613 return;
1614
1615 // If a problem occurs while building the alias groups we need to delete
1616 // this SCoP and pretend it wasn't valid in the first place. To this end
1617 // we make the assumed context infeasible.
1618 addAssumption(isl_set_empty(getParamSpace()));
1619
1620 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1621 << " could not be created as the number of parameters involved "
1622 "is too high. The SCoP will be "
1623 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1624 "the maximal number of parameters but be advised that the "
1625 "compile time might increase exponentially.\n\n");
1626}
1627
Johannes Doerfert9143d672014-09-27 11:02:39 +00001628bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001629 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001630 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001631 // for all memory accesses inside the SCoP.
1632 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001633 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001634 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001635 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001636 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001637 // if their access domains intersect, otherwise they are in different
1638 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001639 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001640 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001641 // and maximal accesses to each array of a group in read only and non
1642 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001643 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1644
1645 AliasSetTracker AST(AA);
1646
1647 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001648 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001649 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001650
1651 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001652 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001653 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1654 isl_set_free(StmtDomain);
1655 if (StmtDomainEmpty)
1656 continue;
1657
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001658 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001659 if (MA->isScalar())
1660 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001661 if (!MA->isRead())
1662 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001663 Instruction *Acc = MA->getAccessInstruction();
1664 PtrToAcc[getPointerOperand(*Acc)] = MA;
1665 AST.add(Acc);
1666 }
1667 }
1668
1669 SmallVector<AliasGroupTy, 4> AliasGroups;
1670 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001671 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001672 continue;
1673 AliasGroupTy AG;
1674 for (auto PR : AS)
1675 AG.push_back(PtrToAcc[PR.getValue()]);
1676 assert(AG.size() > 1 &&
1677 "Alias groups should contain at least two accesses");
1678 AliasGroups.push_back(std::move(AG));
1679 }
1680
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001681 // Split the alias groups based on their domain.
1682 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1683 AliasGroupTy NewAG;
1684 AliasGroupTy &AG = AliasGroups[u];
1685 AliasGroupTy::iterator AGI = AG.begin();
1686 isl_set *AGDomain = getAccessDomain(*AGI);
1687 while (AGI != AG.end()) {
1688 MemoryAccess *MA = *AGI;
1689 isl_set *MADomain = getAccessDomain(MA);
1690 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1691 NewAG.push_back(MA);
1692 AGI = AG.erase(AGI);
1693 isl_set_free(MADomain);
1694 } else {
1695 AGDomain = isl_set_union(AGDomain, MADomain);
1696 AGI++;
1697 }
1698 }
1699 if (NewAG.size() > 1)
1700 AliasGroups.push_back(std::move(NewAG));
1701 isl_set_free(AGDomain);
1702 }
1703
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001704 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001705 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1706 for (AliasGroupTy &AG : AliasGroups) {
1707 NonReadOnlyBaseValues.clear();
1708 ReadOnlyPairs.clear();
1709
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001710 if (AG.size() < 2) {
1711 AG.clear();
1712 continue;
1713 }
1714
Johannes Doerfert13771732014-10-01 12:40:46 +00001715 for (auto II = AG.begin(); II != AG.end();) {
1716 Value *BaseAddr = (*II)->getBaseAddr();
1717 if (HasWriteAccess.count(BaseAddr)) {
1718 NonReadOnlyBaseValues.insert(BaseAddr);
1719 II++;
1720 } else {
1721 ReadOnlyPairs[BaseAddr].insert(*II);
1722 II = AG.erase(II);
1723 }
1724 }
1725
1726 // If we don't have read only pointers check if there are at least two
1727 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00001728 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001729 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00001730 continue;
1731 }
1732
1733 // If we don't have non read only pointers clear the alias group.
1734 if (NonReadOnlyBaseValues.empty()) {
1735 AG.clear();
1736 continue;
1737 }
1738
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001739 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001740 MinMaxAliasGroups.emplace_back();
1741 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
1742 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
1743 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
1744 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001745
1746 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001747
1748 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001749 for (MemoryAccess *MA : AG)
1750 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001751
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00001752 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
1753 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001754
1755 // Bail out if the number of values we need to compare is too large.
1756 // This is important as the number of comparisions grows quadratically with
1757 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001758 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
1759 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001760 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001761
1762 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001763 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001764 Accesses = isl_union_map_empty(getParamSpace());
1765
1766 for (const auto &ReadOnlyPair : ReadOnlyPairs)
1767 for (MemoryAccess *MA : ReadOnlyPair.second)
1768 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1769
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00001770 Valid =
1771 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001772
1773 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001774 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001775 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001776
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001777 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001778}
1779
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001780static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1781 ScopDetection &SD) {
1782
1783 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1784
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001785 unsigned MinLD = INT_MAX, MaxLD = 0;
1786 for (BasicBlock *BB : R.blocks()) {
1787 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001788 if (!R.contains(L))
1789 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001790 if (BoxedLoops && BoxedLoops->count(L))
1791 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001792 unsigned LD = L->getLoopDepth();
1793 MinLD = std::min(MinLD, LD);
1794 MaxLD = std::max(MaxLD, LD);
1795 }
1796 }
1797
1798 // Handle the case that there is no loop in the SCoP first.
1799 if (MaxLD == 0)
1800 return 1;
1801
1802 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1803 assert(MaxLD >= MinLD &&
1804 "Maximal loop depth was smaller than mininaml loop depth?");
1805 return MaxLD - MinLD + 1;
1806}
1807
Johannes Doerfert96425c22015-08-30 21:13:53 +00001808Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, DominatorTree &DT,
1809 isl_ctx *Context, unsigned MaxLoopDepth)
1810 : DT(DT), SE(&ScalarEvolution), R(R), IsOptimized(false),
Johannes Doerfert574182d2015-08-12 10:19:50 +00001811 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001812
Tobias Grosser40985012015-08-20 19:08:05 +00001813void Scop::initFromTempScop(TempScop &TempScop, LoopInfo &LI, ScopDetection &SD,
1814 AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001815 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001816
Johannes Doerfert96425c22015-08-30 21:13:53 +00001817 buildDomains(&R, LI, SD, DT);
1818
Tobias Grosserabfbe632013-02-05 12:09:06 +00001819 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001820
Tobias Grosser54839312015-04-21 11:37:25 +00001821 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001822 // traversing the region tree.
Michael Kruse471a5e32015-07-30 19:27:04 +00001823 Schedule = buildScop(TempScop, getRegion(), NestLoops, LI, SD);
Tobias Grosser808cd692015-07-14 09:33:13 +00001824 if (!Schedule)
1825 Schedule = isl_schedule_empty(getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +00001826
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001827 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001828 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001829 addUserContext();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001830 simplifyAssumedContext();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001831 buildAliasChecks(AA);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001832
Tobias Grosser75805372011-04-29 06:27:02 +00001833 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1834}
1835
Michael Kruse471a5e32015-07-30 19:27:04 +00001836Scop *Scop::createFromTempScop(TempScop &TempScop, LoopInfo &LI,
1837 ScalarEvolution &SE, ScopDetection &SD,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001838 AliasAnalysis &AA, DominatorTree &DT,
1839 isl_ctx *ctx) {
Michael Kruse471a5e32015-07-30 19:27:04 +00001840 auto &R = TempScop.getMaxRegion();
1841 auto MaxLoopDepth = getMaxLoopDepthInRegion(R, LI, SD);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001842 auto S = new Scop(R, SE, DT, ctx, MaxLoopDepth);
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001843 S->initFromTempScop(TempScop, LI, SD, AA);
1844
Michael Kruse471a5e32015-07-30 19:27:04 +00001845 return S;
1846}
1847
Tobias Grosser75805372011-04-29 06:27:02 +00001848Scop::~Scop() {
1849 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001850 isl_set_free(AssumedContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00001851 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001852
Johannes Doerfert96425c22015-08-30 21:13:53 +00001853 for (auto It : DomainMap)
1854 isl_set_free(It.second);
1855
Johannes Doerfertb164c792014-09-18 11:17:17 +00001856 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001857 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001858 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001859 isl_pw_multi_aff_free(MMA.first);
1860 isl_pw_multi_aff_free(MMA.second);
1861 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001862 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001863 isl_pw_multi_aff_free(MMA.first);
1864 isl_pw_multi_aff_free(MMA.second);
1865 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001866 }
Tobias Grosser75805372011-04-29 06:27:02 +00001867}
1868
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001869const ScopArrayInfo *
1870Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser92245222015-07-28 14:53:44 +00001871 const SmallVector<const SCEV *, 4> &Sizes,
1872 bool IsPHI) {
1873 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001874 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001875 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
1876 this));
Tobias Grosserab671442015-05-23 05:58:27 +00001877 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001878}
1879
Tobias Grosser92245222015-07-28 14:53:44 +00001880const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
1881 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001882 assert(SAI && "No ScopArrayInfo available for this base pointer");
1883 return SAI;
1884}
1885
Tobias Grosser74394f02013-01-14 22:40:23 +00001886std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001887std::string Scop::getAssumedContextStr() const {
1888 return stringFromIslObj(AssumedContext);
1889}
Tobias Grosser75805372011-04-29 06:27:02 +00001890
1891std::string Scop::getNameStr() const {
1892 std::string ExitName, EntryName;
1893 raw_string_ostream ExitStr(ExitName);
1894 raw_string_ostream EntryStr(EntryName);
1895
Tobias Grosserf240b482014-01-09 10:42:15 +00001896 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001897 EntryStr.str();
1898
1899 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001900 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001901 ExitStr.str();
1902 } else
1903 ExitName = "FunctionExit";
1904
1905 return EntryName + "---" + ExitName;
1906}
1907
Tobias Grosser74394f02013-01-14 22:40:23 +00001908__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001909__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001910 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00001911}
1912
Tobias Grossere86109f2013-10-29 21:05:49 +00001913__isl_give isl_set *Scop::getAssumedContext() const {
1914 return isl_set_copy(AssumedContext);
1915}
1916
Johannes Doerfert43788c52015-08-20 05:58:56 +00001917__isl_give isl_set *Scop::getRuntimeCheckContext() const {
1918 isl_set *RuntimeCheckContext = getAssumedContext();
1919 return RuntimeCheckContext;
1920}
1921
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001922bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00001923 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001924 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00001925 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
1926 isl_set_free(RuntimeCheckContext);
1927 return IsFeasible;
1928}
1929
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001930void Scop::addAssumption(__isl_take isl_set *Set) {
1931 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001932 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001933}
1934
Tobias Grosser75805372011-04-29 06:27:02 +00001935void Scop::printContext(raw_ostream &OS) const {
1936 OS << "Context:\n";
1937
1938 if (!Context) {
1939 OS.indent(4) << "n/a\n\n";
1940 return;
1941 }
1942
1943 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001944
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001945 OS.indent(4) << "Assumed Context:\n";
1946 if (!AssumedContext) {
1947 OS.indent(4) << "n/a\n\n";
1948 return;
1949 }
1950
1951 OS.indent(4) << getAssumedContextStr() << "\n";
1952
Tobias Grosser083d3d32014-06-28 08:59:45 +00001953 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001954 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001955 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1956 }
Tobias Grosser75805372011-04-29 06:27:02 +00001957}
1958
Johannes Doerfertb164c792014-09-18 11:17:17 +00001959void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001960 int noOfGroups = 0;
1961 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001962 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001963 noOfGroups += 1;
1964 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001965 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001966 }
1967
Tobias Grosserbb853c22015-07-25 12:31:03 +00001968 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00001969 if (MinMaxAliasGroups.empty()) {
1970 OS.indent(8) << "n/a\n";
1971 return;
1972 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001973
Tobias Grosserbb853c22015-07-25 12:31:03 +00001974 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001975
1976 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001977 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001978 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001979 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001980 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1981 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001982 }
1983 OS << " ]]\n";
1984 }
1985
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001986 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001987 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00001988 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001989 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001990 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1991 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001992 }
1993 OS << " ]]\n";
1994 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001995 }
1996}
1997
Tobias Grosser75805372011-04-29 06:27:02 +00001998void Scop::printStatements(raw_ostream &OS) const {
1999 OS << "Statements {\n";
2000
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002001 for (const ScopStmt &Stmt : *this)
2002 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002003
2004 OS.indent(4) << "}\n";
2005}
2006
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002007void Scop::printArrayInfo(raw_ostream &OS) const {
2008 OS << "Arrays {\n";
2009
Tobias Grosserab671442015-05-23 05:58:27 +00002010 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002011 Array.second->print(OS);
2012
2013 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002014
2015 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2016
2017 for (auto &Array : arrays())
2018 Array.second->print(OS, /* SizeAsPwAff */ true);
2019
2020 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002021}
2022
Tobias Grosser75805372011-04-29 06:27:02 +00002023void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002024 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2025 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002026 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002027 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002028 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002029 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002030 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002031 printStatements(OS.indent(4));
2032}
2033
2034void Scop::dump() const { print(dbgs()); }
2035
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002036isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002037
Johannes Doerfertb409fdc2015-08-28 09:24:35 +00002038__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, isl_set *Domain) {
2039 return Affinator.getPwAff(E, Domain);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002040}
2041
Tobias Grosser808cd692015-07-14 09:33:13 +00002042__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002043 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002044
Tobias Grosser808cd692015-07-14 09:33:13 +00002045 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002046 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002047
2048 return Domain;
2049}
2050
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002051__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002052 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002053
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002054 for (ScopStmt &Stmt : *this) {
2055 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002056 if (!MA->isMustWrite())
2057 continue;
2058
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002059 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002060 isl_map *AccessDomain = MA->getAccessRelation();
2061 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2062 Write = isl_union_map_add_map(Write, AccessDomain);
2063 }
2064 }
2065 return isl_union_map_coalesce(Write);
2066}
2067
2068__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002069 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002070
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002071 for (ScopStmt &Stmt : *this) {
2072 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002073 if (!MA->isMayWrite())
2074 continue;
2075
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002076 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002077 isl_map *AccessDomain = MA->getAccessRelation();
2078 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2079 Write = isl_union_map_add_map(Write, AccessDomain);
2080 }
2081 }
2082 return isl_union_map_coalesce(Write);
2083}
2084
Tobias Grosser37eb4222014-02-20 21:43:54 +00002085__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002086 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002087
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002088 for (ScopStmt &Stmt : *this) {
2089 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002090 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002091 continue;
2092
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002093 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002094 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002095 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2096 Write = isl_union_map_add_map(Write, AccessDomain);
2097 }
2098 }
2099 return isl_union_map_coalesce(Write);
2100}
2101
2102__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002103 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002104
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002105 for (ScopStmt &Stmt : *this) {
2106 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002107 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002108 continue;
2109
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002110 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002111 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002112
2113 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2114 Read = isl_union_map_add_map(Read, AccessDomain);
2115 }
2116 }
2117 return isl_union_map_coalesce(Read);
2118}
2119
Tobias Grosser808cd692015-07-14 09:33:13 +00002120__isl_give isl_union_map *Scop::getSchedule() const {
2121 auto Tree = getScheduleTree();
2122 auto S = isl_schedule_get_map(Tree);
2123 isl_schedule_free(Tree);
2124 return S;
2125}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002126
Tobias Grosser808cd692015-07-14 09:33:13 +00002127__isl_give isl_schedule *Scop::getScheduleTree() const {
2128 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2129 getDomains());
2130}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002131
Tobias Grosser808cd692015-07-14 09:33:13 +00002132void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2133 auto *S = isl_schedule_from_domain(getDomains());
2134 S = isl_schedule_insert_partial_schedule(
2135 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2136 isl_schedule_free(Schedule);
2137 Schedule = S;
2138}
2139
2140void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2141 isl_schedule_free(Schedule);
2142 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002143}
2144
2145bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2146 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002147 for (ScopStmt &Stmt : *this) {
2148 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002149 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2150 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2151
2152 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2153 isl_union_set_free(StmtDomain);
2154 isl_union_set_free(NewStmtDomain);
2155 continue;
2156 }
2157
2158 Changed = true;
2159
2160 isl_union_set_free(StmtDomain);
2161 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2162
2163 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002164 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002165 isl_union_set_free(NewStmtDomain);
2166 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002167 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002168 }
2169 isl_union_set_free(Domain);
2170 return Changed;
2171}
2172
Tobias Grosser75805372011-04-29 06:27:02 +00002173ScalarEvolution *Scop::getSE() const { return SE; }
2174
2175bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
2176 if (tempScop.getAccessFunctions(BB))
2177 return false;
2178
2179 return true;
2180}
2181
Tobias Grosser808cd692015-07-14 09:33:13 +00002182struct MapToDimensionDataTy {
2183 int N;
2184 isl_union_pw_multi_aff *Res;
2185};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002186
Tobias Grosser808cd692015-07-14 09:33:13 +00002187// @brief Create a function that maps the elements of 'Set' to its N-th
2188// dimension.
2189//
2190// The result is added to 'User->Res'.
2191//
2192// @param Set The input set.
2193// @param N The dimension to map to.
2194//
2195// @returns Zero if no error occurred, non-zero otherwise.
2196static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2197 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2198 int Dim;
2199 isl_space *Space;
2200 isl_pw_multi_aff *PMA;
2201
2202 Dim = isl_set_dim(Set, isl_dim_set);
2203 Space = isl_set_get_space(Set);
2204 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2205 Dim - Data->N);
2206 if (Data->N > 1)
2207 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2208 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2209
2210 isl_set_free(Set);
2211
2212 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002213}
2214
Tobias Grosser808cd692015-07-14 09:33:13 +00002215// @brief Create a function that maps the elements of Domain to their Nth
2216// dimension.
2217//
2218// @param Domain The set of elements to map.
2219// @param N The dimension to map to.
2220static __isl_give isl_multi_union_pw_aff *
2221mapToDimension(__isl_take isl_union_set *Domain, int N) {
2222 struct MapToDimensionDataTy Data;
2223 isl_space *Space;
2224
2225 Space = isl_union_set_get_space(Domain);
2226 Data.N = N;
2227 Data.Res = isl_union_pw_multi_aff_empty(Space);
2228 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2229 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2230
2231 isl_union_set_free(Domain);
2232 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2233}
2234
2235ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
2236 const Region &CurRegion,
2237 SmallVectorImpl<Loop *> &NestLoops) {
2238 ScopStmt *Stmt;
2239 if (BB) {
2240 Stmts.emplace_back(*this, tempScop, CurRegion, *BB, NestLoops);
2241 Stmt = &Stmts.back();
2242 StmtMap[BB] = Stmt;
2243 } else {
2244 assert(R && "Either basic block or a region expected.");
2245 Stmts.emplace_back(*this, tempScop, CurRegion, *R, NestLoops);
2246 Stmt = &Stmts.back();
2247 for (BasicBlock *BB : R->blocks())
2248 StmtMap[BB] = Stmt;
2249 }
2250 return Stmt;
2251}
2252
Michael Kruse046dde42015-08-10 13:01:57 +00002253__isl_give isl_schedule *
2254Scop::buildBBScopStmt(BasicBlock *BB, TempScop &tempScop,
2255 const Region &CurRegion,
2256 SmallVectorImpl<Loop *> &NestLoops) {
2257 if (isTrivialBB(BB, tempScop))
2258 return nullptr;
2259
2260 auto *Stmt = addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops);
2261 auto *Domain = Stmt->getDomain();
2262 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2263}
2264
Tobias Grosser808cd692015-07-14 09:33:13 +00002265__isl_give isl_schedule *Scop::buildScop(TempScop &tempScop,
2266 const Region &CurRegion,
2267 SmallVectorImpl<Loop *> &NestLoops,
2268 LoopInfo &LI, ScopDetection &SD) {
2269 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion())) {
2270 auto *Stmt = addScopStmt(nullptr, const_cast<Region *>(&CurRegion),
2271 tempScop, CurRegion, NestLoops);
2272 auto *Domain = Stmt->getDomain();
2273 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2274 }
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002275
Tobias Grosser75805372011-04-29 06:27:02 +00002276 Loop *L = castToLoop(CurRegion, LI);
2277
2278 if (L)
2279 NestLoops.push_back(L);
2280
2281 unsigned loopDepth = NestLoops.size();
Tobias Grosser808cd692015-07-14 09:33:13 +00002282 isl_schedule *Schedule = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002283
2284 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00002285 E = CurRegion.element_end();
Tobias Grosser808cd692015-07-14 09:33:13 +00002286 I != E; ++I) {
2287 isl_schedule *StmtSchedule = nullptr;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002288 if (I->isSubRegion()) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002289 StmtSchedule =
2290 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, LI, SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002291 } else {
Michael Kruse046dde42015-08-10 13:01:57 +00002292 StmtSchedule = buildBBScopStmt(I->getNodeAs<BasicBlock>(), tempScop,
2293 CurRegion, NestLoops);
Tobias Grosser75805372011-04-29 06:27:02 +00002294 }
Michael Kruse046dde42015-08-10 13:01:57 +00002295 Schedule = combineInSequence(Schedule, StmtSchedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00002296 }
Tobias Grosser75805372011-04-29 06:27:02 +00002297
Tobias Grosser808cd692015-07-14 09:33:13 +00002298 if (!L)
2299 return Schedule;
2300
2301 auto *Domain = isl_schedule_get_domain(Schedule);
2302 if (!isl_union_set_is_empty(Domain)) {
2303 auto *MUPA = mapToDimension(isl_union_set_copy(Domain), loopDepth);
2304 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
2305 }
2306 isl_union_set_free(Domain);
2307
Tobias Grosser75805372011-04-29 06:27:02 +00002308 NestLoops.pop_back();
Tobias Grosser808cd692015-07-14 09:33:13 +00002309 return Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00002310}
2311
Johannes Doerfert7c494212014-10-31 23:13:39 +00002312ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002313 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002314 if (StmtMapIt == StmtMap.end())
2315 return nullptr;
2316 return StmtMapIt->second;
2317}
2318
Johannes Doerfert96425c22015-08-30 21:13:53 +00002319int Scop::getRelativeLoopDepth(const Loop *L) const {
2320 Loop *OuterLoop =
2321 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2322 if (!OuterLoop)
2323 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002324 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2325}
2326
Tobias Grosser75805372011-04-29 06:27:02 +00002327//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00002328ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
2329 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002330 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002331}
2332
2333ScopInfo::~ScopInfo() {
2334 clear();
2335 isl_ctx_free(ctx);
2336}
2337
Tobias Grosser75805372011-04-29 06:27:02 +00002338void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002339 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002340 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002341 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002342 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002343 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002344 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002345 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00002346 AU.setPreservesAll();
2347}
2348
2349bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002350 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002351 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002352 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002353 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002354 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00002355
Michael Kruse82a1c7d2015-08-14 20:10:27 +00002356 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop();
Tobias Grosser75805372011-04-29 06:27:02 +00002357
2358 // This region is no Scop.
2359 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002360 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002361 return false;
2362 }
2363
Johannes Doerfert96425c22015-08-30 21:13:53 +00002364 scop = Scop::createFromTempScop(*tempScop, LI, SE, SD, AA, DT, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002365
Tobias Grosserd6a50b32015-05-30 06:26:21 +00002366 DEBUG(scop->print(dbgs()));
2367
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002368 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002369 delete scop;
2370 scop = nullptr;
2371 return false;
2372 }
2373
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002374 // Statistics.
2375 ++ScopFound;
2376 if (scop->getMaxLoopDepth() > 0)
2377 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00002378 return false;
2379}
2380
2381char ScopInfo::ID = 0;
2382
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002383Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2384
Tobias Grosser73600b82011-10-08 00:30:40 +00002385INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2386 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002387 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002388INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002389INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002390INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002391INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002392INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002393INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002394INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00002395INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2396 "Polly - Create polyhedral description of Scops", false,
2397 false)