blob: efa42600e7edd24e7a54bb97e39f3ab821bc4eba [file] [log] [blame]
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001
Tobias Grosser75805372011-04-29 06:27:02 +00002//
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"
Michael Kruse7bf39442015-09-10 12:46:52 +000026#include "polly/CodeGen/BlockGenerators.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 Doerfertb68cffb2015-09-10 15:27:46 +000033#include "llvm/Analysis/LoopIterator.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000034#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000036#include "llvm/Analysis/RegionIterator.h"
37#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000038#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000039#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000040#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000041#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000043#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000045#include "isl/schedule.h"
46#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "isl/set.h"
48#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000049#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000050#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000051#include <sstream>
52#include <string>
53#include <vector>
54
55using namespace llvm;
56using namespace polly;
57
Chandler Carruth95fef942014-04-22 03:30:19 +000058#define DEBUG_TYPE "polly-scops"
59
Tobias Grosser74394f02013-01-14 22:40:23 +000060STATISTIC(ScopFound, "Number of valid Scops");
61STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000062
Michael Kruse7bf39442015-09-10 12:46:52 +000063static cl::opt<bool> ModelReadOnlyScalars(
64 "polly-analyze-read-only-scalars",
65 cl::desc("Model read-only scalar values in the scop description"),
66 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
67
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000068// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000069// operations can overflow easily. Additive reductions and bit operations
70// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000071static cl::opt<bool> DisableMultiplicativeReductions(
72 "polly-disable-multiplicative-reductions",
73 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
74 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000075
Johannes Doerfert9143d672014-09-27 11:02:39 +000076static cl::opt<unsigned> RunTimeChecksMaxParameters(
77 "polly-rtc-max-parameters",
78 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
79 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
80
Tobias Grosser71500722015-03-28 15:11:14 +000081static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
82 "polly-rtc-max-arrays-per-group",
83 cl::desc("The maximal number of arrays to compare in each alias group."),
84 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000085static cl::opt<std::string> UserContextStr(
86 "polly-context", cl::value_desc("isl parameter set"),
87 cl::desc("Provide additional constraints on the context parameters"),
88 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000089
Tobias Grosserd83b8a82015-08-20 19:08:11 +000090static cl::opt<bool> DetectReductions("polly-detect-reductions",
91 cl::desc("Detect and exploit reductions"),
92 cl::Hidden, cl::ZeroOrMore,
93 cl::init(true), cl::cat(PollyCategory));
94
Michael Kruse7bf39442015-09-10 12:46:52 +000095//===----------------------------------------------------------------------===//
96/// Helper Classes
97
98void Comparison::print(raw_ostream &OS) const {
99 // Not yet implemented.
100}
101
Michael Kruse046dde42015-08-10 13:01:57 +0000102// Create a sequence of two schedules. Either argument may be null and is
103// interpreted as the empty schedule. Can also return null if both schedules are
104// empty.
105static __isl_give isl_schedule *
106combineInSequence(__isl_take isl_schedule *Prev,
107 __isl_take isl_schedule *Succ) {
108 if (!Prev)
109 return Succ;
110 if (!Succ)
111 return Prev;
112
113 return isl_schedule_sequence(Prev, Succ);
114}
115
Johannes Doerferte7044942015-02-24 11:58:30 +0000116static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
117 const ConstantRange &Range,
118 int dim,
119 enum isl_dim_type type) {
120 isl_val *V;
121 isl_ctx *ctx = isl_set_get_ctx(S);
122
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000123 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
124 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000125 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000126 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
127
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000128 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000129 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000131 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000132 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
133
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000134 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000135 return isl_set_union(SLB, SUB);
136 else
137 return isl_set_intersect(SLB, SUB);
138}
139
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000140static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
141 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
142 if (!BasePtrLI)
143 return nullptr;
144
145 if (!S->getRegion().contains(BasePtrLI))
146 return nullptr;
147
148 ScalarEvolution &SE = *S->getSE();
149
150 auto *OriginBaseSCEV =
151 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
152 if (!OriginBaseSCEV)
153 return nullptr;
154
155 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
156 if (!OriginBaseSCEVUnknown)
157 return nullptr;
158
159 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
160}
161
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000162ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Michael Kruse28468772015-09-14 15:45:33 +0000163 ArrayRef<const SCEV *> DimensionSizes, bool IsPHI,
164 Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000165 : BasePtr(BasePtr), ElementType(ElementType),
Michael Kruse28468772015-09-14 15:45:33 +0000166 DimensionSizes(DimensionSizes.begin(), DimensionSizes.end()),
167 IsPHI(IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +0000168 std::string BasePtrName =
169 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000170 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000171 for (const SCEV *Expr : DimensionSizes) {
172 isl_pw_aff *Size = S->getPwAff(Expr);
173 DimensionSizesPw.push_back(Size);
174 }
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000175
176 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
177 if (BasePtrOriginSAI)
178 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000179}
180
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000181ScopArrayInfo::~ScopArrayInfo() {
182 isl_id_free(Id);
183 for (isl_pw_aff *Size : DimensionSizesPw)
184 isl_pw_aff_free(Size);
185}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000186
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000187std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
188
189int ScopArrayInfo::getElemSizeInBytes() const {
190 return ElementType->getPrimitiveSizeInBits() / 8;
191}
192
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000193isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
194
195void ScopArrayInfo::dump() const { print(errs()); }
196
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000197void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000198 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000199 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
200 OS << "[";
201
202 if (SizeAsPwAff)
203 OS << " " << DimensionSizesPw[u] << " ";
204 else
205 OS << *DimensionSizes[u];
206
207 OS << "]";
208 }
209
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000210 if (BasePtrOriginSAI)
211 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
212
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000213 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000214}
215
216const ScopArrayInfo *
217ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
218 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
219 assert(Id && "Output dimension didn't have an ID");
220 return getFromId(Id);
221}
222
223const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
224 void *User = isl_id_get_user(Id);
225 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
226 isl_id_free(Id);
227 return SAI;
228}
229
Michael Krusee2bccbb2015-09-18 19:59:43 +0000230void MemoryAccess::printIR(raw_ostream &OS) const {
Michael Kruse7bf39442015-09-10 12:46:52 +0000231 if (isRead())
232 OS << "Read ";
233 else {
234 if (isMayWrite())
235 OS << "May";
236 OS << "Write ";
237 }
Michael Krusee2bccbb2015-09-18 19:59:43 +0000238 OS << BaseAddr->getName() << '[' << *Offset << "]\n";
Michael Kruse7bf39442015-09-10 12:46:52 +0000239}
240
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000241const std::string
242MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
243 switch (RT) {
244 case MemoryAccess::RT_NONE:
245 llvm_unreachable("Requested a reduction operator string for a memory "
246 "access which isn't a reduction");
247 case MemoryAccess::RT_ADD:
248 return "+";
249 case MemoryAccess::RT_MUL:
250 return "*";
251 case MemoryAccess::RT_BOR:
252 return "|";
253 case MemoryAccess::RT_BXOR:
254 return "^";
255 case MemoryAccess::RT_BAND:
256 return "&";
257 }
258 llvm_unreachable("Unknown reduction type");
259 return "";
260}
261
Johannes Doerfertf6183392014-07-01 20:52:51 +0000262/// @brief Return the reduction type for a given binary operator
263static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
264 const Instruction *Load) {
265 if (!BinOp)
266 return MemoryAccess::RT_NONE;
267 switch (BinOp->getOpcode()) {
268 case Instruction::FAdd:
269 if (!BinOp->hasUnsafeAlgebra())
270 return MemoryAccess::RT_NONE;
271 // Fall through
272 case Instruction::Add:
273 return MemoryAccess::RT_ADD;
274 case Instruction::Or:
275 return MemoryAccess::RT_BOR;
276 case Instruction::Xor:
277 return MemoryAccess::RT_BXOR;
278 case Instruction::And:
279 return MemoryAccess::RT_BAND;
280 case Instruction::FMul:
281 if (!BinOp->hasUnsafeAlgebra())
282 return MemoryAccess::RT_NONE;
283 // Fall through
284 case Instruction::Mul:
285 if (DisableMultiplicativeReductions)
286 return MemoryAccess::RT_NONE;
287 return MemoryAccess::RT_MUL;
288 default:
289 return MemoryAccess::RT_NONE;
290 }
291}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000292
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000293/// @brief Derive the individual index expressions from a GEP instruction
294///
295/// This function optimistically assumes the GEP references into a fixed size
296/// array. If this is actually true, this function returns a list of array
297/// subscript expressions as SCEV as well as a list of integers describing
298/// the size of the individual array dimensions. Both lists have either equal
299/// length of the size list is one element shorter in case there is no known
300/// size available for the outermost array dimension.
301///
302/// @param GEP The GetElementPtr instruction to analyze.
303///
304/// @return A tuple with the subscript expressions and the dimension sizes.
305static std::tuple<std::vector<const SCEV *>, std::vector<int>>
306getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
307 std::vector<const SCEV *> Subscripts;
308 std::vector<int> Sizes;
309
310 Type *Ty = GEP->getPointerOperandType();
311
312 bool DroppedFirstDim = false;
313
314 for (long i = 1; i < GEP->getNumOperands(); i++) {
315
316 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
317
318 if (i == 1) {
319 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
320 Ty = PtrTy->getElementType();
321 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
322 Ty = ArrayTy->getElementType();
323 } else {
324 Subscripts.clear();
325 Sizes.clear();
326 break;
327 }
328 if (auto Const = dyn_cast<SCEVConstant>(Expr))
329 if (Const->getValue()->isZero()) {
330 DroppedFirstDim = true;
331 continue;
332 }
333 Subscripts.push_back(Expr);
334 continue;
335 }
336
337 auto ArrayTy = dyn_cast<ArrayType>(Ty);
338 if (!ArrayTy) {
339 Subscripts.clear();
340 Sizes.clear();
341 break;
342 }
343
344 Subscripts.push_back(Expr);
345 if (!(DroppedFirstDim && i == 2))
346 Sizes.push_back(ArrayTy->getNumElements());
347
348 Ty = ArrayTy->getElementType();
349 }
350
351 return std::make_tuple(Subscripts, Sizes);
352}
353
Tobias Grosser75805372011-04-29 06:27:02 +0000354MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000355 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000356 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000357 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000358}
359
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000360const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
361 isl_id *ArrayId = getArrayId();
362 void *User = isl_id_get_user(ArrayId);
363 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
364 isl_id_free(ArrayId);
365 return SAI;
366}
367
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000368__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000369 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
370}
371
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000372__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
373 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000374 isl_map *Schedule, *ScheduledAccRel;
375 isl_union_set *UDomain;
376
377 UDomain = isl_union_set_from_set(getStatement()->getDomain());
378 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
379 Schedule = isl_map_from_union_map(USchedule);
380 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
381 return isl_pw_multi_aff_from_map(ScheduledAccRel);
382}
383
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000384__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000385 return isl_map_copy(AccessRelation);
386}
387
Johannes Doerferta99130f2014-10-13 12:58:03 +0000388std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000389 return stringFromIslObj(AccessRelation);
390}
391
Johannes Doerferta99130f2014-10-13 12:58:03 +0000392__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000393 return isl_map_get_space(AccessRelation);
394}
395
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000396__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000397 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000398}
399
Tobias Grosser6f730082015-09-05 07:46:47 +0000400std::string MemoryAccess::getNewAccessRelationStr() const {
401 return stringFromIslObj(NewAccessRelation);
402}
403
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000404__isl_give isl_basic_map *
405MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000406 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000407 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000408
Tobias Grosser084d8f72012-05-29 09:29:44 +0000409 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000410 isl_basic_set_universe(Statement->getDomainSpace()),
411 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000412}
413
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000414// Formalize no out-of-bound access assumption
415//
416// When delinearizing array accesses we optimistically assume that the
417// delinearized accesses do not access out of bound locations (the subscript
418// expression of each array evaluates for each statement instance that is
419// executed to a value that is larger than zero and strictly smaller than the
420// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000421// dimension for which we do not need to assume any upper bound. At this point
422// we formalize this assumption to ensure that at code generation time the
423// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000424//
425// To find the set of constraints necessary to avoid out of bound accesses, we
426// first build the set of data locations that are not within array bounds. We
427// then apply the reverse access relation to obtain the set of iterations that
428// may contain invalid accesses and reduce this set of iterations to the ones
429// that are actually executed by intersecting them with the domain of the
430// statement. If we now project out all loop dimensions, we obtain a set of
431// parameters that may cause statement instances to be executed that may
432// possibly yield out of bound memory accesses. The complement of these
433// constraints is the set of constraints that needs to be assumed to ensure such
434// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000435void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000436 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000437 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000438 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000439 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
440 isl_pw_aff *Var =
441 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
442 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
443
444 isl_set *DimOutside;
445
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000446 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000447 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000448
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000449 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
450 Statement->getNumIterators());
451 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
452 isl_space_dim(Space, isl_dim_set));
453 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
454 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000455
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000456 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000457
458 Outside = isl_set_union(Outside, DimOutside);
459 }
460
461 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
462 Outside = isl_set_intersect(Outside, Statement->getDomain());
463 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000464
465 // Remove divs to avoid the construction of overly complicated assumptions.
466 // Doing so increases the set of parameter combinations that are assumed to
467 // not appear. This is always save, but may make the resulting run-time check
468 // bail out more often than strictly necessary.
469 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000470 Outside = isl_set_complement(Outside);
471 Statement->getParent()->addAssumption(Outside);
472 isl_space_free(Space);
473}
474
Johannes Doerferte7044942015-02-24 11:58:30 +0000475void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
476 ScalarEvolution *SE = Statement->getParent()->getSE();
477
478 Value *Ptr = getPointerOperand(*getAccessInstruction());
479 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
480 return;
481
482 auto *PtrSCEV = SE->getSCEV(Ptr);
483 if (isa<SCEVCouldNotCompute>(PtrSCEV))
484 return;
485
486 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
487 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
488 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
489
490 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
491 if (Range.isFullSet())
492 return;
493
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000494 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000495 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000496 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
497 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
498
499 auto Min = LB.sdiv(APInt(BW, ElementSize));
500 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000501
502 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
503 AccessRange =
504 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
505 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
506}
507
Michael Krusee2bccbb2015-09-18 19:59:43 +0000508__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000509 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000510 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000511
512 for (int i = Size - 2; i >= 0; --i) {
513 isl_space *Space;
514 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000515 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000516
517 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
518 isl_pw_aff_free(DimSize);
519 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
520
521 Space = isl_map_get_space(AccessRelation);
522 Space = isl_space_map_from_set(isl_space_range(Space));
523 Space = isl_space_align_params(Space, SpaceSize);
524
525 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
526 isl_id_free(ParamId);
527
528 MapOne = isl_map_universe(isl_space_copy(Space));
529 for (int j = 0; j < Size; ++j)
530 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
531 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
532
533 MapTwo = isl_map_universe(isl_space_copy(Space));
534 for (int j = 0; j < Size; ++j)
535 if (j < i || j > i + 1)
536 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
537
538 isl_local_space *LS = isl_local_space_from_space(Space);
539 isl_constraint *C;
540 C = isl_equality_alloc(isl_local_space_copy(LS));
541 C = isl_constraint_set_constant_si(C, -1);
542 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
543 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
544 MapTwo = isl_map_add_constraint(MapTwo, C);
545 C = isl_equality_alloc(LS);
546 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
547 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
548 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
549 MapTwo = isl_map_add_constraint(MapTwo, C);
550 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
551
552 MapOne = isl_map_union(MapOne, MapTwo);
553 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
554 }
555 return AccessRelation;
556}
557
Michael Krusee2bccbb2015-09-18 19:59:43 +0000558void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
559 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000560
Michael Krusee2bccbb2015-09-18 19:59:43 +0000561 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000562 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000563
Michael Krusee2bccbb2015-09-18 19:59:43 +0000564 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000565 // We overapproximate non-affine accesses with a possible access to the
566 // whole array. For read accesses it does not make a difference, if an
567 // access must or may happen. However, for write accesses it is important to
568 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000569 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000570 AccessRelation =
571 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000572
Michael Krusee2bccbb2015-09-18 19:59:43 +0000573 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000574 return;
575 }
576
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000577 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000578 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000579
Michael Krusee2bccbb2015-09-18 19:59:43 +0000580 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
581 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000582
Sebastian Pop422e33f2014-06-03 18:16:31 +0000583 if (Size == 1) {
584 // For the non delinearized arrays, divide the access function of the last
585 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000586 //
587 // A stride one array access in C expressed as A[i] is expressed in
588 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
589 // two subsequent values of 'i' index two values that are stored next to
590 // each other in memory. By this division we make this characteristic
591 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000592 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000593 Affine = isl_pw_aff_scale_down_val(Affine, v);
594 }
595
596 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
597
Tobias Grosser79baa212014-04-10 08:38:02 +0000598 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000599 }
600
Michael Krusee2bccbb2015-09-18 19:59:43 +0000601 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
602 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000603
Tobias Grosser79baa212014-04-10 08:38:02 +0000604 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000605 AccessRelation = isl_map_set_tuple_id(
606 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000607 AccessRelation =
608 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
609
Michael Krusee2bccbb2015-09-18 19:59:43 +0000610 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000611 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000612 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000613}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000614
Michael Krusee2bccbb2015-09-18 19:59:43 +0000615MemoryAccess::MemoryAccess(Instruction *AccessInst, __isl_take isl_id *Id,
616 AccessType Type, Value *BaseAddress,
617 const SCEV *Offset, unsigned ElemBytes, bool Affine,
618 ArrayRef<const SCEV *> Subscripts,
619 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
620 bool IsPHI, StringRef BaseName)
621 : Id(Id), IsPHI(IsPHI), AccType(Type), RedType(RT_NONE), Statement(nullptr),
622 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
623 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
624 AccessValue(AccessValue), Offset(Offset), IsAffine(Affine),
625 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
626 NewAccessRelation(nullptr) {}
627
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000628void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000629 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000630 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000631}
632
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000633const std::string MemoryAccess::getReductionOperatorStr() const {
634 return MemoryAccess::getReductionOperatorStr(getReductionType());
635}
636
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000637__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
638
Johannes Doerfertf6183392014-07-01 20:52:51 +0000639raw_ostream &polly::operator<<(raw_ostream &OS,
640 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000641 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000642 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000643 else
644 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000645 return OS;
646}
647
Tobias Grosser75805372011-04-29 06:27:02 +0000648void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000649 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000650 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000651 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000652 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000653 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000654 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000655 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000656 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000657 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000658 break;
659 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000660 OS << "[Reduction Type: " << getReductionType() << "] ";
661 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000662 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000663 if (hasNewAccessRelation())
664 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000665}
666
Tobias Grosser74394f02013-01-14 22:40:23 +0000667void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000668
669// Create a map in the size of the provided set domain, that maps from the
670// one element of the provided set domain to another element of the provided
671// set domain.
672// The mapping is limited to all points that are equal in all but the last
673// dimension and for which the last dimension of the input is strict smaller
674// than the last dimension of the output.
675//
676// getEqualAndLarger(set[i0, i1, ..., iX]):
677//
678// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
679// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
680//
Tobias Grosserf5338802011-10-06 00:03:35 +0000681static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000682 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000683 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000684 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000685
686 // Set all but the last dimension to be equal for the input and output
687 //
688 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
689 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000690 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000691 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000692
693 // Set the last dimension of the input to be strict smaller than the
694 // last dimension of the output.
695 //
696 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000697 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
698 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000699 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000700}
701
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000702__isl_give isl_set *
703MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000704 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000705 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000706 isl_space *Space = isl_space_range(isl_map_get_space(S));
707 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000708
Sebastian Popa00a0292012-12-18 07:46:06 +0000709 S = isl_map_reverse(S);
710 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000711
Sebastian Popa00a0292012-12-18 07:46:06 +0000712 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
713 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
714 NextScatt = isl_map_apply_domain(NextScatt, S);
715 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000716
Sebastian Popa00a0292012-12-18 07:46:06 +0000717 isl_set *Deltas = isl_map_deltas(NextScatt);
718 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000719}
720
Sebastian Popa00a0292012-12-18 07:46:06 +0000721bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000722 int StrideWidth) const {
723 isl_set *Stride, *StrideX;
724 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000725
Sebastian Popa00a0292012-12-18 07:46:06 +0000726 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000727 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000728 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
729 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
730 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
731 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000732 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000733
Tobias Grosser28dd4862012-01-24 16:42:16 +0000734 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000735 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000736
Tobias Grosser28dd4862012-01-24 16:42:16 +0000737 return IsStrideX;
738}
739
Sebastian Popa00a0292012-12-18 07:46:06 +0000740bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
741 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000742}
743
Tobias Grosser79baa212014-04-10 08:38:02 +0000744bool MemoryAccess::isScalar() const {
745 return isl_map_n_out(AccessRelation) == 0;
746}
747
Sebastian Popa00a0292012-12-18 07:46:06 +0000748bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
749 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000750}
751
Tobias Grosser166c4222015-09-05 07:46:40 +0000752void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
753 isl_map_free(NewAccessRelation);
754 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000755}
Tobias Grosser75805372011-04-29 06:27:02 +0000756
757//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000758
Tobias Grosser808cd692015-07-14 09:33:13 +0000759isl_map *ScopStmt::getSchedule() const {
760 isl_set *Domain = getDomain();
761 if (isl_set_is_empty(Domain)) {
762 isl_set_free(Domain);
763 return isl_map_from_aff(
764 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
765 }
766 auto *Schedule = getParent()->getSchedule();
767 Schedule = isl_union_map_intersect_domain(
768 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
769 if (isl_union_map_is_empty(Schedule)) {
770 isl_set_free(Domain);
771 isl_union_map_free(Schedule);
772 return isl_map_from_aff(
773 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
774 }
775 auto *M = isl_map_from_union_map(Schedule);
776 M = isl_map_coalesce(M);
777 M = isl_map_gist_domain(M, Domain);
778 M = isl_map_coalesce(M);
779 return M;
780}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000781
Johannes Doerfert574182d2015-08-12 10:19:50 +0000782__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000783 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
784 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000785}
786
Tobias Grosser37eb4222014-02-20 21:43:54 +0000787void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
788 assert(isl_set_is_subset(NewDomain, Domain) &&
789 "New domain is not a subset of old domain!");
790 isl_set_free(Domain);
791 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000792}
793
Michael Kruse9d080092015-09-11 21:41:48 +0000794void ScopStmt::buildAccesses(BasicBlock *Block, bool isApproximated) {
795 AccFuncSetType *AFS = Parent.getAccessFunctions(Block);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000796 if (!AFS)
797 return;
798
Michael Krusee2bccbb2015-09-18 19:59:43 +0000799 for (auto &Access : *AFS) {
800 Instruction *AccessInst = Access.getAccessInstruction();
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000801 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000802
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000803 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Michael Krusee2bccbb2015-09-18 19:59:43 +0000804 Access.getBaseAddr(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000805
Michael Krusee2bccbb2015-09-18 19:59:43 +0000806 if (isApproximated && Access.isMustWrite())
807 Access.AccType = MemoryAccess::MAY_WRITE;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000808
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000809 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
810 if (!MAL)
811 MAL = new MemoryAccessList();
Michael Krusee2bccbb2015-09-18 19:59:43 +0000812 Access.setStatement(this);
813 Access.buildAccessRelation(SAI);
814 MAL->emplace_front(&Access);
815 MemAccs.push_back(MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000816 }
817}
818
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000819void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000820 for (MemoryAccess *MA : *this)
821 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000822
823 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000824}
825
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000826/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
827static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
828 void *User) {
829 isl_set **BoundedParts = static_cast<isl_set **>(User);
830 if (isl_basic_set_is_bounded(BSet))
831 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
832 else
833 isl_basic_set_free(BSet);
834 return isl_stat_ok;
835}
836
837/// @brief Return the bounded parts of @p S.
838static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
839 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
840 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
841 isl_set_free(S);
842 return BoundedParts;
843}
844
845/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
846///
847/// @returns A separation of @p S into first an unbounded then a bounded subset,
848/// both with regards to the dimension @p Dim.
849static std::pair<__isl_give isl_set *, __isl_give isl_set *>
850partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
851
852 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000853 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000854
855 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000856 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000857
858 // Remove dimensions that are greater than Dim as they are not interesting.
859 assert(NumDimsS >= Dim + 1);
860 OnlyDimS =
861 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
862
863 // Create artificial parametric upper bounds for dimensions smaller than Dim
864 // as we are not interested in them.
865 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
866 for (unsigned u = 0; u < Dim; u++) {
867 isl_constraint *C = isl_inequality_alloc(
868 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
869 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
870 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
871 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
872 }
873
874 // Collect all bounded parts of OnlyDimS.
875 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
876
877 // Create the dimensions greater than Dim again.
878 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
879 NumDimsS - Dim - 1);
880
881 // Remove the artificial upper bound parameters again.
882 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
883
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000884 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000885 return std::make_pair(UnboundedParts, BoundedParts);
886}
887
Johannes Doerfert96425c22015-08-30 21:13:53 +0000888static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
889 isl_pw_aff *L, isl_pw_aff *R) {
890 switch (Pred) {
891 case ICmpInst::ICMP_EQ:
892 return isl_pw_aff_eq_set(L, R);
893 case ICmpInst::ICMP_NE:
894 return isl_pw_aff_ne_set(L, R);
895 case ICmpInst::ICMP_SLT:
896 return isl_pw_aff_lt_set(L, R);
897 case ICmpInst::ICMP_SLE:
898 return isl_pw_aff_le_set(L, R);
899 case ICmpInst::ICMP_SGT:
900 return isl_pw_aff_gt_set(L, R);
901 case ICmpInst::ICMP_SGE:
902 return isl_pw_aff_ge_set(L, R);
903 case ICmpInst::ICMP_ULT:
904 return isl_pw_aff_lt_set(L, R);
905 case ICmpInst::ICMP_UGT:
906 return isl_pw_aff_gt_set(L, R);
907 case ICmpInst::ICMP_ULE:
908 return isl_pw_aff_le_set(L, R);
909 case ICmpInst::ICMP_UGE:
910 return isl_pw_aff_ge_set(L, R);
911 default:
912 llvm_unreachable("Non integer predicate not supported");
913 }
914}
915
916/// @brief Build the conditions sets for the branch @p BI in the @p Domain.
917///
918/// This will fill @p ConditionSets with the conditions under which control
919/// will be moved from @p BI to its successors. Hence, @p ConditionSets will
920/// have as many elements as @p BI has successors.
921static void
922buildConditionSets(Scop &S, BranchInst *BI, Loop *L, __isl_keep isl_set *Domain,
923 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
924
925 if (BI->isUnconditional()) {
926 ConditionSets.push_back(isl_set_copy(Domain));
927 return;
928 }
929
930 Value *Condition = BI->getCondition();
931
932 isl_set *ConsequenceCondSet = nullptr;
933 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
934 if (CCond->isZero())
935 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
936 else
937 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
938 } else {
939 auto *ICond = dyn_cast<ICmpInst>(Condition);
940 assert(ICond &&
941 "Condition of exiting branch was neither constant nor ICmp!");
942
943 ScalarEvolution &SE = *S.getSE();
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000944 BasicBlock *BB = BI->getParent();
Johannes Doerfert96425c22015-08-30 21:13:53 +0000945 isl_pw_aff *LHS, *RHS;
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000946 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
947 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
Johannes Doerfert96425c22015-08-30 21:13:53 +0000948 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), LHS, RHS);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000949
950 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
951 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
952 ConsequenceCondSet =
953 isl_set_set_dim_id(ConsequenceCondSet, isl_dim_set, u, DimId);
954 }
Johannes Doerfert96425c22015-08-30 21:13:53 +0000955 }
956
957 assert(ConsequenceCondSet);
958 isl_set *AlternativeCondSet =
959 isl_set_complement(isl_set_copy(ConsequenceCondSet));
960
961 ConditionSets.push_back(isl_set_coalesce(
962 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
963 ConditionSets.push_back(isl_set_coalesce(
964 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
965}
966
Johannes Doerfert32ae76e2015-09-10 13:12:02 +0000967void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000968 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000969
Tobias Grosser084d8f72012-05-29 09:29:44 +0000970 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
971
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000972 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000973 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000974}
975
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000976void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000977 isl_ctx *Ctx = Parent.getIslCtx();
978 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
979 Type *Ty = GEP->getPointerOperandType();
980 ScalarEvolution &SE = *Parent.getSE();
981
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000982 std::vector<const SCEV *> Subscripts;
983 std::vector<int> Sizes;
984
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000985 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000986
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000987 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000988 Ty = PtrTy->getElementType();
989 }
990
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000991 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000992
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000993 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000994
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000995 for (size_t i = 0; i < Sizes.size(); i++) {
996 auto Expr = Subscripts[i + IndexOffset];
997 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000998
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000999 if (!isAffineExpr(&Parent.getRegion(), Expr, SE))
1000 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001001
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001002 isl_pw_aff *AccessOffset = getPwAff(Expr);
1003 AccessOffset =
1004 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001005
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001006 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1007 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001008
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001009 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1010 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1011 OutOfBound = isl_set_params(OutOfBound);
1012 isl_set *InBound = isl_set_complement(OutOfBound);
1013 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001014
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001015 // A => B == !A or B
1016 isl_set *InBoundIfExecuted =
1017 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001018
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001019 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001020 }
1021
1022 isl_local_space_free(LSpace);
1023}
1024
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001025void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1026 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001027 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1028 deriveAssumptionsFromGEP(GEP);
1029}
1030
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001031void ScopStmt::collectSurroundingLoops() {
1032 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1033 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1034 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1035 isl_id_free(DimId);
1036 }
1037}
1038
Michael Kruse9d080092015-09-11 21:41:48 +00001039ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001040 : Parent(parent), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001041
Tobias Grosser16c44032015-07-09 07:31:45 +00001042 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001043
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001044 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001045 collectSurroundingLoops();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001046
1047 BasicBlock *EntryBB = R.getEntry();
1048 for (BasicBlock *Block : R.blocks()) {
Michael Kruse9d080092015-09-11 21:41:48 +00001049 buildAccesses(Block, Block != EntryBB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001050 deriveAssumptions(Block);
1051 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001052 if (DetectReductions)
1053 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001054}
1055
Michael Kruse9d080092015-09-11 21:41:48 +00001056ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001057 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001058
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001059 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001060
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001061 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001062 collectSurroundingLoops();
Michael Kruse9d080092015-09-11 21:41:48 +00001063 buildAccesses(BB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001064 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001065 if (DetectReductions)
1066 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001067}
1068
Johannes Doerferte58a0122014-06-27 20:31:28 +00001069/// @brief Collect loads which might form a reduction chain with @p StoreMA
1070///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001071/// Check if the stored value for @p StoreMA is a binary operator with one or
1072/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001073/// used only once (by @p StoreMA) and its load operands are also used only
1074/// once, we have found a possible reduction chain. It starts at an operand
1075/// load and includes the binary operator and @p StoreMA.
1076///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001077/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001078/// escape this block or into any other store except @p StoreMA.
1079void ScopStmt::collectCandiateReductionLoads(
1080 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1081 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1082 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001083 return;
1084
1085 // Skip if there is not one binary operator between the load and the store
1086 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001087 if (!BinOp)
1088 return;
1089
1090 // Skip if the binary operators has multiple uses
1091 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001092 return;
1093
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001094 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001095 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1096 return;
1097
Johannes Doerfert9890a052014-07-01 00:32:29 +00001098 // Skip if the binary operator is outside the current SCoP
1099 if (BinOp->getParent() != Store->getParent())
1100 return;
1101
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001102 // Skip if it is a multiplicative reduction and we disabled them
1103 if (DisableMultiplicativeReductions &&
1104 (BinOp->getOpcode() == Instruction::Mul ||
1105 BinOp->getOpcode() == Instruction::FMul))
1106 return;
1107
Johannes Doerferte58a0122014-06-27 20:31:28 +00001108 // Check the binary operator operands for a candidate load
1109 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1110 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1111 if (!PossibleLoad0 && !PossibleLoad1)
1112 return;
1113
1114 // A load is only a candidate if it cannot escape (thus has only this use)
1115 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001116 if (PossibleLoad0->getParent() == Store->getParent())
1117 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001118 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001119 if (PossibleLoad1->getParent() == Store->getParent())
1120 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001121}
1122
1123/// @brief Check for reductions in this ScopStmt
1124///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001125/// Iterate over all store memory accesses and check for valid binary reduction
1126/// like chains. For all candidates we check if they have the same base address
1127/// and there are no other accesses which overlap with them. The base address
1128/// check rules out impossible reductions candidates early. The overlap check,
1129/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001130/// guarantees that none of the intermediate results will escape during
1131/// execution of the loop nest. We basically check here that no other memory
1132/// access can access the same memory as the potential reduction.
1133void ScopStmt::checkForReductions() {
1134 SmallVector<MemoryAccess *, 2> Loads;
1135 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1136
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001137 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001138 // stores and collecting possible reduction loads.
1139 for (MemoryAccess *StoreMA : MemAccs) {
1140 if (StoreMA->isRead())
1141 continue;
1142
1143 Loads.clear();
1144 collectCandiateReductionLoads(StoreMA, Loads);
1145 for (MemoryAccess *LoadMA : Loads)
1146 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1147 }
1148
1149 // Then check each possible candidate pair.
1150 for (const auto &CandidatePair : Candidates) {
1151 bool Valid = true;
1152 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1153 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1154
1155 // Skip those with obviously unequal base addresses.
1156 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1157 isl_map_free(LoadAccs);
1158 isl_map_free(StoreAccs);
1159 continue;
1160 }
1161
1162 // And check if the remaining for overlap with other memory accesses.
1163 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1164 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1165 isl_set *AllAccs = isl_map_range(AllAccsRel);
1166
1167 for (MemoryAccess *MA : MemAccs) {
1168 if (MA == CandidatePair.first || MA == CandidatePair.second)
1169 continue;
1170
1171 isl_map *AccRel =
1172 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1173 isl_set *Accs = isl_map_range(AccRel);
1174
1175 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1176 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1177 Valid = Valid && isl_set_is_empty(OverlapAccs);
1178 isl_set_free(OverlapAccs);
1179 }
1180 }
1181
1182 isl_set_free(AllAccs);
1183 if (!Valid)
1184 continue;
1185
Johannes Doerfertf6183392014-07-01 20:52:51 +00001186 const LoadInst *Load =
1187 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1188 MemoryAccess::ReductionType RT =
1189 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1190
Johannes Doerferte58a0122014-06-27 20:31:28 +00001191 // If no overlapping access was found we mark the load and store as
1192 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001193 CandidatePair.first->markAsReductionLike(RT);
1194 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001195 }
Tobias Grosser75805372011-04-29 06:27:02 +00001196}
1197
Tobias Grosser74394f02013-01-14 22:40:23 +00001198std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001199
Tobias Grosser54839312015-04-21 11:37:25 +00001200std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001201 auto *S = getSchedule();
1202 auto Str = stringFromIslObj(S);
1203 isl_map_free(S);
1204 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001205}
1206
Tobias Grosser74394f02013-01-14 22:40:23 +00001207unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001208
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001209unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001210
Tobias Grosser75805372011-04-29 06:27:02 +00001211const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1212
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001213const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001214 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001215}
1216
Tobias Grosser74394f02013-01-14 22:40:23 +00001217isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001218
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001219__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001220
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001221__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001222 return isl_set_get_space(Domain);
1223}
1224
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001225__isl_give isl_id *ScopStmt::getDomainId() const {
1226 return isl_set_get_tuple_id(Domain);
1227}
Tobias Grossercd95b772012-08-30 11:49:38 +00001228
Tobias Grosser75805372011-04-29 06:27:02 +00001229ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001230 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001231 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001232}
1233
1234void ScopStmt::print(raw_ostream &OS) const {
1235 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001236 OS.indent(12) << "Domain :=\n";
1237
1238 if (Domain) {
1239 OS.indent(16) << getDomainStr() << ";\n";
1240 } else
1241 OS.indent(16) << "n/a\n";
1242
Tobias Grosser54839312015-04-21 11:37:25 +00001243 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001244
1245 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001246 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001247 } else
1248 OS.indent(16) << "n/a\n";
1249
Tobias Grosser083d3d32014-06-28 08:59:45 +00001250 for (MemoryAccess *Access : MemAccs)
1251 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001252}
1253
1254void ScopStmt::dump() const { print(dbgs()); }
1255
1256//===----------------------------------------------------------------------===//
1257/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001258
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001259void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001260 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1261 isl_set_free(Context);
1262 Context = NewContext;
1263}
1264
Tobias Grosserabfbe632013-02-05 12:09:06 +00001265void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001266 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001267 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001268 if (ParameterIds.find(Parameter) != ParameterIds.end())
1269 continue;
1270
1271 int dimension = Parameters.size();
1272
1273 Parameters.push_back(Parameter);
1274 ParameterIds[Parameter] = dimension;
1275 }
1276}
1277
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001278__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1279 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001280
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001281 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001282 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001283
Tobias Grosser8f99c162011-11-15 11:38:55 +00001284 std::string ParameterName;
1285
1286 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1287 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001288 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001289 }
1290
1291 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001292 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001293
Tobias Grosser20532b82014-04-11 17:56:49 +00001294 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1295 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001296}
Tobias Grosser75805372011-04-29 06:27:02 +00001297
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001298isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1299 isl_set *DomainContext = isl_union_set_params(getDomains());
1300 return isl_set_intersect_params(C, DomainContext);
1301}
1302
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001303void Scop::buildBoundaryContext() {
1304 BoundaryContext = Affinator.getWrappingContext();
1305 BoundaryContext = isl_set_complement(BoundaryContext);
1306 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1307}
1308
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001309void Scop::addUserContext() {
1310 if (UserContextStr.empty())
1311 return;
1312
1313 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1314 isl_space *Space = getParamSpace();
1315 if (isl_space_dim(Space, isl_dim_param) !=
1316 isl_set_dim(UserContext, isl_dim_param)) {
1317 auto SpaceStr = isl_space_to_str(Space);
1318 errs() << "Error: the context provided in -polly-context has not the same "
1319 << "number of dimensions than the computed context. Due to this "
1320 << "mismatch, the -polly-context option is ignored. Please provide "
1321 << "the context in the parameter space: " << SpaceStr << ".\n";
1322 free(SpaceStr);
1323 isl_set_free(UserContext);
1324 isl_space_free(Space);
1325 return;
1326 }
1327
1328 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1329 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1330 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1331
1332 if (strcmp(NameContext, NameUserContext) != 0) {
1333 auto SpaceStr = isl_space_to_str(Space);
1334 errs() << "Error: the name of dimension " << i
1335 << " provided in -polly-context "
1336 << "is '" << NameUserContext << "', but the name in the computed "
1337 << "context is '" << NameContext
1338 << "'. Due to this name mismatch, "
1339 << "the -polly-context option is ignored. Please provide "
1340 << "the context in the parameter space: " << SpaceStr << ".\n";
1341 free(SpaceStr);
1342 isl_set_free(UserContext);
1343 isl_space_free(Space);
1344 return;
1345 }
1346
1347 UserContext =
1348 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1349 isl_space_get_dim_id(Space, isl_dim_param, i));
1350 }
1351
1352 Context = isl_set_intersect(Context, UserContext);
1353 isl_space_free(Space);
1354}
1355
Tobias Grosser6be480c2011-11-08 15:41:13 +00001356void Scop::buildContext() {
1357 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001358 Context = isl_set_universe(isl_space_copy(Space));
1359 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001360}
1361
Tobias Grosser18daaca2012-05-22 10:47:27 +00001362void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001363 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001364 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001365
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001366 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001367
Johannes Doerferte7044942015-02-24 11:58:30 +00001368 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001369 }
1370}
1371
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001372void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001373 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001374 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001375
Tobias Grosser083d3d32014-06-28 08:59:45 +00001376 for (const auto &ParamID : ParameterIds) {
1377 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001378 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001379 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001380 }
1381
1382 // Align the parameters of all data structures to the model.
1383 Context = isl_set_align_params(Context, Space);
1384
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001385 for (ScopStmt &Stmt : *this)
1386 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001387}
1388
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001389static __isl_give isl_set *
1390simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1391 const Scop &S) {
1392 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1393 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1394 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1395 return AssumptionContext;
1396}
1397
1398void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001399 // The parameter constraints of the iteration domains give us a set of
1400 // constraints that need to hold for all cases where at least a single
1401 // statement iteration is executed in the whole scop. We now simplify the
1402 // assumed context under the assumption that such constraints hold and at
1403 // least a single statement iteration is executed. For cases where no
1404 // statement instances are executed, the assumptions we have taken about
1405 // the executed code do not matter and can be changed.
1406 //
1407 // WARNING: This only holds if the assumptions we have taken do not reduce
1408 // the set of statement instances that are executed. Otherwise we
1409 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001410 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001411 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001412 // performed. In such a case, modifying the run-time conditions and
1413 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001414 // to not be executed.
1415 //
1416 // Example:
1417 //
1418 // When delinearizing the following code:
1419 //
1420 // for (long i = 0; i < 100; i++)
1421 // for (long j = 0; j < m; j++)
1422 // A[i+p][j] = 1.0;
1423 //
1424 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001425 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001426 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001427 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1428 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001429}
1430
Johannes Doerfertb164c792014-09-18 11:17:17 +00001431/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001432static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001433 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1434 isl_pw_multi_aff *MinPMA, *MaxPMA;
1435 isl_pw_aff *LastDimAff;
1436 isl_aff *OneAff;
1437 unsigned Pos;
1438
Johannes Doerfert9143d672014-09-27 11:02:39 +00001439 // Restrict the number of parameters involved in the access as the lexmin/
1440 // lexmax computation will take too long if this number is high.
1441 //
1442 // Experiments with a simple test case using an i7 4800MQ:
1443 //
1444 // #Parameters involved | Time (in sec)
1445 // 6 | 0.01
1446 // 7 | 0.04
1447 // 8 | 0.12
1448 // 9 | 0.40
1449 // 10 | 1.54
1450 // 11 | 6.78
1451 // 12 | 30.38
1452 //
1453 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1454 unsigned InvolvedParams = 0;
1455 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1456 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1457 InvolvedParams++;
1458
1459 if (InvolvedParams > RunTimeChecksMaxParameters) {
1460 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001461 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001462 }
1463 }
1464
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001465 Set = isl_set_remove_divs(Set);
1466
Johannes Doerfertb164c792014-09-18 11:17:17 +00001467 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1468 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1469
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001470 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1471 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1472
Johannes Doerfertb164c792014-09-18 11:17:17 +00001473 // Adjust the last dimension of the maximal access by one as we want to
1474 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1475 // we test during code generation might now point after the end of the
1476 // allocated array but we will never dereference it anyway.
1477 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1478 "Assumed at least one output dimension");
1479 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1480 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1481 OneAff = isl_aff_zero_on_domain(
1482 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1483 OneAff = isl_aff_add_constant_si(OneAff, 1);
1484 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1485 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1486
1487 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1488
1489 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001490 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001491}
1492
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001493static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1494 isl_set *Domain = MA->getStatement()->getDomain();
1495 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1496 return isl_set_reset_tuple_id(Domain);
1497}
1498
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001499/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1500static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001501 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001502 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001503
1504 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1505 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001506 Locations = isl_union_set_coalesce(Locations);
1507 Locations = isl_union_set_detect_equalities(Locations);
1508 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001509 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001510 isl_union_set_free(Locations);
1511 return Valid;
1512}
1513
Johannes Doerfert96425c22015-08-30 21:13:53 +00001514/// @brief Helper to treat non-affine regions and basic blocks the same.
1515///
1516///{
1517
1518/// @brief Return the block that is the representing block for @p RN.
1519static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1520 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1521 : RN->getNodeAs<BasicBlock>();
1522}
1523
1524/// @brief Return the @p idx'th block that is executed after @p RN.
1525static inline BasicBlock *getRegionNodeSuccessor(RegionNode *RN, BranchInst *BI,
1526 unsigned idx) {
1527 if (RN->isSubRegion()) {
1528 assert(idx == 0);
1529 return RN->getNodeAs<Region>()->getExit();
1530 }
1531 return BI->getSuccessor(idx);
1532}
1533
1534/// @brief Return the smallest loop surrounding @p RN.
1535static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1536 if (!RN->isSubRegion())
1537 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1538
1539 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1540 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1541 while (L && NonAffineSubRegion->contains(L))
1542 L = L->getParentLoop();
1543 return L;
1544}
1545
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001546static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1547 if (!RN->isSubRegion())
1548 return 1;
1549
1550 unsigned NumBlocks = 0;
1551 Region *R = RN->getNodeAs<Region>();
1552 for (auto BB : R->blocks()) {
1553 (void)BB;
1554 NumBlocks++;
1555 }
1556 return NumBlocks;
1557}
1558
Johannes Doerfert96425c22015-08-30 21:13:53 +00001559///}
1560
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001561static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1562 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001563 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001564 isl_id *DimId =
1565 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1566 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1567}
1568
Johannes Doerfert96425c22015-08-30 21:13:53 +00001569isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1570 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1571 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001572 return getDomainConditions(BB);
1573}
1574
1575isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1576 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001577 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001578}
1579
1580void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1581 DominatorTree &DT) {
1582
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001583 auto *EntryBB = R->getEntry();
1584 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1585 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001586
1587 Loop *L = LI.getLoopFor(EntryBB);
1588 while (LD-- >= 0) {
1589 S = addDomainDimId(S, LD + 1, L);
1590 L = L->getParentLoop();
1591 }
1592
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001593 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001594
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001595 if (SD.isNonAffineSubRegion(R, R))
1596 return;
1597
Johannes Doerfert96425c22015-08-30 21:13:53 +00001598 buildDomainsWithBranchConstraints(R, LI, SD, DT);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001599 propagateDomainConstraints(R, LI, SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001600}
1601
1602void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1603 ScopDetection &SD,
1604 DominatorTree &DT) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001605 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001606
1607 // To create the domain for each block in R we iterate over all blocks and
1608 // subregions in R and propagate the conditions under which the current region
1609 // element is executed. To this end we iterate in reverse post order over R as
1610 // it ensures that we first visit all predecessors of a region node (either a
1611 // basic block or a subregion) before we visit the region node itself.
1612 // Initially, only the domain for the SCoP region entry block is set and from
1613 // there we propagate the current domain to all successors, however we add the
1614 // condition that the successor is actually executed next.
1615 // As we are only interested in non-loop carried constraints here we can
1616 // simply skip loop back edges.
1617
1618 ReversePostOrderTraversal<Region *> RTraversal(R);
1619 for (auto *RN : RTraversal) {
1620
1621 // Recurse for affine subregions but go on for basic blocks and non-affine
1622 // subregions.
1623 if (RN->isSubRegion()) {
1624 Region *SubRegion = RN->getNodeAs<Region>();
1625 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1626 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1627 continue;
1628 }
1629 }
1630
1631 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001632 TerminatorInst *TI = BB->getTerminator();
1633
1634 // Unreachable instructions do not have successors so we can skip them.
1635 if (isa<UnreachableInst>(TI)) {
1636 // Assume unreachables only in error blocks.
1637 assert(isErrorBlock(*BB));
1638 continue;
1639 }
1640
Johannes Doerfert96425c22015-08-30 21:13:53 +00001641 isl_set *Domain = DomainMap[BB];
1642 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1643 assert(Domain && "Due to reverse post order traversal of the region all "
1644 "predecessor of the current region node should have been "
1645 "visited and a domain for this region node should have "
1646 "been set.");
1647
1648 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1649 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1650
1651 // Build the condition sets for the successor nodes of the current region
1652 // node. If it is a non-affine subregion we will always execute the single
1653 // exit node, hence the single entry node domain is the condition set. For
1654 // basic blocks we use the helper function buildConditionSets.
1655 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001656 BranchInst *BI = cast<BranchInst>(TI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001657 if (RN->isSubRegion())
1658 ConditionSets.push_back(isl_set_copy(Domain));
1659 else
1660 buildConditionSets(*this, BI, BBLoop, Domain, ConditionSets);
1661
1662 // Now iterate over the successors and set their initial domain based on
1663 // their condition set. We skip back edges here and have to be careful when
1664 // we leave a loop not to keep constraints over a dimension that doesn't
1665 // exist anymore.
1666 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
1667 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, BI, u);
1668 isl_set *CondSet = ConditionSets[u];
1669
1670 // Skip back edges.
1671 if (DT.dominates(SuccBB, BB)) {
1672 isl_set_free(CondSet);
1673 continue;
1674 }
1675
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001676 // Do not adjust the number of dimensions if we enter a boxed loop or are
1677 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001678 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001679 Region *SuccRegion = RI.getRegionFor(SuccBB);
1680 if (BBLoop != SuccBBLoop && !RN->isSubRegion() &&
1681 !(SD.isNonAffineSubRegion(SuccRegion, &getRegion()) &&
1682 SuccRegion->contains(SuccBBLoop))) {
1683
1684 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1685 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1686 // and enter a new one we need to drop the old constraints.
1687 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001688 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001689 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001690 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1691 isl_set_n_dim(CondSet) - LoopDepthDiff,
1692 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001693 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001694 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001695 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001696 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001697 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001698 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001699 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1700 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001701 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001702 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001703 }
1704
1705 // Set the domain for the successor or merge it with an existing domain in
1706 // case there are multiple paths (without loop back edges) to the
1707 // successor block.
1708 isl_set *&SuccDomain = DomainMap[SuccBB];
1709 if (!SuccDomain)
1710 SuccDomain = CondSet;
1711 else
1712 SuccDomain = isl_set_union(SuccDomain, CondSet);
1713
1714 SuccDomain = isl_set_coalesce(SuccDomain);
1715 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1716 << "\n");
1717 }
1718 }
1719}
1720
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001721/// @brief Return the domain for @p BB wrt @p DomainMap.
1722///
1723/// This helper function will lookup @p BB in @p DomainMap but also handle the
1724/// case where @p BB is contained in a non-affine subregion using the region
1725/// tree obtained by @p RI.
1726static __isl_give isl_set *
1727getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1728 RegionInfo &RI) {
1729 auto DIt = DomainMap.find(BB);
1730 if (DIt != DomainMap.end())
1731 return isl_set_copy(DIt->getSecond());
1732
1733 Region *R = RI.getRegionFor(BB);
1734 while (R->getEntry() == BB)
1735 R = R->getParent();
1736 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1737}
1738
Johannes Doerferte114dc02015-09-14 11:15:58 +00001739static bool containsErrorBlock(RegionNode *RN) {
1740 if (!RN->isSubRegion())
1741 return isErrorBlock(*RN->getNodeAs<BasicBlock>());
1742 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
1743 if (isErrorBlock(*BB))
1744 return true;
1745 return false;
1746}
1747
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001748void Scop::propagateDomainConstraints(Region *R, LoopInfo &LI,
1749 ScopDetection &SD, DominatorTree &DT) {
1750 // Iterate over the region R and propagate the domain constrains from the
1751 // predecessors to the current node. In contrast to the
1752 // buildDomainsWithBranchConstraints function, this one will pull the domain
1753 // information from the predecessors instead of pushing it to the successors.
1754 // Additionally, we assume the domains to be already present in the domain
1755 // map here. However, we iterate again in reverse post order so we know all
1756 // predecessors have been visited before a block or non-affine subregion is
1757 // visited.
1758
1759 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1760 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1761
1762 ReversePostOrderTraversal<Region *> RTraversal(R);
1763 for (auto *RN : RTraversal) {
1764
1765 // Recurse for affine subregions but go on for basic blocks and non-affine
1766 // subregions.
1767 if (RN->isSubRegion()) {
1768 Region *SubRegion = RN->getNodeAs<Region>();
1769 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1770 propagateDomainConstraints(SubRegion, LI, SD, DT);
1771 continue;
1772 }
1773 }
1774
1775 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1776 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1777 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1778
1779 isl_set *&Domain = DomainMap[BB];
1780 assert(Domain && "Due to reverse post order traversal of the region all "
1781 "predecessor of the current region node should have been "
1782 "visited and a domain for this region node should have "
1783 "been set.");
1784
1785 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1786 for (auto *PredBB : predecessors(BB)) {
1787
1788 // Skip backedges
1789 if (DT.dominates(BB, PredBB))
1790 continue;
1791
1792 isl_set *PredBBDom = nullptr;
1793
1794 // Handle the SCoP entry block with its outside predecessors.
1795 if (!getRegion().contains(PredBB))
1796 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1797
1798 if (!PredBBDom) {
1799 // Determine the loop depth of the predecessor and adjust its domain to
1800 // the domain of the current block. This can mean we have to:
1801 // o) Drop a dimension if this block is the exit of a loop, not the
1802 // header of a new loop and the predecessor was part of the loop.
1803 // o) Add an unconstrainted new dimension if this block is the header
1804 // of a loop and the predecessor is not part of it.
1805 // o) Drop the information about the innermost loop dimension when the
1806 // predecessor and the current block are surrounded by different
1807 // loops in the same depth.
1808 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
1809 Loop *PredBBLoop = LI.getLoopFor(PredBB);
1810 while (BoxedLoops.count(PredBBLoop))
1811 PredBBLoop = PredBBLoop->getParentLoop();
1812
1813 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001814 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001815 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001816 PredBBDom = isl_set_project_out(
1817 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
1818 LoopDepthDiff);
1819 else if (PredBBLoopDepth < BBLoopDepth) {
1820 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001821 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001822 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
1823 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001824 PredBBDom = isl_set_drop_constraints_involving_dims(
1825 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001826 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001827 }
1828
1829 PredDom = isl_set_union(PredDom, PredBBDom);
1830 }
1831
1832 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00001833 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001834
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001835 if (BBLoop && BBLoop->getHeader() == BB)
1836 addLoopBoundsToHeaderDomain(BBLoop, LI);
1837
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001838 // Add assumptions for error blocks.
Johannes Doerferte114dc02015-09-14 11:15:58 +00001839 if (containsErrorBlock(RN)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001840 IsOptimized = true;
1841 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
1842 addAssumption(isl_set_complement(DomPar));
1843 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001844 }
1845}
1846
1847/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
1848/// is incremented by one and all other dimensions are equal, e.g.,
1849/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
1850/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
1851static __isl_give isl_map *
1852createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
1853 auto *MapSpace = isl_space_map_from_set(SetSpace);
1854 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
1855 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
1856 if (u != Dim)
1857 NextIterationMap =
1858 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
1859 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
1860 C = isl_constraint_set_constant_si(C, 1);
1861 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
1862 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
1863 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
1864 return NextIterationMap;
1865}
1866
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001867void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
1868 int LoopDepth = getRelativeLoopDepth(L);
1869 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001870
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001871 BasicBlock *HeaderBB = L->getHeader();
1872 assert(DomainMap.count(HeaderBB));
1873 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001874
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001875 isl_map *NextIterationMap =
1876 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001877
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001878 isl_set *UnionBackedgeCondition =
1879 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001880
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001881 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
1882 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001883
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001884 for (BasicBlock *LatchBB : LatchBlocks) {
1885 assert(DomainMap.count(LatchBB));
1886 isl_set *LatchBBDom = DomainMap[LatchBB];
1887 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001888
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001889 BranchInst *BI = cast<BranchInst>(LatchBB->getTerminator());
1890 if (BI->isUnconditional())
1891 BackedgeCondition = isl_set_copy(LatchBBDom);
1892 else {
1893 SmallVector<isl_set *, 2> ConditionSets;
1894 int idx = BI->getSuccessor(0) != HeaderBB;
1895 buildConditionSets(*this, BI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001896
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001897 // Free the non back edge condition set as we do not need it.
1898 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001899
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001900 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00001901 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001902
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001903 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
1904 assert(LatchLoopDepth >= LoopDepth);
1905 BackedgeCondition =
1906 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
1907 LatchLoopDepth - LoopDepth);
1908 UnionBackedgeCondition =
1909 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001910 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001911
1912 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
1913 for (int i = 0; i < LoopDepth; i++)
1914 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
1915
1916 isl_set *UnionBackedgeConditionComplement =
1917 isl_set_complement(UnionBackedgeCondition);
1918 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
1919 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
1920 UnionBackedgeConditionComplement =
1921 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
1922 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
1923 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
1924
1925 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
1926 HeaderBBDom = Parts.second;
1927
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00001928 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
1929 // the bounded assumptions to the context as they are already implied by the
1930 // <nsw> tag.
1931 if (Affinator.hasNSWAddRecForLoop(L)) {
1932 isl_set_free(Parts.first);
1933 return;
1934 }
1935
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001936 isl_set *UnboundedCtx = isl_set_params(Parts.first);
1937 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00001938 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001939}
1940
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001941void Scop::buildAliasChecks(AliasAnalysis &AA) {
1942 if (!PollyUseRuntimeAliasChecks)
1943 return;
1944
1945 if (buildAliasGroups(AA))
1946 return;
1947
1948 // If a problem occurs while building the alias groups we need to delete
1949 // this SCoP and pretend it wasn't valid in the first place. To this end
1950 // we make the assumed context infeasible.
1951 addAssumption(isl_set_empty(getParamSpace()));
1952
1953 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1954 << " could not be created as the number of parameters involved "
1955 "is too high. The SCoP will be "
1956 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1957 "the maximal number of parameters but be advised that the "
1958 "compile time might increase exponentially.\n\n");
1959}
1960
Johannes Doerfert9143d672014-09-27 11:02:39 +00001961bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001962 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001963 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001964 // for all memory accesses inside the SCoP.
1965 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001966 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001967 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001968 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001969 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001970 // if their access domains intersect, otherwise they are in different
1971 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001972 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001973 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001974 // and maximal accesses to each array of a group in read only and non
1975 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001976 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1977
1978 AliasSetTracker AST(AA);
1979
1980 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001981 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001982 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001983
1984 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001985 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001986 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1987 isl_set_free(StmtDomain);
1988 if (StmtDomainEmpty)
1989 continue;
1990
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001991 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001992 if (MA->isScalar())
1993 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001994 if (!MA->isRead())
1995 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001996 Instruction *Acc = MA->getAccessInstruction();
1997 PtrToAcc[getPointerOperand(*Acc)] = MA;
1998 AST.add(Acc);
1999 }
2000 }
2001
2002 SmallVector<AliasGroupTy, 4> AliasGroups;
2003 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002004 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002005 continue;
2006 AliasGroupTy AG;
2007 for (auto PR : AS)
2008 AG.push_back(PtrToAcc[PR.getValue()]);
2009 assert(AG.size() > 1 &&
2010 "Alias groups should contain at least two accesses");
2011 AliasGroups.push_back(std::move(AG));
2012 }
2013
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002014 // Split the alias groups based on their domain.
2015 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2016 AliasGroupTy NewAG;
2017 AliasGroupTy &AG = AliasGroups[u];
2018 AliasGroupTy::iterator AGI = AG.begin();
2019 isl_set *AGDomain = getAccessDomain(*AGI);
2020 while (AGI != AG.end()) {
2021 MemoryAccess *MA = *AGI;
2022 isl_set *MADomain = getAccessDomain(MA);
2023 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2024 NewAG.push_back(MA);
2025 AGI = AG.erase(AGI);
2026 isl_set_free(MADomain);
2027 } else {
2028 AGDomain = isl_set_union(AGDomain, MADomain);
2029 AGI++;
2030 }
2031 }
2032 if (NewAG.size() > 1)
2033 AliasGroups.push_back(std::move(NewAG));
2034 isl_set_free(AGDomain);
2035 }
2036
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002037 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002038 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2039 for (AliasGroupTy &AG : AliasGroups) {
2040 NonReadOnlyBaseValues.clear();
2041 ReadOnlyPairs.clear();
2042
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002043 if (AG.size() < 2) {
2044 AG.clear();
2045 continue;
2046 }
2047
Johannes Doerfert13771732014-10-01 12:40:46 +00002048 for (auto II = AG.begin(); II != AG.end();) {
2049 Value *BaseAddr = (*II)->getBaseAddr();
2050 if (HasWriteAccess.count(BaseAddr)) {
2051 NonReadOnlyBaseValues.insert(BaseAddr);
2052 II++;
2053 } else {
2054 ReadOnlyPairs[BaseAddr].insert(*II);
2055 II = AG.erase(II);
2056 }
2057 }
2058
2059 // If we don't have read only pointers check if there are at least two
2060 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002061 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002062 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002063 continue;
2064 }
2065
2066 // If we don't have non read only pointers clear the alias group.
2067 if (NonReadOnlyBaseValues.empty()) {
2068 AG.clear();
2069 continue;
2070 }
2071
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002072 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002073 MinMaxAliasGroups.emplace_back();
2074 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2075 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2076 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2077 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002078
2079 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002080
2081 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002082 for (MemoryAccess *MA : AG)
2083 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002084
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002085 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2086 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002087
2088 // Bail out if the number of values we need to compare is too large.
2089 // This is important as the number of comparisions grows quadratically with
2090 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002091 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2092 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002093 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002094
2095 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002096 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002097 Accesses = isl_union_map_empty(getParamSpace());
2098
2099 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2100 for (MemoryAccess *MA : ReadOnlyPair.second)
2101 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2102
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002103 Valid =
2104 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002105
2106 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002107 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002108 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002109
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002110 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002111}
2112
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002113static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2114 Loop *L = LI.getLoopFor(R.getEntry());
2115 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2116}
2117
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002118static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2119 ScopDetection &SD) {
2120
2121 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2122
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002123 unsigned MinLD = INT_MAX, MaxLD = 0;
2124 for (BasicBlock *BB : R.blocks()) {
2125 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002126 if (!R.contains(L))
2127 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002128 if (BoxedLoops && BoxedLoops->count(L))
2129 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002130 unsigned LD = L->getLoopDepth();
2131 MinLD = std::min(MinLD, LD);
2132 MaxLD = std::max(MaxLD, LD);
2133 }
2134 }
2135
2136 // Handle the case that there is no loop in the SCoP first.
2137 if (MaxLD == 0)
2138 return 1;
2139
2140 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2141 assert(MaxLD >= MinLD &&
2142 "Maximal loop depth was smaller than mininaml loop depth?");
2143 return MaxLD - MinLD + 1;
2144}
2145
Michael Kruse9d080092015-09-11 21:41:48 +00002146Scop::Scop(Region &R, AccFuncMapType &AccFuncMap,
2147 ScalarEvolution &ScalarEvolution, DominatorTree &DT,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002148 isl_ctx *Context, unsigned MaxLoopDepth)
Michael Kruse9d080092015-09-11 21:41:48 +00002149 : DT(DT), SE(&ScalarEvolution), R(R), AccFuncMap(AccFuncMap),
2150 IsOptimized(false), HasSingleExitEdge(R.getExitingBlock()),
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002151 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this),
2152 BoundaryContext(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002153
Michael Kruse9d080092015-09-11 21:41:48 +00002154void Scop::init(LoopInfo &LI, ScopDetection &SD, AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002155 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00002156
Johannes Doerfert96425c22015-08-30 21:13:53 +00002157 buildDomains(&R, LI, SD, DT);
2158
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002159 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Tobias Grosser75805372011-04-29 06:27:02 +00002160
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002161 Loop *L = getLoopSurroundingRegion(R, LI);
2162 LoopSchedules[L];
Michael Kruse9d080092015-09-11 21:41:48 +00002163 buildSchedule(&R, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002164 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002165
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002166 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002167 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002168 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002169 buildBoundaryContext();
2170 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002171 buildAliasChecks(AA);
Tobias Grosser75805372011-04-29 06:27:02 +00002172}
2173
2174Scop::~Scop() {
2175 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002176 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002177 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002178 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002179
Johannes Doerfert96425c22015-08-30 21:13:53 +00002180 for (auto It : DomainMap)
2181 isl_set_free(It.second);
2182
Johannes Doerfertb164c792014-09-18 11:17:17 +00002183 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002184 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002185 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002186 isl_pw_multi_aff_free(MMA.first);
2187 isl_pw_multi_aff_free(MMA.second);
2188 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002189 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002190 isl_pw_multi_aff_free(MMA.first);
2191 isl_pw_multi_aff_free(MMA.second);
2192 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002193 }
Tobias Grosser75805372011-04-29 06:27:02 +00002194}
2195
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002196const ScopArrayInfo *
2197Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002198 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002199 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002200 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002201 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2202 this));
Tobias Grosserab671442015-05-23 05:58:27 +00002203 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002204}
2205
Tobias Grosser92245222015-07-28 14:53:44 +00002206const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2207 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002208 assert(SAI && "No ScopArrayInfo available for this base pointer");
2209 return SAI;
2210}
2211
Tobias Grosser74394f02013-01-14 22:40:23 +00002212std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002213std::string Scop::getAssumedContextStr() const {
2214 return stringFromIslObj(AssumedContext);
2215}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002216std::string Scop::getBoundaryContextStr() const {
2217 return stringFromIslObj(BoundaryContext);
2218}
Tobias Grosser75805372011-04-29 06:27:02 +00002219
2220std::string Scop::getNameStr() const {
2221 std::string ExitName, EntryName;
2222 raw_string_ostream ExitStr(ExitName);
2223 raw_string_ostream EntryStr(EntryName);
2224
Tobias Grosserf240b482014-01-09 10:42:15 +00002225 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002226 EntryStr.str();
2227
2228 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002229 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002230 ExitStr.str();
2231 } else
2232 ExitName = "FunctionExit";
2233
2234 return EntryName + "---" + ExitName;
2235}
2236
Tobias Grosser74394f02013-01-14 22:40:23 +00002237__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002238__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002239 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002240}
2241
Tobias Grossere86109f2013-10-29 21:05:49 +00002242__isl_give isl_set *Scop::getAssumedContext() const {
2243 return isl_set_copy(AssumedContext);
2244}
2245
Johannes Doerfert43788c52015-08-20 05:58:56 +00002246__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2247 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002248 RuntimeCheckContext =
2249 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2250 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002251 return RuntimeCheckContext;
2252}
2253
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002254bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002255 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002256 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002257 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2258 isl_set_free(RuntimeCheckContext);
2259 return IsFeasible;
2260}
2261
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002262void Scop::addAssumption(__isl_take isl_set *Set) {
2263 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002264 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002265}
2266
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002267__isl_give isl_set *Scop::getBoundaryContext() const {
2268 return isl_set_copy(BoundaryContext);
2269}
2270
Tobias Grosser75805372011-04-29 06:27:02 +00002271void Scop::printContext(raw_ostream &OS) const {
2272 OS << "Context:\n";
2273
2274 if (!Context) {
2275 OS.indent(4) << "n/a\n\n";
2276 return;
2277 }
2278
2279 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002280
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002281 OS.indent(4) << "Assumed Context:\n";
2282 if (!AssumedContext) {
2283 OS.indent(4) << "n/a\n\n";
2284 return;
2285 }
2286
2287 OS.indent(4) << getAssumedContextStr() << "\n";
2288
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002289 OS.indent(4) << "Boundary Context:\n";
2290 if (!BoundaryContext) {
2291 OS.indent(4) << "n/a\n\n";
2292 return;
2293 }
2294
2295 OS.indent(4) << getBoundaryContextStr() << "\n";
2296
Tobias Grosser083d3d32014-06-28 08:59:45 +00002297 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002298 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002299 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2300 }
Tobias Grosser75805372011-04-29 06:27:02 +00002301}
2302
Johannes Doerfertb164c792014-09-18 11:17:17 +00002303void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002304 int noOfGroups = 0;
2305 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002306 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002307 noOfGroups += 1;
2308 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002309 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002310 }
2311
Tobias Grosserbb853c22015-07-25 12:31:03 +00002312 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002313 if (MinMaxAliasGroups.empty()) {
2314 OS.indent(8) << "n/a\n";
2315 return;
2316 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002317
Tobias Grosserbb853c22015-07-25 12:31:03 +00002318 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002319
2320 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002321 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002322 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002323 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002324 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2325 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002326 }
2327 OS << " ]]\n";
2328 }
2329
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002330 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002331 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002332 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002333 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002334 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2335 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002336 }
2337 OS << " ]]\n";
2338 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002339 }
2340}
2341
Tobias Grosser75805372011-04-29 06:27:02 +00002342void Scop::printStatements(raw_ostream &OS) const {
2343 OS << "Statements {\n";
2344
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002345 for (const ScopStmt &Stmt : *this)
2346 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002347
2348 OS.indent(4) << "}\n";
2349}
2350
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002351void Scop::printArrayInfo(raw_ostream &OS) const {
2352 OS << "Arrays {\n";
2353
Tobias Grosserab671442015-05-23 05:58:27 +00002354 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002355 Array.second->print(OS);
2356
2357 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002358
2359 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2360
2361 for (auto &Array : arrays())
2362 Array.second->print(OS, /* SizeAsPwAff */ true);
2363
2364 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002365}
2366
Tobias Grosser75805372011-04-29 06:27:02 +00002367void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002368 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2369 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002370 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002371 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002372 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002373 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002374 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002375 printStatements(OS.indent(4));
2376}
2377
2378void Scop::dump() const { print(dbgs()); }
2379
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002380isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002381
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002382__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2383 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002384}
2385
Tobias Grosser808cd692015-07-14 09:33:13 +00002386__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002387 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002388
Tobias Grosser808cd692015-07-14 09:33:13 +00002389 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002390 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002391
2392 return Domain;
2393}
2394
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002395__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002396 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002397
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002398 for (ScopStmt &Stmt : *this) {
2399 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002400 if (!MA->isMustWrite())
2401 continue;
2402
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002403 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002404 isl_map *AccessDomain = MA->getAccessRelation();
2405 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2406 Write = isl_union_map_add_map(Write, AccessDomain);
2407 }
2408 }
2409 return isl_union_map_coalesce(Write);
2410}
2411
2412__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002413 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002414
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002415 for (ScopStmt &Stmt : *this) {
2416 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002417 if (!MA->isMayWrite())
2418 continue;
2419
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002420 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002421 isl_map *AccessDomain = MA->getAccessRelation();
2422 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2423 Write = isl_union_map_add_map(Write, AccessDomain);
2424 }
2425 }
2426 return isl_union_map_coalesce(Write);
2427}
2428
Tobias Grosser37eb4222014-02-20 21:43:54 +00002429__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002430 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002431
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002432 for (ScopStmt &Stmt : *this) {
2433 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002434 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002435 continue;
2436
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002437 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002438 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002439 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2440 Write = isl_union_map_add_map(Write, AccessDomain);
2441 }
2442 }
2443 return isl_union_map_coalesce(Write);
2444}
2445
2446__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002447 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002448
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002449 for (ScopStmt &Stmt : *this) {
2450 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002451 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002452 continue;
2453
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002454 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002455 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002456
2457 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2458 Read = isl_union_map_add_map(Read, AccessDomain);
2459 }
2460 }
2461 return isl_union_map_coalesce(Read);
2462}
2463
Tobias Grosser808cd692015-07-14 09:33:13 +00002464__isl_give isl_union_map *Scop::getSchedule() const {
2465 auto Tree = getScheduleTree();
2466 auto S = isl_schedule_get_map(Tree);
2467 isl_schedule_free(Tree);
2468 return S;
2469}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002470
Tobias Grosser808cd692015-07-14 09:33:13 +00002471__isl_give isl_schedule *Scop::getScheduleTree() const {
2472 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2473 getDomains());
2474}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002475
Tobias Grosser808cd692015-07-14 09:33:13 +00002476void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2477 auto *S = isl_schedule_from_domain(getDomains());
2478 S = isl_schedule_insert_partial_schedule(
2479 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2480 isl_schedule_free(Schedule);
2481 Schedule = S;
2482}
2483
2484void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2485 isl_schedule_free(Schedule);
2486 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002487}
2488
2489bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2490 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002491 for (ScopStmt &Stmt : *this) {
2492 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002493 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2494 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2495
2496 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2497 isl_union_set_free(StmtDomain);
2498 isl_union_set_free(NewStmtDomain);
2499 continue;
2500 }
2501
2502 Changed = true;
2503
2504 isl_union_set_free(StmtDomain);
2505 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2506
2507 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002508 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002509 isl_union_set_free(NewStmtDomain);
2510 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002511 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002512 }
2513 isl_union_set_free(Domain);
2514 return Changed;
2515}
2516
Tobias Grosser75805372011-04-29 06:27:02 +00002517ScalarEvolution *Scop::getSE() const { return SE; }
2518
Michael Kruse9d080092015-09-11 21:41:48 +00002519bool Scop::isTrivialBB(BasicBlock *BB) {
2520 if (getAccessFunctions(BB) && !isErrorBlock(*BB))
Tobias Grosser75805372011-04-29 06:27:02 +00002521 return false;
2522
2523 return true;
2524}
2525
Tobias Grosser808cd692015-07-14 09:33:13 +00002526struct MapToDimensionDataTy {
2527 int N;
2528 isl_union_pw_multi_aff *Res;
2529};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002530
Tobias Grosser808cd692015-07-14 09:33:13 +00002531// @brief Create a function that maps the elements of 'Set' to its N-th
2532// dimension.
2533//
2534// The result is added to 'User->Res'.
2535//
2536// @param Set The input set.
2537// @param N The dimension to map to.
2538//
2539// @returns Zero if no error occurred, non-zero otherwise.
2540static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2541 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2542 int Dim;
2543 isl_space *Space;
2544 isl_pw_multi_aff *PMA;
2545
2546 Dim = isl_set_dim(Set, isl_dim_set);
2547 Space = isl_set_get_space(Set);
2548 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2549 Dim - Data->N);
2550 if (Data->N > 1)
2551 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2552 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2553
2554 isl_set_free(Set);
2555
2556 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002557}
2558
Tobias Grosser808cd692015-07-14 09:33:13 +00002559// @brief Create a function that maps the elements of Domain to their Nth
2560// dimension.
2561//
2562// @param Domain The set of elements to map.
2563// @param N The dimension to map to.
2564static __isl_give isl_multi_union_pw_aff *
2565mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002566 if (N <= 0 || isl_union_set_is_empty(Domain)) {
2567 isl_union_set_free(Domain);
2568 return nullptr;
2569 }
2570
Tobias Grosser808cd692015-07-14 09:33:13 +00002571 struct MapToDimensionDataTy Data;
2572 isl_space *Space;
2573
2574 Space = isl_union_set_get_space(Domain);
2575 Data.N = N;
2576 Data.Res = isl_union_pw_multi_aff_empty(Space);
2577 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2578 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2579
2580 isl_union_set_free(Domain);
2581 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2582}
2583
Michael Kruse9d080092015-09-11 21:41:48 +00002584ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002585 ScopStmt *Stmt;
2586 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00002587 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00002588 Stmt = &Stmts.back();
2589 StmtMap[BB] = Stmt;
2590 } else {
2591 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00002592 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00002593 Stmt = &Stmts.back();
2594 for (BasicBlock *BB : R->blocks())
2595 StmtMap[BB] = Stmt;
2596 }
2597 return Stmt;
2598}
2599
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002600void Scop::buildSchedule(
Michael Kruse9d080092015-09-11 21:41:48 +00002601 Region *R, LoopInfo &LI, ScopDetection &SD,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002602 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00002603
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002604 if (SD.isNonAffineSubRegion(R, &getRegion())) {
2605 auto *Stmt = addScopStmt(nullptr, R);
2606 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2607 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2608 auto &LSchedulePair = LoopSchedules[nullptr];
2609 LSchedulePair.first = StmtSchedule;
2610 return;
2611 }
2612
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002613 ReversePostOrderTraversal<Region *> RTraversal(R);
2614 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00002615
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002616 if (RN->isSubRegion()) {
2617 Region *SubRegion = RN->getNodeAs<Region>();
2618 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Michael Kruse9d080092015-09-11 21:41:48 +00002619 buildSchedule(SubRegion, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002620 continue;
2621 }
Tobias Grosser75805372011-04-29 06:27:02 +00002622 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002623
2624 Loop *L = getRegionNodeLoop(RN, LI);
2625 int LD = getRelativeLoopDepth(L);
2626 auto &LSchedulePair = LoopSchedules[L];
2627 LSchedulePair.second += getNumBlocksInRegionNode(RN);
2628
2629 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse9d080092015-09-11 21:41:48 +00002630 if (RN->isSubRegion() || !isTrivialBB(BB)) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002631
2632 ScopStmt *Stmt;
2633 if (RN->isSubRegion())
Michael Kruse9d080092015-09-11 21:41:48 +00002634 Stmt = addScopStmt(nullptr, RN->getNodeAs<Region>());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002635 else
Michael Kruse9d080092015-09-11 21:41:48 +00002636 Stmt = addScopStmt(BB, nullptr);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002637
2638 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2639 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2640 LSchedulePair.first =
2641 combineInSequence(LSchedulePair.first, StmtSchedule);
2642 }
2643
2644 unsigned NumVisited = LSchedulePair.second;
2645 while (L && NumVisited == L->getNumBlocks()) {
2646 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
2647 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
2648 LSchedulePair.first =
2649 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
2650
2651 auto *PL = L->getParentLoop();
2652 assert(LoopSchedules.count(PL));
2653 auto &PSchedulePair = LoopSchedules[PL];
2654 PSchedulePair.first =
2655 combineInSequence(PSchedulePair.first, LSchedulePair.first);
2656 PSchedulePair.second += NumVisited;
2657
2658 L = PL;
2659 NumVisited = PSchedulePair.second;
2660 }
Tobias Grosser808cd692015-07-14 09:33:13 +00002661 }
Tobias Grosser75805372011-04-29 06:27:02 +00002662}
2663
Johannes Doerfert7c494212014-10-31 23:13:39 +00002664ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002665 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002666 if (StmtMapIt == StmtMap.end())
2667 return nullptr;
2668 return StmtMapIt->second;
2669}
2670
Michael Kruse9d080092015-09-11 21:41:48 +00002671void Scop::printIRAccesses(raw_ostream &OS, ScalarEvolution *SE,
2672 LoopInfo *LI) const {
Michael Kruse7bf39442015-09-10 12:46:52 +00002673 OS << "Scop: " << R.getNameStr() << "\n";
2674
Michael Kruse9d080092015-09-11 21:41:48 +00002675 printIRAccessesDetail(OS, SE, LI, &R, 0);
Michael Kruse7bf39442015-09-10 12:46:52 +00002676}
2677
Michael Kruse9d080092015-09-11 21:41:48 +00002678void Scop::printIRAccessesDetail(raw_ostream &OS, ScalarEvolution *SE,
2679 LoopInfo *LI, const Region *CurR,
2680 unsigned ind) const {
Michael Kruse7bf39442015-09-10 12:46:52 +00002681 // FIXME: Print other details rather than memory accesses.
2682 for (const auto &CurBlock : CurR->blocks()) {
2683 AccFuncMapType::const_iterator AccSetIt = AccFuncMap.find(CurBlock);
2684
2685 // Ignore trivial blocks that do not contain any memory access.
2686 if (AccSetIt == AccFuncMap.end())
2687 continue;
2688
2689 OS.indent(ind) << "BB: " << CurBlock->getName() << '\n';
2690 typedef AccFuncSetType::const_iterator access_iterator;
2691 const AccFuncSetType &AccFuncs = AccSetIt->second;
2692
2693 for (access_iterator AI = AccFuncs.begin(), AE = AccFuncs.end(); AI != AE;
2694 ++AI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00002695 AI->printIR(OS.indent(ind + 2));
Michael Kruse7bf39442015-09-10 12:46:52 +00002696 }
2697}
2698
Johannes Doerfert96425c22015-08-30 21:13:53 +00002699int Scop::getRelativeLoopDepth(const Loop *L) const {
2700 Loop *OuterLoop =
2701 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2702 if (!OuterLoop)
2703 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002704 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2705}
2706
Michael Krused868b5d2015-09-10 15:25:24 +00002707void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00002708 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002709
2710 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
2711 // true, are not modeled as ordinary PHI nodes as they are not part of the
2712 // region. However, we model the operands in the predecessor blocks that are
2713 // part of the region as regular scalar accesses.
2714
2715 // If we can synthesize a PHI we can skip it, however only if it is in
2716 // the region. If it is not it can only be in the exit block of the region.
2717 // In this case we model the operands but not the PHI itself.
2718 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
2719 return;
2720
2721 // PHI nodes are modeled as if they had been demoted prior to the SCoP
2722 // detection. Hence, the PHI is a load of a new memory location in which the
2723 // incoming value was written at the end of the incoming basic block.
2724 bool OnlyNonAffineSubRegionOperands = true;
2725 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
2726 Value *Op = PHI->getIncomingValue(u);
2727 BasicBlock *OpBB = PHI->getIncomingBlock(u);
2728
2729 // Do not build scalar dependences inside a non-affine subregion.
2730 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
2731 continue;
2732
2733 OnlyNonAffineSubRegionOperands = false;
2734
2735 if (!R.contains(OpBB))
2736 continue;
2737
2738 Instruction *OpI = dyn_cast<Instruction>(Op);
2739 if (OpI) {
2740 BasicBlock *OpIBB = OpI->getParent();
2741 // As we pretend there is a use (or more precise a write) of OpI in OpBB
2742 // we have to insert a scalar dependence from the definition of OpI to
2743 // OpBB if the definition is not in OpBB.
2744 if (OpIBB != OpBB) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00002745 addMemoryAccess(OpBB, PHI, MemoryAccess::READ, OpI, ZeroOffset, 1, true,
2746 OpI);
2747 addMemoryAccess(OpIBB, OpI, MemoryAccess::MUST_WRITE, OpI, ZeroOffset,
2748 1, true, OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00002749 }
2750 }
2751
2752 // Always use the terminator of the incoming basic block as the access
2753 // instruction.
2754 OpI = OpBB->getTerminator();
2755
Michael Krusee2bccbb2015-09-18 19:59:43 +00002756 addMemoryAccess(OpBB, OpI, MemoryAccess::MUST_WRITE, PHI, ZeroOffset, 1,
2757 true, Op, /* IsPHI */ !IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002758 }
2759
2760 if (!OnlyNonAffineSubRegionOperands) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00002761 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, ZeroOffset,
2762 1, true, PHI,
2763 /* IsPHI */ !IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002764 }
2765}
2766
Michael Krused868b5d2015-09-10 15:25:24 +00002767bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
2768 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002769 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
2770 if (isIgnoredIntrinsic(Inst))
2771 return false;
2772
2773 bool AnyCrossStmtUse = false;
2774 BasicBlock *ParentBB = Inst->getParent();
2775
2776 for (User *U : Inst->users()) {
2777 Instruction *UI = dyn_cast<Instruction>(U);
2778
2779 // Ignore the strange user
2780 if (UI == 0)
2781 continue;
2782
2783 BasicBlock *UseParent = UI->getParent();
2784
2785 // Ignore the users in the same BB (statement)
2786 if (UseParent == ParentBB)
2787 continue;
2788
2789 // Do not build scalar dependences inside a non-affine subregion.
2790 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
2791 continue;
2792
2793 // Check whether or not the use is in the SCoP.
2794 if (!R->contains(UseParent)) {
2795 AnyCrossStmtUse = true;
2796 continue;
2797 }
2798
2799 // If the instruction can be synthesized and the user is in the region
2800 // we do not need to add scalar dependences.
2801 if (canSynthesizeInst)
2802 continue;
2803
2804 // No need to translate these scalar dependences into polyhedral form,
2805 // because synthesizable scalars can be generated by the code generator.
2806 if (canSynthesize(UI, LI, SE, R))
2807 continue;
2808
2809 // Skip PHI nodes in the region as they handle their operands on their own.
2810 if (isa<PHINode>(UI))
2811 continue;
2812
2813 // Now U is used in another statement.
2814 AnyCrossStmtUse = true;
2815
2816 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00002817 // Use the def instruction as base address of the MemoryAccess, so that it
2818 // will become the name of the scalar access in the polyhedral form.
2819 addMemoryAccess(UseParent, UI, MemoryAccess::READ, Inst, ZeroOffset, 1,
2820 true, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00002821 }
2822
2823 if (ModelReadOnlyScalars) {
2824 for (Value *Op : Inst->operands()) {
2825 if (canSynthesize(Op, LI, SE, R))
2826 continue;
2827
2828 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
2829 if (R->contains(OpInst))
2830 continue;
2831
2832 if (isa<Constant>(Op))
2833 continue;
2834
Michael Krusee2bccbb2015-09-18 19:59:43 +00002835 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::READ, Op,
2836 ZeroOffset, 1, true, Op);
Michael Kruse7bf39442015-09-10 12:46:52 +00002837 }
2838 }
2839
2840 return AnyCrossStmtUse;
2841}
2842
2843extern MapInsnToMemAcc InsnToMemAcc;
2844
Michael Krusee2bccbb2015-09-18 19:59:43 +00002845void ScopInfo::buildMemoryAccess(
2846 Instruction *Inst, Loop *L, Region *R,
2847 const ScopDetection::BoxedLoopsSetTy *BoxedLoops) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002848 unsigned Size;
2849 Type *SizeType;
2850 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00002851 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00002852
2853 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
2854 SizeType = Load->getType();
2855 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002856 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00002857 Val = Load;
2858 } else {
2859 StoreInst *Store = cast<StoreInst>(Inst);
2860 SizeType = Store->getValueOperand()->getType();
2861 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002862 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00002863 Val = Store->getValueOperand();
2864 }
2865
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002866 auto Address = getPointerOperand(*Inst);
2867
2868 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00002869 const SCEVUnknown *BasePointer =
2870 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
2871
2872 assert(BasePointer && "Could not find base pointer");
2873 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
2874
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002875 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
2876 auto NewAddress = Address;
2877 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
2878 auto Src = BitCast->getOperand(0);
2879 auto SrcTy = Src->getType();
2880 auto DstTy = BitCast->getType();
2881 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
2882 NewAddress = Src;
2883 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002884
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002885 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
2886 std::vector<const SCEV *> Subscripts;
2887 std::vector<int> Sizes;
2888 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
2889 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002890
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002891 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002892
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002893 bool AllAffineSubcripts = true;
2894 for (auto Subscript : Subscripts)
2895 if (!isAffineExpr(R, Subscript, *SE)) {
2896 AllAffineSubcripts = false;
2897 break;
2898 }
2899
2900 if (AllAffineSubcripts && Sizes.size() > 0) {
2901 for (auto V : Sizes)
2902 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
2903 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002904 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002905 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002906
Michael Krusee2bccbb2015-09-18 19:59:43 +00002907 addMemoryAccess(Inst->getParent(), Inst, Type, BasePointer->getValue(),
2908 AccessFunction, Size, true, Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00002909 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002910 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002911 }
2912 }
2913
Michael Kruse7bf39442015-09-10 12:46:52 +00002914 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002915 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
2916 addMemoryAccess(Inst->getParent(), Inst, Type, BasePointer->getValue(),
2917 AccessFunction, Size, true,
Michael Kruse7bf39442015-09-10 12:46:52 +00002918 AccItr->second.DelinearizedSubscripts,
2919 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002920 return;
2921 }
Michael Kruse7bf39442015-09-10 12:46:52 +00002922
2923 // Check if the access depends on a loop contained in a non-affine subregion.
2924 bool isVariantInNonAffineLoop = false;
2925 if (BoxedLoops) {
2926 SetVector<const Loop *> Loops;
2927 findLoops(AccessFunction, Loops);
2928 for (const Loop *L : Loops)
2929 if (BoxedLoops->count(L))
2930 isVariantInNonAffineLoop = true;
2931 }
2932
2933 bool IsAffine = !isVariantInNonAffineLoop &&
2934 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue());
2935
2936 SmallVector<const SCEV *, 4> Subscripts, Sizes;
2937 Subscripts.push_back(AccessFunction);
2938 Sizes.push_back(SE->getConstant(ZeroOffset->getType(), Size));
2939
Michael Krusee2bccbb2015-09-18 19:59:43 +00002940 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
2941 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00002942
Michael Krusee2bccbb2015-09-18 19:59:43 +00002943 addMemoryAccess(Inst->getParent(), Inst, Type, BasePointer->getValue(),
2944 AccessFunction, Size, IsAffine, Subscripts, Sizes, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00002945}
2946
Michael Krused868b5d2015-09-10 15:25:24 +00002947void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002948
2949 if (SD->isNonAffineSubRegion(&SR, &R)) {
2950 for (BasicBlock *BB : SR.blocks())
2951 buildAccessFunctions(R, *BB, &SR);
2952 return;
2953 }
2954
2955 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
2956 if (I->isSubRegion())
2957 buildAccessFunctions(R, *I->getNodeAs<Region>());
2958 else
2959 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
2960}
2961
Michael Krused868b5d2015-09-10 15:25:24 +00002962void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
2963 Region *NonAffineSubRegion,
2964 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002965 Loop *L = LI->getLoopFor(&BB);
2966
2967 // The set of loops contained in non-affine subregions that are part of R.
2968 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
2969
2970 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
2971 Instruction *Inst = I;
2972
2973 PHINode *PHI = dyn_cast<PHINode>(Inst);
2974 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00002975 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002976
2977 // For the exit block we stop modeling after the last PHI node.
2978 if (!PHI && IsExitBlock)
2979 break;
2980
2981 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Michael Krusee2bccbb2015-09-18 19:59:43 +00002982 buildMemoryAccess(Inst, L, &R, BoxedLoops);
Michael Kruse7bf39442015-09-10 12:46:52 +00002983
2984 if (isIgnoredIntrinsic(Inst))
2985 continue;
2986
2987 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00002988 if (!isa<StoreInst>(Inst))
2989 addMemoryAccess(&BB, Inst, MemoryAccess::MUST_WRITE, Inst, ZeroOffset,
2990 1, true, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00002991 }
2992 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00002993}
Michael Kruse7bf39442015-09-10 12:46:52 +00002994
Michael Krusee2bccbb2015-09-18 19:59:43 +00002995void ScopInfo::addMemoryAccess(
2996 BasicBlock *BB, Instruction *Inst, MemoryAccess::AccessType Type,
2997 Value *BaseAddress, const SCEV *Offset, unsigned ElemBytes, bool Affine,
2998 Value *AccessValue, ArrayRef<const SCEV *> Subscripts,
2999 ArrayRef<const SCEV *> Sizes, bool IsPHI = false) {
3000 AccFuncSetType &AccList = AccFuncMap[BB];
3001 size_t Identifier = AccList.size();
Michael Kruse7bf39442015-09-10 12:46:52 +00003002
Michael Krusee2bccbb2015-09-18 19:59:43 +00003003 Value *BaseAddr = BaseAddress;
3004 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3005
3006 std::string IdName = "__polly_array_ref_" + std::to_string(Identifier);
3007 isl_id *Id = isl_id_alloc(ctx, IdName.c_str(), nullptr);
3008
3009 AccList.emplace_back(Inst, Id, Type, BaseAddress, Offset, ElemBytes, Affine,
3010 Subscripts, Sizes, AccessValue, IsPHI, BaseName);
Michael Kruse7bf39442015-09-10 12:46:52 +00003011}
3012
Michael Kruse9d080092015-09-11 21:41:48 +00003013Scop *ScopInfo::buildScop(Region &R, DominatorTree &DT) {
3014 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
3015 Scop *S = new Scop(R, AccFuncMap, *SE, DT, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003016
3017 buildAccessFunctions(R, R);
3018
3019 // In case the region does not have an exiting block we will later (during
3020 // code generation) split the exit block. This will move potential PHI nodes
3021 // from the current exit block into the new region exiting block. Hence, PHI
3022 // nodes that are at this point not part of the region will be.
3023 // To handle these PHI nodes later we will now model their operands as scalar
3024 // accesses. Note that we do not model anything in the exit block if we have
3025 // an exiting block in the region, as there will not be any splitting later.
3026 if (!R.getExitingBlock())
3027 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3028
Michael Kruse9d080092015-09-11 21:41:48 +00003029 S->init(*LI, *SD, *AA);
3030 return S;
Michael Kruse7bf39442015-09-10 12:46:52 +00003031}
3032
Michael Krused868b5d2015-09-10 15:25:24 +00003033void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003034 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003035 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003036 return;
3037 }
3038
3039 scop->printIRAccesses(OS, SE, LI);
3040 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003041}
3042
Michael Krused868b5d2015-09-10 15:25:24 +00003043void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003044 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003045 if (scop) {
3046 delete scop;
3047 scop = 0;
3048 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003049}
3050
3051//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003052ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003053 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003054 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003055}
3056
3057ScopInfo::~ScopInfo() {
3058 clear();
3059 isl_ctx_free(ctx);
3060}
3061
Tobias Grosser75805372011-04-29 06:27:02 +00003062void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Michael Krused868b5d2015-09-10 15:25:24 +00003063 AU.addRequiredID(IndependentBlocksID);
Chandler Carruthf5579872015-01-17 14:16:56 +00003064 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003065 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003066 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003067 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3068 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003069 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003070 AU.setPreservesAll();
3071}
3072
3073bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003074 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003075
Michael Krused868b5d2015-09-10 15:25:24 +00003076 if (!SD->isMaxRegionInScop(*R))
3077 return false;
3078
3079 Function *F = R->getEntry()->getParent();
3080 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3081 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3082 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3083 TD = &F->getParent()->getDataLayout();
3084 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3085 ZeroOffset = SE->getConstant(TD->getIntPtrType(F->getContext()), 0);
3086
Michael Kruse9d080092015-09-11 21:41:48 +00003087 scop = buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003088
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003089 DEBUG(scop->print(dbgs()));
3090
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003091 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003092 delete scop;
3093 scop = nullptr;
3094 return false;
3095 }
3096
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003097 // Statistics.
3098 ++ScopFound;
3099 if (scop->getMaxLoopDepth() > 0)
3100 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003101 return false;
3102}
3103
3104char ScopInfo::ID = 0;
3105
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003106Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3107
Tobias Grosser73600b82011-10-08 00:30:40 +00003108INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3109 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003110 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003111INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003112INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003113INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003114INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003115INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003116INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003117INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3118 "Polly - Create polyhedral description of Scops", false,
3119 false)